13 "github.com/anacrolix/log"
14 "github.com/anacrolix/multiless"
16 request_strategy "github.com/anacrolix/torrent/request-strategy"
19 // Returns what is necessary to run request_strategy.GetRequestablePieces for primaryTorrent.
20 func (cl *Client) getRequestStrategyInput(primaryTorrent *Torrent) (input request_strategy.Input) {
21 input.MaxUnverifiedBytes = cl.config.MaxUnverifiedBytes
22 if !primaryTorrent.haveInfo() {
25 if capFunc := primaryTorrent.storage.Capacity; capFunc != nil {
26 if cap, ok := (*capFunc)(); ok {
30 if input.Capacity == nil {
31 input.Torrents = []request_strategy.Torrent{primaryTorrent.requestStrategyTorrentInput()}
34 input.Torrents = make([]request_strategy.Torrent, 0, len(cl.torrents))
35 for _, t := range cl.torrents {
37 // This would be removed if metadata is handled here. Determining chunks per piece
38 // requires the info. If we have no info, we have no pieces too, so the end result is
42 if t.storage.Capacity != primaryTorrent.storage.Capacity {
45 input.Torrents = append(input.Torrents, t.requestStrategyTorrentInput())
50 func (t *Torrent) getRequestStrategyInput() request_strategy.Input {
51 return t.cl.getRequestStrategyInput(t)
54 func (t *Torrent) requestStrategyTorrentInput() request_strategy.Torrent {
55 rst := request_strategy.Torrent{
57 ChunksPerPiece: t.chunksPerRegularPiece(),
59 rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
60 for i := range t.pieces {
62 rst.Pieces = append(rst.Pieces, request_strategy.Piece{
63 Request: !t.ignorePieceForRequests(i),
64 Priority: p.purePriority(),
65 Partial: t.piecePartiallyDownloaded(i),
66 Availability: p.availability,
67 Length: int64(p.length()),
68 NumPendingChunks: int(t.pieceNumPendingChunks(i)),
69 IterPendingChunks: &p.undirtiedChunksIter,
76 gob.Register(peerId{})
84 func (p peerId) Uintptr() uintptr {
88 func (p peerId) GobEncode() (b []byte, _ error) {
89 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
90 Data: uintptr(unsafe.Pointer(&p.ptr)),
91 Len: int(unsafe.Sizeof(p.ptr)),
92 Cap: int(unsafe.Sizeof(p.ptr)),
97 func (p *peerId) GobDecode(b []byte) error {
98 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
101 ptr := unsafe.Pointer(&b[0])
102 p.ptr = *(*uintptr)(ptr)
103 log.Printf("%p", ptr)
104 dst := reflect.SliceHeader{
105 Data: uintptr(unsafe.Pointer(&p.Peer)),
106 Len: int(unsafe.Sizeof(p.Peer)),
107 Cap: int(unsafe.Sizeof(p.Peer)),
109 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
114 RequestIndex = request_strategy.RequestIndex
115 chunkIndexType = request_strategy.ChunkIndex
118 type peerRequests struct {
119 requestIndexes []RequestIndex
121 torrentStrategyInput *request_strategy.Torrent
124 func (p *peerRequests) Len() int {
125 return len(p.requestIndexes)
128 func (p *peerRequests) Less(i, j int) bool {
129 leftRequest := p.requestIndexes[i]
130 rightRequest := p.requestIndexes[j]
132 leftPieceIndex := leftRequest / p.torrentStrategyInput.ChunksPerPiece
133 rightPieceIndex := rightRequest / p.torrentStrategyInput.ChunksPerPiece
134 leftCurrent := p.peer.actualRequestState.Requests.Contains(leftRequest)
135 rightCurrent := p.peer.actualRequestState.Requests.Contains(rightRequest)
136 pending := func(index RequestIndex, current bool) int {
137 ret := t.pendingRequests.Get(index)
141 // See https://github.com/anacrolix/torrent/issues/679 for possible issues. This should be
148 ml := multiless.New()
149 // Push requests that can't be served right now to the end. But we don't throw them away unless
150 // there's a better alternative. This is for when we're using the fast extension and get choked
151 // but our requests could still be good when we get unchoked.
152 if p.peer.peerChoking {
154 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
155 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
159 pending(leftRequest, leftCurrent),
160 pending(rightRequest, rightCurrent))
161 ml = ml.Bool(!leftCurrent, !rightCurrent)
163 -int(p.torrentStrategyInput.Pieces[leftPieceIndex].Priority),
164 -int(p.torrentStrategyInput.Pieces[rightPieceIndex].Priority),
167 int(p.torrentStrategyInput.Pieces[leftPieceIndex].Availability),
168 int(p.torrentStrategyInput.Pieces[rightPieceIndex].Availability))
169 ml = ml.Uint32(leftPieceIndex, rightPieceIndex)
170 ml = ml.Uint32(leftRequest, rightRequest)
174 func (p *peerRequests) Swap(i, j int) {
175 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
178 func (p *peerRequests) Push(x interface{}) {
179 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
182 func (p *peerRequests) Pop() interface{} {
183 last := len(p.requestIndexes) - 1
184 x := p.requestIndexes[last]
185 p.requestIndexes = p.requestIndexes[:last]
189 type desiredRequestState struct {
190 Requests []RequestIndex
194 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
195 input := p.t.getRequestStrategyInput()
196 requestHeap := peerRequests{
199 for i := range input.Torrents {
200 t := &input.Torrents[i]
201 if t.InfoHash == p.t.infoHash {
202 requestHeap.torrentStrategyInput = t
206 request_strategy.GetRequestablePieces(
208 func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
209 if t.InfoHash != p.t.infoHash {
212 if !p.peerHasPiece(pieceIndex) {
215 allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
216 rsp.IterPendingChunks.Iter(func(ci request_strategy.ChunkIndex) {
217 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
218 // if p.t.pendingRequests.Get(r) != 0 && !p.actualRequestState.Requests.Contains(r) {
222 // We must signal interest to request this
223 desired.Interested = true
224 // We can make or will allow sustaining a request here if we're not choked, or
225 // have made the request previously (presumably while unchoked), and haven't had
226 // the peer respond yet (and the request was retained because we are using the
228 if p.peerChoking && !p.actualRequestState.Requests.Contains(r) {
229 // We can't request this right now.
233 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
237 p.t.assertPendingRequests()
238 heap.Init(&requestHeap)
239 for requestHeap.Len() != 0 && len(desired.Requests) < p.nominalMaxRequests() {
240 requestIndex := heap.Pop(&requestHeap).(RequestIndex)
241 desired.Requests = append(desired.Requests, requestIndex)
246 func (p *Peer) maybeUpdateActualRequestState() bool {
247 if p.needRequestUpdate == "" {
252 context.Background(),
253 pprof.Labels("update request", p.needRequestUpdate),
254 func(_ context.Context) {
255 next := p.getDesiredRequestState()
256 more = p.applyRequestState(next)
262 // Transmit/action the request state to the peer.
263 func (p *Peer) applyRequestState(next desiredRequestState) bool {
264 current := &p.actualRequestState
265 if !p.setInterested(next.Interested) {
269 cancel := current.Requests.Clone()
270 for _, ri := range next.Requests {
273 cancel.Iterate(func(req uint32) bool {
282 for i := 0; i < len(next.Requests); i++ {
283 req := next.Requests[i]
284 if p.cancelledRequests.Contains(req) {
285 // Waiting for a reject or piece message, which will suitably trigger us to update our
286 // requests, so we can skip this one with no additional consideration.
289 // The cardinality of our desired requests shouldn't exceed the max requests since it's used
290 // in the calculation of the requests. However, if we cancelled requests and they haven't
291 // been rejected or serviced yet with the fast extension enabled, we can end up with more
292 // extra outstanding requests. We could subtract the number of outstanding cancels from the
293 // next request cardinality, but peers might not like that.
294 if maxRequests(current.Requests.GetCardinality()) >= p.nominalMaxRequests() {
295 // log.Printf("not assigning all requests [desired=%v, cancelled=%v, current=%v, max=%v]",
296 // next.Requests.GetCardinality(),
297 // p.cancelledRequests.GetCardinality(),
298 // current.Requests.GetCardinality(),
299 // p.nominalMaxRequests(),
303 otherPending := p.t.pendingRequests.Get(next.Requests[0])
304 if p.actualRequestState.Requests.Contains(next.Requests[0]) {
307 if otherPending < lastPending {
308 // Pending should only rise. It's supposed to be the strongest ordering criteria. If it
309 // doesn't, our shuffling condition could be wrong.
312 // If the request has already been requested by another peer, shuffle this and the rest of
313 // the requests (since according to the increasing condition, the rest of the indices
314 // already have an outstanding request with another peer).
315 if !shuffled && otherPending > 0 {
316 shuffleReqs := next.Requests[i:]
317 rand.Shuffle(len(shuffleReqs), func(i, j int) {
318 shuffleReqs[i], shuffleReqs[j] = shuffleReqs[j], shuffleReqs[i]
320 // log.Printf("shuffled reqs [%v:%v]", i, len(next.Requests))
327 more = p.mustRequest(req)
332 p.updateRequestsTimer.Stop()
334 p.needRequestUpdate = ""
335 if !current.Requests.IsEmpty() {
336 p.updateRequestsTimer.Reset(3 * time.Second)