12 "github.com/RoaringBitmap/roaring"
13 g "github.com/anacrolix/generics"
14 "github.com/anacrolix/generics/heap"
15 "github.com/anacrolix/log"
16 "github.com/anacrolix/multiless"
18 requestStrategy "github.com/anacrolix/torrent/request-strategy"
19 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
23 // Since we have to store all the requests in memory, we can't reasonably exceed what could be
24 // indexed with the memory space available.
28 func (t *Torrent) requestStrategyPieceOrderState(i int) requestStrategy.PieceRequestOrderState {
29 return requestStrategy.PieceRequestOrderState{
30 Priority: t.piece(i).purePriority(),
31 Partial: t.piecePartiallyDownloaded(i),
32 Availability: t.piece(i).availability(),
37 gob.Register(peerId{})
45 func (p peerId) Uintptr() uintptr {
49 func (p peerId) GobEncode() (b []byte, _ error) {
50 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
51 Data: uintptr(unsafe.Pointer(&p.ptr)),
52 Len: int(unsafe.Sizeof(p.ptr)),
53 Cap: int(unsafe.Sizeof(p.ptr)),
58 func (p *peerId) GobDecode(b []byte) error {
59 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
62 ptr := unsafe.Pointer(&b[0])
63 p.ptr = *(*uintptr)(ptr)
65 dst := reflect.SliceHeader{
66 Data: uintptr(unsafe.Pointer(&p.Peer)),
67 Len: int(unsafe.Sizeof(p.Peer)),
68 Cap: int(unsafe.Sizeof(p.Peer)),
70 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
75 RequestIndex = requestStrategy.RequestIndex
76 chunkIndexType = requestStrategy.ChunkIndex
79 type desiredPeerRequests struct {
80 requestIndexes []RequestIndex
82 pieceStates []g.Option[requestStrategy.PieceRequestOrderState]
85 func (p *desiredPeerRequests) lessByValue(leftRequest, rightRequest RequestIndex) bool {
87 leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
88 rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
90 // Push requests that can't be served right now to the end. But we don't throw them away unless
91 // there's a better alternative. This is for when we're using the fast extension and get choked
92 // but our requests could still be good when we get unchoked.
93 if p.peer.peerChoking {
95 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
96 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
99 leftPiece := p.pieceStates[leftPieceIndex].UnwrapPtr()
100 rightPiece := p.pieceStates[rightPieceIndex].UnwrapPtr()
101 // Putting this first means we can steal requests from lesser-performing peers for our first few
103 priority := func() PiecePriority {
104 // Technically we would be happy with the cached priority here, except we don't actually
105 // cache it anymore, and Torrent.PiecePriority just does another lookup of *Piece to resolve
106 // the priority through Piece.purePriority, which is probably slower.
107 leftPriority := leftPiece.Priority
108 rightPriority := rightPiece.Priority
114 if leftPriority != rightPriority {
115 panic("expected equal")
123 leftRequestState := t.requestState[leftRequest]
124 rightRequestState := t.requestState[rightRequest]
125 leftPeer := leftRequestState.peer
126 rightPeer := rightRequestState.peer
127 // Prefer chunks already requested from this peer.
128 ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
129 // Prefer unrequested chunks.
130 ml = ml.Bool(rightPeer == nil, leftPeer == nil)
135 // The right peer should also be set, or we'd have resolved the computation by now.
137 rightPeer.requestState.Requests.GetCardinality(),
138 leftPeer.requestState.Requests.GetCardinality(),
140 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
141 leftLast := leftRequestState.when
142 rightLast := rightRequestState.when
143 if leftLast.IsZero() || rightLast.IsZero() {
144 panic("expected non-zero last requested times")
146 // We want the most-recently requested on the left. Clients like Transmission serve requests
147 // in received order, so the most recently-requested is the one that has the longest until
148 // it will be served and therefore is the best candidate to cancel.
149 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
152 leftPiece.Availability,
153 rightPiece.Availability)
154 if priority == PiecePriorityReadahead {
155 // TODO: For readahead in particular, it would be even better to consider distance from the
156 // reader position so that reads earlier in a torrent don't starve reads later in the
157 // torrent. This would probably require reconsideration of how readahead priority works.
158 ml = ml.Int(leftPieceIndex, rightPieceIndex)
160 ml = ml.Int(t.pieceRequestOrder[leftPieceIndex], t.pieceRequestOrder[rightPieceIndex])
165 type desiredRequestState struct {
166 Requests desiredPeerRequests
170 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
175 if t.closed.IsSet() {
178 if t.dataDownloadDisallowed.Bool() {
181 input := t.getRequestStrategyInput()
182 requestHeap := desiredPeerRequests{
184 pieceStates: t.requestPieceStates,
185 requestIndexes: t.requestIndexes,
187 clear(requestHeap.pieceStates)
188 // Caller-provided allocation for roaring bitmap iteration.
189 var it typedRoaring.Iterator[RequestIndex]
190 requestStrategy.GetRequestablePieces(
192 t.getPieceRequestOrder(),
193 func(ih InfoHash, pieceIndex int, pieceExtra requestStrategy.PieceRequestOrderState) bool {
194 if ih != *t.canonicalShortInfohash() {
197 if !p.peerHasPiece(pieceIndex) {
200 requestHeap.pieceStates[pieceIndex].Set(pieceExtra)
201 allowedFast := p.peerAllowedFast.Contains(pieceIndex)
202 t.iterUndirtiedRequestIndexesInPiece(&it, pieceIndex, func(r requestStrategy.RequestIndex) {
204 // We must signal interest to request this. TODO: We could set interested if the
205 // peers pieces (minus the allowed fast set) overlap with our missing pieces if
206 // there are any readers, or any pending pieces.
207 desired.Interested = true
208 // We can make or will allow sustaining a request here if we're not choked, or
209 // have made the request previously (presumably while unchoked), and haven't had
210 // the peer respond yet (and the request was retained because we are using the
212 if p.peerChoking && !p.requestState.Requests.Contains(r) {
213 // We can't request this right now.
217 cancelled := &p.requestState.Cancelled
218 if !cancelled.IsEmpty() && cancelled.Contains(r) {
219 // Can't re-request while awaiting acknowledgement.
222 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
227 t.assertPendingRequests()
228 desired.Requests = requestHeap
232 func (p *Peer) maybeUpdateActualRequestState() {
233 if p.closed.IsSet() {
236 if p.needRequestUpdate == "" {
239 if p.needRequestUpdate == peerUpdateRequestsTimerReason {
240 since := time.Since(p.lastRequestUpdate)
241 if since < updateRequestsTimerDuration {
246 context.Background(),
247 pprof.Labels("update request", p.needRequestUpdate),
248 func(_ context.Context) {
249 next := p.getDesiredRequestState()
250 p.applyRequestState(next)
251 p.t.cacheNextRequestIndexesForReuse(next.Requests.requestIndexes)
256 func (t *Torrent) cacheNextRequestIndexesForReuse(slice []RequestIndex) {
257 // The incoming slice can be smaller when getDesiredRequestState short circuits on some
259 if cap(slice) > cap(t.requestIndexes) {
260 t.requestIndexes = slice[:0]
264 // Whether we should allow sending not interested ("losing interest") to the peer. I noticed
265 // qBitTorrent seems to punish us for sending not interested when we're streaming and don't
266 // currently need anything.
267 func (p *Peer) allowSendNotInterested() bool {
268 // Except for caching, we're not likely to lose pieces very soon.
269 if p.t.haveAllPieces() {
272 all, known := p.peerHasAllPieces()
276 // Allow losing interest if we have all the pieces the peer has.
277 return roaring.AndNot(p.peerPieces(), &p.t._completedPieces).IsEmpty()
280 // Transmit/action the request state to the peer.
281 func (p *Peer) applyRequestState(next desiredRequestState) {
282 current := &p.requestState
283 // Make interest sticky
284 if !next.Interested && p.requestState.Interested {
285 if !p.allowSendNotInterested() {
286 next.Interested = true
289 if !p.setInterested(next.Interested) {
293 orig := next.Requests.requestIndexes
294 requestHeap := heap.InterfaceForSlice(
295 &next.Requests.requestIndexes,
296 next.Requests.lessByValue,
298 heap.Init(requestHeap)
301 originalRequestCount := current.Requests.GetCardinality()
303 if requestHeap.Len() == 0 {
306 numPending := maxRequests(current.Requests.GetCardinality() + current.Cancelled.GetCardinality())
307 if numPending >= p.nominalMaxRequests() {
310 req := heap.Pop(requestHeap)
311 if cap(next.Requests.requestIndexes) != cap(orig) {
314 existing := t.requestingPeer(req)
315 if existing != nil && existing != p {
316 // Don't steal from the poor.
317 diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
318 // Steal a request that leaves us with one more request than the existing peer
319 // connection if the stealer more recently received a chunk.
320 if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
325 more = p.mustRequest(req)
331 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
332 // requests into the available write buffer space. We don't want that to happen because it
333 // makes our peak requests dependent on how much was already in the buffer.
335 "couldn't fill apply entire request state [newRequests=%v]",
336 current.Requests.GetCardinality()-originalRequestCount))
338 newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
340 // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
341 // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
342 p.peakRequests = newPeakRequests
343 p.needRequestUpdate = ""
344 p.lastRequestUpdate = time.Now()
345 if enableUpdateRequestsTimer {
346 p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
350 // This could be set to 10s to match the unchoke/request update interval recommended by some
351 // specifications. I've set it shorter to trigger it more often for testing for now.
353 updateRequestsTimerDuration = 3 * time.Second
354 enableUpdateRequestsTimer = false