12 "github.com/anacrolix/log"
13 "github.com/anacrolix/multiless"
14 "github.com/lispad/go-generics-tools/binheap"
16 request_strategy "github.com/anacrolix/torrent/request-strategy"
19 func (t *Torrent) requestStrategyPieceOrderState(i int) request_strategy.PieceRequestOrderState {
20 return request_strategy.PieceRequestOrderState{
21 Priority: t.piece(i).purePriority(),
22 Partial: t.piecePartiallyDownloaded(i),
23 Availability: t.piece(i).availability(),
28 gob.Register(peerId{})
36 func (p peerId) Uintptr() uintptr {
40 func (p peerId) GobEncode() (b []byte, _ error) {
41 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
42 Data: uintptr(unsafe.Pointer(&p.ptr)),
43 Len: int(unsafe.Sizeof(p.ptr)),
44 Cap: int(unsafe.Sizeof(p.ptr)),
49 func (p *peerId) GobDecode(b []byte) error {
50 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
53 ptr := unsafe.Pointer(&b[0])
54 p.ptr = *(*uintptr)(ptr)
56 dst := reflect.SliceHeader{
57 Data: uintptr(unsafe.Pointer(&p.Peer)),
58 Len: int(unsafe.Sizeof(p.Peer)),
59 Cap: int(unsafe.Sizeof(p.Peer)),
61 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
66 RequestIndex = request_strategy.RequestIndex
67 chunkIndexType = request_strategy.ChunkIndex
70 type desiredPeerRequests struct {
71 requestIndexes []RequestIndex
75 func (p *desiredPeerRequests) Len() int {
76 return len(p.requestIndexes)
79 func (p *desiredPeerRequests) Less(i, j int) bool {
80 return p.lessByValue(p.requestIndexes[i], p.requestIndexes[j])
83 func (p *desiredPeerRequests) lessByValue(leftRequest, rightRequest RequestIndex) bool {
85 leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
86 rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
88 // Push requests that can't be served right now to the end. But we don't throw them away unless
89 // there's a better alternative. This is for when we're using the fast extension and get choked
90 // but our requests could still be good when we get unchoked.
91 if p.peer.peerChoking {
93 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
94 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
97 leftPiece := t.piece(leftPieceIndex)
98 rightPiece := t.piece(rightPieceIndex)
99 // Putting this first means we can steal requests from lesser-performing peers for our first few
101 priority := func() piecePriority {
102 // Technically we would be happy with the cached priority here, except we don't actually
103 // cache it anymore, and Torrent.piecePriority just does another lookup of *Piece to resolve
104 // the priority through Piece.purePriority, which is probably slower.
105 leftPriority := leftPiece.purePriority()
106 rightPriority := rightPiece.purePriority()
112 if leftPriority != rightPriority {
113 panic("expected equal")
121 leftRequestState := t.requestState[leftRequest]
122 rightRequestState := t.requestState[rightRequest]
123 leftPeer := leftRequestState.peer
124 rightPeer := rightRequestState.peer
125 // Prefer chunks already requested from this peer.
126 ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
127 // Prefer unrequested chunks.
128 ml = ml.Bool(rightPeer == nil, leftPeer == nil)
133 // The right peer should also be set, or we'd have resolved the computation by now.
135 rightPeer.requestState.Requests.GetCardinality(),
136 leftPeer.requestState.Requests.GetCardinality(),
138 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
139 leftLast := leftRequestState.when
140 rightLast := rightRequestState.when
141 if leftLast.IsZero() || rightLast.IsZero() {
142 panic("expected non-zero last requested times")
144 // We want the most-recently requested on the left. Clients like Transmission serve requests
145 // in received order, so the most recently-requested is the one that has the longest until
146 // it will be served and therefore is the best candidate to cancel.
147 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
150 leftPiece.relativeAvailability,
151 rightPiece.relativeAvailability)
152 if priority == PiecePriorityReadahead {
153 // TODO: For readahead in particular, it would be even better to consider distance from the
154 // reader position so that reads earlier in a torrent don't starve reads later in the
155 // torrent. This would probably require reconsideration of how readahead priority works.
156 ml = ml.Int(leftPieceIndex, rightPieceIndex)
158 // TODO: To prevent unnecessarily requesting from disparate pieces, and to ensure pieces are
159 // selected randomly when availability is even, there should be some fixed ordering of
165 func (p *desiredPeerRequests) Swap(i, j int) {
166 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
169 func (p *desiredPeerRequests) Push(x interface{}) {
170 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
173 func (p *desiredPeerRequests) Pop() interface{} {
174 last := len(p.requestIndexes) - 1
175 x := p.requestIndexes[last]
176 p.requestIndexes = p.requestIndexes[:last]
180 type desiredRequestState struct {
181 Requests desiredPeerRequests
185 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
189 if p.t.closed.IsSet() {
192 input := p.t.getRequestStrategyInput()
193 requestHeap := desiredPeerRequests{
196 request_strategy.GetRequestablePieces(
198 p.t.getPieceRequestOrder(),
199 func(ih InfoHash, pieceIndex int) {
200 if ih != p.t.infoHash {
203 if !p.peerHasPiece(pieceIndex) {
206 allowedFast := p.peerAllowedFast.Contains(pieceIndex)
207 p.t.piece(pieceIndex).undirtiedChunksIter.Iter(func(ci request_strategy.ChunkIndex) {
208 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
210 // We must signal interest to request this. TODO: We could set interested if the
211 // peers pieces (minus the allowed fast set) overlap with our missing pieces if
212 // there are any readers, or any pending pieces.
213 desired.Interested = true
214 // We can make or will allow sustaining a request here if we're not choked, or
215 // have made the request previously (presumably while unchoked), and haven't had
216 // the peer respond yet (and the request was retained because we are using the
218 if p.peerChoking && !p.requestState.Requests.Contains(r) {
219 // We can't request this right now.
223 if p.requestState.Cancelled.Contains(r) {
224 // Can't re-request while awaiting acknowledgement.
227 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
231 p.t.assertPendingRequests()
232 desired.Requests = requestHeap
236 func (p *Peer) maybeUpdateActualRequestState() {
237 if p.closed.IsSet() {
240 if p.needRequestUpdate == "" {
243 if p.needRequestUpdate == peerUpdateRequestsTimerReason {
244 since := time.Since(p.lastRequestUpdate)
245 if since < updateRequestsTimerDuration {
250 context.Background(),
251 pprof.Labels("update request", p.needRequestUpdate),
252 func(_ context.Context) {
253 next := p.getDesiredRequestState()
254 p.applyRequestState(next)
259 // Transmit/action the request state to the peer.
260 func (p *Peer) applyRequestState(next desiredRequestState) {
261 current := &p.requestState
262 if !p.setInterested(next.Interested) {
263 panic("insufficient write buffer")
266 requestHeap := binheap.FromSlice(next.Requests.requestIndexes, next.Requests.lessByValue)
268 originalRequestCount := current.Requests.GetCardinality()
269 // We're either here on a timer, or because we ran out of requests. Both are valid reasons to
270 // alter peakRequests.
271 if originalRequestCount != 0 && p.needRequestUpdate != peerUpdateRequestsTimerReason {
273 "expected zero existing requests (%v) for update reason %q",
274 originalRequestCount, p.needRequestUpdate))
276 for requestHeap.Len() != 0 && maxRequests(current.Requests.GetCardinality()+current.Cancelled.GetCardinality()) < p.nominalMaxRequests() {
277 req := requestHeap.Pop()
278 existing := t.requestingPeer(req)
279 if existing != nil && existing != p {
280 // Don't steal from the poor.
281 diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
282 // Steal a request that leaves us with one more request than the existing peer
283 // connection if the stealer more recently received a chunk.
284 if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
289 more = p.mustRequest(req)
295 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
296 // requests into the available write buffer space. We don't want that to happen because it
297 // makes our peak requests dependent on how much was already in the buffer.
299 "couldn't fill apply entire request state [newRequests=%v]",
300 current.Requests.GetCardinality()-originalRequestCount))
302 newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
304 // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
305 // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
306 p.peakRequests = newPeakRequests
307 p.needRequestUpdate = ""
308 p.lastRequestUpdate = time.Now()
309 p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
312 // This could be set to 10s to match the unchoke/request update interval recommended by some
313 // specifications. I've set it shorter to trigger it more often for testing for now.
314 const updateRequestsTimerDuration = 3 * time.Second