12 "github.com/anacrolix/log"
13 "github.com/anacrolix/multiless"
15 request_strategy "github.com/anacrolix/torrent/request-strategy"
18 func (cl *Client) tickleRequester() {
19 cl.updateRequests.Broadcast()
22 func (cl *Client) getRequestStrategyInput() request_strategy.Input {
23 ts := make([]request_strategy.Torrent, 0, len(cl.torrents))
24 for _, t := range cl.torrents {
26 // This would be removed if metadata is handled here. We have to guard against not
27 // knowing the piece size. If we have no info, we have no pieces too, so the end result
31 rst := request_strategy.Torrent{
33 ChunksPerPiece: t.chunksPerRegularPiece(),
36 rst.Capacity = t.storage.Capacity
38 rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
39 for i := range t.pieces {
41 rst.Pieces = append(rst.Pieces, request_strategy.Piece{
42 Request: !t.ignorePieceForRequests(i),
43 Priority: p.purePriority(),
44 Partial: t.piecePartiallyDownloaded(i),
45 Availability: p.availability,
46 Length: int64(p.length()),
47 NumPendingChunks: int(t.pieceNumPendingChunks(i)),
48 IterPendingChunks: &p.undirtiedChunksIter,
51 t.iterPeers(func(p *Peer) {
55 if p.piecesReceivedSinceLastRequestUpdate > p.maxPiecesReceivedBetweenRequestUpdates {
56 p.maxPiecesReceivedBetweenRequestUpdates = p.piecesReceivedSinceLastRequestUpdate
58 p.piecesReceivedSinceLastRequestUpdate = 0
59 rst.Peers = append(rst.Peers, request_strategy.Peer{
60 Pieces: *p.newPeerPieces(),
61 MaxRequests: p.nominalMaxRequests(),
62 ExistingRequests: p.actualRequestState.Requests,
63 Choking: p.peerChoking,
64 PieceAllowedFast: p.peerAllowedFast,
65 DownloadRate: p.downloadRate(),
66 Age: time.Since(p.completedHandshake),
69 ptr: uintptr(unsafe.Pointer(p)),
75 return request_strategy.Input{
77 MaxUnverifiedBytes: cl.config.MaxUnverifiedBytes,
82 gob.Register(peerId{})
90 func (p peerId) Uintptr() uintptr {
94 func (p peerId) GobEncode() (b []byte, _ error) {
95 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
96 Data: uintptr(unsafe.Pointer(&p.ptr)),
97 Len: int(unsafe.Sizeof(p.ptr)),
98 Cap: int(unsafe.Sizeof(p.ptr)),
103 func (p *peerId) GobDecode(b []byte) error {
104 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
107 ptr := unsafe.Pointer(&b[0])
108 p.ptr = *(*uintptr)(ptr)
109 log.Printf("%p", ptr)
110 dst := reflect.SliceHeader{
111 Data: uintptr(unsafe.Pointer(&p.Peer)),
112 Len: int(unsafe.Sizeof(p.Peer)),
113 Cap: int(unsafe.Sizeof(p.Peer)),
115 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
120 RequestIndex = request_strategy.RequestIndex
121 chunkIndexType = request_strategy.ChunkIndex
124 type peerRequests struct {
125 requestIndexes []RequestIndex
127 torrentStrategyInput request_strategy.Torrent
130 func (p *peerRequests) Len() int {
131 return len(p.requestIndexes)
134 func (p *peerRequests) Less(i, j int) bool {
135 leftRequest := p.requestIndexes[i]
136 rightRequest := p.requestIndexes[j]
138 leftPieceIndex := leftRequest / p.torrentStrategyInput.ChunksPerPiece
139 rightPieceIndex := rightRequest / p.torrentStrategyInput.ChunksPerPiece
140 leftCurrent := p.peer.actualRequestState.Requests.Contains(leftRequest)
141 rightCurrent := p.peer.actualRequestState.Requests.Contains(rightRequest)
142 pending := func(index RequestIndex, current bool) int {
143 ret := t.pendingRequests.Get(index)
147 // See https://github.com/anacrolix/torrent/issues/679 for possible issues. This should be
154 ml := multiless.New()
155 // Push requests that can't be served right now to the end. But we don't throw them away unless
156 // there's a better alternative. This is for when we're using the fast extension and get choked
157 // but our requests could still be good when we get unchoked.
158 if p.peer.peerChoking {
160 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
161 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
165 pending(leftRequest, leftCurrent),
166 pending(rightRequest, rightCurrent))
167 ml = ml.Bool(!leftCurrent, !rightCurrent)
169 -int(p.torrentStrategyInput.Pieces[leftPieceIndex].Priority),
170 -int(p.torrentStrategyInput.Pieces[rightPieceIndex].Priority),
173 int(p.torrentStrategyInput.Pieces[leftPieceIndex].Availability),
174 int(p.torrentStrategyInput.Pieces[rightPieceIndex].Availability))
175 ml = ml.Uint32(leftPieceIndex, rightPieceIndex)
176 ml = ml.Uint32(leftRequest, rightRequest)
180 func (p *peerRequests) Swap(i, j int) {
181 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
184 func (p *peerRequests) Push(x interface{}) {
185 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
188 func (p *peerRequests) Pop() interface{} {
189 last := len(p.requestIndexes) - 1
190 x := p.requestIndexes[last]
191 p.requestIndexes = p.requestIndexes[:last]
195 type desiredRequestState struct {
196 Requests []RequestIndex
200 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
201 input := p.t.cl.getRequestStrategyInput()
202 requestHeap := peerRequests{
205 for _, t := range input.Torrents {
206 if t.InfoHash == p.t.infoHash {
207 requestHeap.torrentStrategyInput = t
211 request_strategy.GetRequestablePieces(
213 func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
214 if t.InfoHash != p.t.infoHash {
217 if !p.peerHasPiece(pieceIndex) {
220 allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
221 rsp.IterPendingChunks.Iter(func(ci request_strategy.ChunkIndex) {
222 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
223 //if p.t.pendingRequests.Get(r) != 0 && !p.actualRequestState.Requests.Contains(r) {
227 // We must signal interest to request this
228 desired.Interested = true
229 // We can make or will allow sustaining a request here if we're not choked, or
230 // have made the request previously (presumably while unchoked), and haven't had
231 // the peer respond yet (and the request was retained because we are using the
233 if p.peerChoking && !p.actualRequestState.Requests.Contains(r) {
234 // We can't request this right now.
238 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
242 p.t.assertPendingRequests()
243 heap.Init(&requestHeap)
244 for requestHeap.Len() != 0 && len(desired.Requests) < p.nominalMaxRequests() {
245 requestIndex := heap.Pop(&requestHeap).(RequestIndex)
246 desired.Requests = append(desired.Requests, requestIndex)
251 func (p *Peer) maybeUpdateActualRequestState() bool {
252 if p.needRequestUpdate == "" {
257 context.Background(),
258 pprof.Labels("update request", p.needRequestUpdate),
259 func(_ context.Context) {
260 next := p.getDesiredRequestState()
261 more = p.applyRequestState(next)
267 // Transmit/action the request state to the peer.
268 func (p *Peer) applyRequestState(next desiredRequestState) bool {
269 current := &p.actualRequestState
270 if !p.setInterested(next.Interested) {
274 cancel := current.Requests.Clone()
275 for _, ri := range next.Requests {
278 cancel.Iterate(func(req uint32) bool {
285 for _, req := range next.Requests {
286 if p.cancelledRequests.Contains(req) {
287 // Waiting for a reject or piece message, which will suitably trigger us to update our
288 // requests, so we can skip this one with no additional consideration.
291 // The cardinality of our desired requests shouldn't exceed the max requests since it's used
292 // in the calculation of the requests. However, if we cancelled requests and they haven't
293 // been rejected or serviced yet with the fast extension enabled, we can end up with more
294 // extra outstanding requests. We could subtract the number of outstanding cancels from the
295 // next request cardinality, but peers might not like that.
296 if maxRequests(current.Requests.GetCardinality()) >= p.nominalMaxRequests() {
297 //log.Printf("not assigning all requests [desired=%v, cancelled=%v, current=%v, max=%v]",
298 // next.Requests.GetCardinality(),
299 // p.cancelledRequests.GetCardinality(),
300 // current.Requests.GetCardinality(),
301 // p.nominalMaxRequests(),
305 more = p.mustRequest(req)
310 p.updateRequestsTimer.Stop()
312 p.needRequestUpdate = ""
313 if !current.Requests.IsEmpty() {
314 p.updateRequestsTimer.Reset(3 * time.Second)