torrent/requesting.go

238 lines
5.8 KiB
Go
Raw Normal View History

package torrent
import (
"time"
2021-05-09 14:53:32 +00:00
"unsafe"
2021-05-20 01:16:54 +00:00
"github.com/anacrolix/missinggo/v2/bitmap"
"github.com/anacrolix/chansync"
request_strategy "github.com/anacrolix/torrent/request-strategy"
)
// Calculate requests individually for each peer.
const peerRequesting = true
func (cl *Client) requester() {
for {
update := func() chansync.Signaled {
cl.lock()
defer cl.unlock()
cl.doRequests()
return cl.updateRequests.Signaled()
}()
2021-09-15 14:12:58 +00:00
minWait := time.After(100 * time.Millisecond)
maxWait := time.After(1000 * time.Millisecond)
select {
case <-cl.closed.Done():
return
2021-09-15 14:12:58 +00:00
case <-minWait:
case <-maxWait:
}
select {
case <-cl.closed.Done():
return
case <-update:
2021-09-15 14:12:58 +00:00
case <-maxWait:
}
}
}
func (cl *Client) tickleRequester() {
cl.updateRequests.Broadcast()
}
func (cl *Client) getRequestStrategyInput() request_strategy.Input {
2021-05-14 03:06:12 +00:00
ts := make([]request_strategy.Torrent, 0, len(cl.torrents))
for _, t := range cl.torrents {
2021-09-19 05:16:37 +00:00
if !t.haveInfo() {
// This would be removed if metadata is handled here. We have to guard against not
// knowing the piece size. If we have no info, we have no pieces too, so the end result
// is the same.
2021-09-19 05:16:37 +00:00
continue
}
2021-05-14 03:06:12 +00:00
rst := request_strategy.Torrent{
2021-09-19 05:16:37 +00:00
InfoHash: t.infoHash,
ChunksPerPiece: (t.usualPieceSize() + int(t.chunkSize) - 1) / int(t.chunkSize),
}
if t.storage != nil {
rst.Capacity = t.storage.Capacity
}
2021-09-11 11:17:31 +00:00
rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
for i := range t.pieces {
p := &t.pieces[i]
rst.Pieces = append(rst.Pieces, request_strategy.Piece{
2021-09-11 11:17:47 +00:00
Request: !t.ignorePieceForRequests(i),
Priority: p.purePriority(),
Partial: t.piecePartiallyDownloaded(i),
Availability: p.availability,
Length: int64(p.length()),
NumPendingChunks: int(t.pieceNumPendingChunks(i)),
IterPendingChunks: p.iterUndirtiedChunks,
})
}
t.iterPeers(func(p *Peer) {
if p.closed.IsSet() {
return
}
if p.piecesReceivedSinceLastRequestUpdate > p.maxPiecesReceivedBetweenRequestUpdates {
p.maxPiecesReceivedBetweenRequestUpdates = p.piecesReceivedSinceLastRequestUpdate
}
p.piecesReceivedSinceLastRequestUpdate = 0
2021-05-13 01:26:22 +00:00
rst.Peers = append(rst.Peers, request_strategy.Peer{
HasPiece: p.peerHasPiece,
2021-05-13 01:26:22 +00:00
MaxRequests: p.nominalMaxRequests(),
2021-09-19 05:16:37 +00:00
HasExistingRequest: func(r RequestIndex) bool {
return p.actualRequestState.Requests.Contains(r)
},
Choking: p.peerChoking,
PieceAllowedFast: func(i pieceIndex) bool {
2021-05-20 01:16:54 +00:00
return p.peerAllowedFast.Contains(bitmap.BitIndex(i))
},
DownloadRate: p.downloadRate(),
Age: time.Since(p.completedHandshake),
Id: peerId{
Peer: p,
ptr: uintptr(unsafe.Pointer(p)),
},
})
})
ts = append(ts, rst)
}
return request_strategy.Input{
2021-05-14 03:40:09 +00:00
Torrents: ts,
MaxUnverifiedBytes: cl.config.MaxUnverifiedBytes,
}
}
func (cl *Client) doRequests() {
nextPeerStates := request_strategy.Run(cl.getRequestStrategyInput())
for p, state := range nextPeerStates {
setPeerNextRequestState(p, state)
}
}
type peerId struct {
*Peer
ptr uintptr
}
2021-05-13 01:26:22 +00:00
func (p peerId) Uintptr() uintptr {
return p.ptr
2021-05-13 01:26:22 +00:00
}
func setPeerNextRequestState(_p request_strategy.PeerId, rp request_strategy.PeerNextRequestState) {
p := _p.(peerId).Peer
p.nextRequestState = rp
p.onNextRequestStateChanged()
}
2021-09-19 05:16:37 +00:00
type RequestIndex = request_strategy.RequestIndex
type chunkIndexType = request_strategy.ChunkIndex
func (p *Peer) applyNextRequestState() bool {
if peerRequesting {
if p.actualRequestState.Requests.GetCardinality() > uint64(p.nominalMaxRequests()/2) {
return true
}
type piece struct {
index int
endGame bool
}
var pieceOrder []piece
request_strategy.GetRequestablePieces(
p.t.cl.getRequestStrategyInput(),
func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
if t.InfoHash != p.t.infoHash {
return
}
if !p.peerHasPiece(pieceIndex) {
return
}
pieceOrder = append(pieceOrder, piece{
index: pieceIndex,
endGame: rsp.Priority == PiecePriorityNow,
})
},
)
more := true
interested := false
for _, endGameIter := range []bool{false, true} {
for _, piece := range pieceOrder {
tp := p.t.piece(piece.index)
tp.iterUndirtiedChunks(func(cs chunkIndexType) {
req := cs + tp.requestIndexOffset()
if !piece.endGame && !endGameIter && p.t.pendingRequests[req] > 0 {
return
}
interested = true
more = p.setInterested(true)
if !more {
return
}
if maxRequests(p.actualRequestState.Requests.GetCardinality()) >= p.nominalMaxRequests() {
return
}
if p.peerChoking && !p.peerAllowedFast.Contains(bitmap.BitIndex(piece.index)) {
return
}
var err error
more, err = p.request(req)
if err != nil {
panic(err)
}
})
if interested && maxRequests(p.actualRequestState.Requests.GetCardinality()) >= p.nominalMaxRequests() {
break
}
if !more {
break
}
}
if !more {
break
}
}
if !more {
return false
}
if !interested {
p.setInterested(false)
}
return more
}
next := p.nextRequestState
current := p.actualRequestState
if !p.setInterested(next.Interested) {
return false
}
more := true
current.Requests.Iterate(func(req uint32) bool {
if !next.Requests.Contains(req) {
more = p.cancel(req)
return more
}
return true
})
if !more {
return false
}
next.Requests.Iterate(func(req uint32) bool {
// This could happen if the peer chokes us between the next state being generated, and us
// trying to transmit the state.
if p.peerChoking && !p.peerAllowedFast.Contains(bitmap.BitIndex(req/p.t.chunksPerRegularPiece())) {
return true
}
var err error
more, err = p.request(req)
if err != nil {
panic(err)
} /* else {
log.Print(req)
} */
return more
})
return more
}