12 "github.com/anacrolix/log"
13 "github.com/anacrolix/multiless"
15 request_strategy "github.com/anacrolix/torrent/request-strategy"
18 func (cl *Client) getRequestStrategyInput() request_strategy.Input {
19 ts := make([]request_strategy.Torrent, 0, len(cl.torrents))
20 for _, t := range cl.torrents {
22 // This would be removed if metadata is handled here. We have to guard against not
23 // knowing the piece size. If we have no info, we have no pieces too, so the end result
27 rst := request_strategy.Torrent{
29 ChunksPerPiece: t.chunksPerRegularPiece(),
32 rst.Capacity = t.storage.Capacity
34 rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
35 for i := range t.pieces {
37 rst.Pieces = append(rst.Pieces, request_strategy.Piece{
38 Request: !t.ignorePieceForRequests(i),
39 Priority: p.purePriority(),
40 Partial: t.piecePartiallyDownloaded(i),
41 Availability: p.availability,
42 Length: int64(p.length()),
43 NumPendingChunks: int(t.pieceNumPendingChunks(i)),
44 IterPendingChunks: &p.undirtiedChunksIter,
49 return request_strategy.Input{
51 MaxUnverifiedBytes: cl.config.MaxUnverifiedBytes,
56 gob.Register(peerId{})
64 func (p peerId) Uintptr() uintptr {
68 func (p peerId) GobEncode() (b []byte, _ error) {
69 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
70 Data: uintptr(unsafe.Pointer(&p.ptr)),
71 Len: int(unsafe.Sizeof(p.ptr)),
72 Cap: int(unsafe.Sizeof(p.ptr)),
77 func (p *peerId) GobDecode(b []byte) error {
78 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
81 ptr := unsafe.Pointer(&b[0])
82 p.ptr = *(*uintptr)(ptr)
84 dst := reflect.SliceHeader{
85 Data: uintptr(unsafe.Pointer(&p.Peer)),
86 Len: int(unsafe.Sizeof(p.Peer)),
87 Cap: int(unsafe.Sizeof(p.Peer)),
89 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
94 RequestIndex = request_strategy.RequestIndex
95 chunkIndexType = request_strategy.ChunkIndex
98 type peerRequests struct {
99 requestIndexes []RequestIndex
101 torrentStrategyInput *request_strategy.Torrent
104 func (p *peerRequests) Len() int {
105 return len(p.requestIndexes)
108 func (p *peerRequests) Less(i, j int) bool {
109 leftRequest := p.requestIndexes[i]
110 rightRequest := p.requestIndexes[j]
112 leftPieceIndex := leftRequest / p.torrentStrategyInput.ChunksPerPiece
113 rightPieceIndex := rightRequest / p.torrentStrategyInput.ChunksPerPiece
114 leftCurrent := p.peer.actualRequestState.Requests.Contains(leftRequest)
115 rightCurrent := p.peer.actualRequestState.Requests.Contains(rightRequest)
116 pending := func(index RequestIndex, current bool) int {
117 ret := t.pendingRequests.Get(index)
121 // See https://github.com/anacrolix/torrent/issues/679 for possible issues. This should be
128 ml := multiless.New()
129 // Push requests that can't be served right now to the end. But we don't throw them away unless
130 // there's a better alternative. This is for when we're using the fast extension and get choked
131 // but our requests could still be good when we get unchoked.
132 if p.peer.peerChoking {
134 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
135 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
139 pending(leftRequest, leftCurrent),
140 pending(rightRequest, rightCurrent))
141 ml = ml.Bool(!leftCurrent, !rightCurrent)
143 -int(p.torrentStrategyInput.Pieces[leftPieceIndex].Priority),
144 -int(p.torrentStrategyInput.Pieces[rightPieceIndex].Priority),
147 int(p.torrentStrategyInput.Pieces[leftPieceIndex].Availability),
148 int(p.torrentStrategyInput.Pieces[rightPieceIndex].Availability))
149 ml = ml.Uint32(leftPieceIndex, rightPieceIndex)
150 ml = ml.Uint32(leftRequest, rightRequest)
154 func (p *peerRequests) Swap(i, j int) {
155 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
158 func (p *peerRequests) Push(x interface{}) {
159 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
162 func (p *peerRequests) Pop() interface{} {
163 last := len(p.requestIndexes) - 1
164 x := p.requestIndexes[last]
165 p.requestIndexes = p.requestIndexes[:last]
169 type desiredRequestState struct {
170 Requests []RequestIndex
174 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
175 input := p.t.cl.getRequestStrategyInput()
176 requestHeap := peerRequests{
179 for i := range input.Torrents {
180 t := &input.Torrents[i]
181 if t.InfoHash == p.t.infoHash {
182 requestHeap.torrentStrategyInput = t
186 request_strategy.GetRequestablePieces(
188 func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
189 if t.InfoHash != p.t.infoHash {
192 if !p.peerHasPiece(pieceIndex) {
195 allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
196 rsp.IterPendingChunks.Iter(func(ci request_strategy.ChunkIndex) {
197 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
198 //if p.t.pendingRequests.Get(r) != 0 && !p.actualRequestState.Requests.Contains(r) {
202 // We must signal interest to request this
203 desired.Interested = true
204 // We can make or will allow sustaining a request here if we're not choked, or
205 // have made the request previously (presumably while unchoked), and haven't had
206 // the peer respond yet (and the request was retained because we are using the
208 if p.peerChoking && !p.actualRequestState.Requests.Contains(r) {
209 // We can't request this right now.
213 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
217 p.t.assertPendingRequests()
218 heap.Init(&requestHeap)
219 for requestHeap.Len() != 0 && len(desired.Requests) < p.nominalMaxRequests() {
220 requestIndex := heap.Pop(&requestHeap).(RequestIndex)
221 desired.Requests = append(desired.Requests, requestIndex)
226 func (p *Peer) maybeUpdateActualRequestState() bool {
227 if p.needRequestUpdate == "" {
232 context.Background(),
233 pprof.Labels("update request", p.needRequestUpdate),
234 func(_ context.Context) {
235 next := p.getDesiredRequestState()
236 more = p.applyRequestState(next)
242 // Transmit/action the request state to the peer.
243 func (p *Peer) applyRequestState(next desiredRequestState) bool {
244 current := &p.actualRequestState
245 if !p.setInterested(next.Interested) {
249 cancel := current.Requests.Clone()
250 for _, ri := range next.Requests {
253 cancel.Iterate(func(req uint32) bool {
260 for _, req := range next.Requests {
261 if p.cancelledRequests.Contains(req) {
262 // Waiting for a reject or piece message, which will suitably trigger us to update our
263 // requests, so we can skip this one with no additional consideration.
266 // The cardinality of our desired requests shouldn't exceed the max requests since it's used
267 // in the calculation of the requests. However, if we cancelled requests and they haven't
268 // been rejected or serviced yet with the fast extension enabled, we can end up with more
269 // extra outstanding requests. We could subtract the number of outstanding cancels from the
270 // next request cardinality, but peers might not like that.
271 if maxRequests(current.Requests.GetCardinality()) >= p.nominalMaxRequests() {
272 //log.Printf("not assigning all requests [desired=%v, cancelled=%v, current=%v, max=%v]",
273 // next.Requests.GetCardinality(),
274 // p.cancelledRequests.GetCardinality(),
275 // current.Requests.GetCardinality(),
276 // p.nominalMaxRequests(),
280 more = p.mustRequest(req)
285 p.updateRequestsTimer.Stop()
287 p.needRequestUpdate = ""
288 if !current.Requests.IsEmpty() {
289 p.updateRequestsTimer.Reset(3 * time.Second)