]> Sergey Matveev's repositories - btrtrc.git/blob - requesting.go
cmd/btrtrc client
[btrtrc.git] / requesting.go
1 package torrent
2
3 import (
4         "context"
5         "encoding/gob"
6         "fmt"
7         "reflect"
8         "runtime/pprof"
9         "time"
10         "unsafe"
11
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"
17
18         requestStrategy "github.com/anacrolix/torrent/request-strategy"
19         typedRoaring "github.com/anacrolix/torrent/typed-roaring"
20 )
21
22 type (
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.
25         maxRequests = int
26 )
27
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(),
33         }
34 }
35
36 func init() {
37         gob.Register(peerId{})
38 }
39
40 type peerId struct {
41         *Peer
42         ptr uintptr
43 }
44
45 func (p peerId) Uintptr() uintptr {
46         return p.ptr
47 }
48
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)),
54         }
55         return
56 }
57
58 func (p *peerId) GobDecode(b []byte) error {
59         if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
60                 panic(len(b))
61         }
62         ptr := unsafe.Pointer(&b[0])
63         p.ptr = *(*uintptr)(ptr)
64         log.Printf("%p", 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)),
69         }
70         copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
71         return nil
72 }
73
74 type (
75         RequestIndex   = requestStrategy.RequestIndex
76         chunkIndexType = requestStrategy.ChunkIndex
77 )
78
79 type desiredPeerRequests struct {
80         requestIndexes []RequestIndex
81         peer           *Peer
82         pieceStates    []g.Option[requestStrategy.PieceRequestOrderState]
83 }
84
85 func (p *desiredPeerRequests) lessByValue(leftRequest, rightRequest RequestIndex) bool {
86         t := p.peer.t
87         leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
88         rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
89         ml := multiless.New()
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 {
94                 ml = ml.Bool(
95                         !p.peer.peerAllowedFast.Contains(leftPieceIndex),
96                         !p.peer.peerAllowedFast.Contains(rightPieceIndex),
97                 )
98         }
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
102         // new requests.
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
109                 ml = ml.Int(
110                         -int(leftPriority),
111                         -int(rightPriority),
112                 )
113                 if !ml.Ok() {
114                         if leftPriority != rightPriority {
115                                 panic("expected equal")
116                         }
117                 }
118                 return leftPriority
119         }()
120         if ml.Ok() {
121                 return ml.MustLess()
122         }
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)
131         if ml.Ok() {
132                 return ml.MustLess()
133         }
134         if leftPeer != nil {
135                 // The right peer should also be set, or we'd have resolved the computation by now.
136                 ml = ml.Uint64(
137                         rightPeer.requestState.Requests.GetCardinality(),
138                         leftPeer.requestState.Requests.GetCardinality(),
139                 )
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")
145                 }
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())
150         }
151         ml = ml.Int(
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)
159         } else {
160                 ml = ml.Int(t.pieceRequestOrder[leftPieceIndex], t.pieceRequestOrder[rightPieceIndex])
161         }
162         return ml.Less()
163 }
164
165 type desiredRequestState struct {
166         Requests   desiredPeerRequests
167         Interested bool
168 }
169
170 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
171         t := p.t
172         if !t.haveInfo() {
173                 return
174         }
175         if t.closed.IsSet() {
176                 return
177         }
178         if t.dataDownloadDisallowed.Bool() {
179                 return
180         }
181         input := t.getRequestStrategyInput()
182         requestHeap := desiredPeerRequests{
183                 peer:           p,
184                 pieceStates:    t.requestPieceStates,
185                 requestIndexes: t.requestIndexes,
186         }
187         clear(requestHeap.pieceStates)
188         // Caller-provided allocation for roaring bitmap iteration.
189         var it typedRoaring.Iterator[RequestIndex]
190         requestStrategy.GetRequestablePieces(
191                 input,
192                 t.getPieceRequestOrder(),
193                 func(ih InfoHash, pieceIndex int, pieceExtra requestStrategy.PieceRequestOrderState) bool {
194                         if ih != *t.canonicalShortInfohash() {
195                                 return false
196                         }
197                         if !p.peerHasPiece(pieceIndex) {
198                                 return false
199                         }
200                         requestHeap.pieceStates[pieceIndex].Set(pieceExtra)
201                         allowedFast := p.peerAllowedFast.Contains(pieceIndex)
202                         t.iterUndirtiedRequestIndexesInPiece(&it, pieceIndex, func(r requestStrategy.RequestIndex) {
203                                 if !allowedFast {
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
211                                         // fast extension).
212                                         if p.peerChoking && !p.requestState.Requests.Contains(r) {
213                                                 // We can't request this right now.
214                                                 return
215                                         }
216                                 }
217                                 cancelled := &p.requestState.Cancelled
218                                 if !cancelled.IsEmpty() && cancelled.Contains(r) {
219                                         // Can't re-request while awaiting acknowledgement.
220                                         return
221                                 }
222                                 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
223                         })
224                         return true
225                 },
226         )
227         t.assertPendingRequests()
228         desired.Requests = requestHeap
229         return
230 }
231
232 func (p *Peer) maybeUpdateActualRequestState() {
233         if p.closed.IsSet() {
234                 return
235         }
236         if p.needRequestUpdate == "" {
237                 return
238         }
239         if p.needRequestUpdate == peerUpdateRequestsTimerReason {
240                 since := time.Since(p.lastRequestUpdate)
241                 if since < updateRequestsTimerDuration {
242                         panic(since)
243                 }
244         }
245         pprof.Do(
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)
252                 },
253         )
254 }
255
256 func (t *Torrent) cacheNextRequestIndexesForReuse(slice []RequestIndex) {
257         // The incoming slice can be smaller when getDesiredRequestState short circuits on some
258         // conditions.
259         if cap(slice) > cap(t.requestIndexes) {
260                 t.requestIndexes = slice[:0]
261         }
262 }
263
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() {
270                 return true
271         }
272         all, known := p.peerHasAllPieces()
273         if all || !known {
274                 return false
275         }
276         // Allow losing interest if we have all the pieces the peer has.
277         return roaring.AndNot(p.peerPieces(), &p.t._completedPieces).IsEmpty()
278 }
279
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
287                 }
288         }
289         if !p.setInterested(next.Interested) {
290                 return
291         }
292         more := true
293         orig := next.Requests.requestIndexes
294         requestHeap := heap.InterfaceForSlice(
295                 &next.Requests.requestIndexes,
296                 next.Requests.lessByValue,
297         )
298         heap.Init(requestHeap)
299
300         t := p.t
301         originalRequestCount := current.Requests.GetCardinality()
302         for {
303                 if requestHeap.Len() == 0 {
304                         break
305                 }
306                 numPending := maxRequests(current.Requests.GetCardinality() + current.Cancelled.GetCardinality())
307                 if numPending >= p.nominalMaxRequests() {
308                         break
309                 }
310                 req := heap.Pop(requestHeap)
311                 if cap(next.Requests.requestIndexes) != cap(orig) {
312                         panic("changed")
313                 }
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)) {
321                                 continue
322                         }
323                         t.cancelRequest(req)
324                 }
325                 more = p.mustRequest(req)
326                 if !more {
327                         break
328                 }
329         }
330         if !more {
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.
334                 panic(fmt.Sprintf(
335                         "couldn't fill apply entire request state [newRequests=%v]",
336                         current.Requests.GetCardinality()-originalRequestCount))
337         }
338         newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
339         // log.Printf(
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)
347         }
348 }
349
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.
352 const (
353         updateRequestsTimerDuration = 3 * time.Second
354         enableUpdateRequestsTimer   = false
355 )