1 package request_strategy
8 "github.com/anacrolix/multiless"
9 "github.com/anacrolix/torrent/storage"
11 pp "github.com/anacrolix/torrent/peer_protocol"
12 "github.com/anacrolix/torrent/types"
16 Request = types.Request
17 pieceIndex = types.PieceIndex
18 piecePriority = types.PiecePriority
19 // This can be made into a type-param later, will be great for testing.
20 ChunkSpec = types.ChunkSpec
23 type ClientPieceOrder struct{}
25 type filterTorrent struct {
28 // Potentially shared with other torrents.
32 func sortFilterPieces(pieces []filterPiece) {
33 sort.Slice(pieces, func(_i, _j int) bool {
36 return multiless.New().Int(
37 int(j.Priority), int(i.Priority),
41 i.Availability, j.Availability,
45 i.t.StableId, j.t.StableId,
50 type requestsPeer struct {
52 nextState PeerNextRequestState
53 requestablePiecesRemaining int
56 func (rp *requestsPeer) canFitRequest() bool {
57 return len(rp.nextState.Requests) < rp.MaxRequests
60 func (rp *requestsPeer) addNextRequest(r Request) {
61 _, ok := rp.nextState.Requests[r]
63 panic("should only add once")
65 rp.nextState.Requests[r] = struct{}{}
68 type peersForPieceRequests struct {
73 func (me *peersForPieceRequests) addNextRequest(r Request) {
74 me.requestsPeer.addNextRequest(r)
78 type requestablePiece struct {
83 IterPendingChunks ChunksIter
86 type filterPiece struct {
92 // Calls f with requestable pieces in order.
93 func GetRequestablePieces(input Input, f func(t *Torrent, p *Piece, pieceIndex int)) {
95 for i := range input.Torrents {
96 maxPieces += len(input.Torrents[i].Pieces)
98 pieces := make([]filterPiece, 0, maxPieces)
99 // Storage capacity left for this run, keyed by the storage capacity pointer on the storage
100 // TorrentImpl. A nil value means no capacity limit.
101 storageLeft := make(map[storage.TorrentCapacity]*int64)
102 for _t := range input.Torrents {
103 // TODO: We could do metainfo requests here.
105 Torrent: &input.Torrents[_t],
110 if _, ok := storageLeft[key]; !ok {
111 capacity, ok := (*key)()
113 storageLeft[key] = &capacity
115 storageLeft[key] = nil
118 t.storageLeft = storageLeft[key]
120 for i := range t.Pieces {
121 pieces = append(pieces, filterPiece{
128 sortFilterPieces(pieces)
129 var allTorrentsUnverifiedBytes int64
130 for _, piece := range pieces {
131 if left := piece.t.storageLeft; left != nil {
132 if *left < int64(piece.Length) {
135 *left -= int64(piece.Length)
137 if !piece.Request || piece.NumPendingChunks == 0 {
138 // TODO: Clarify exactly what is verified. Stuff that's being hashed should be
139 // considered unverified and hold up further requests.
142 if piece.t.MaxUnverifiedBytes != 0 && piece.t.unverifiedBytes+piece.Length > piece.t.MaxUnverifiedBytes {
145 if input.MaxUnverifiedBytes != 0 && allTorrentsUnverifiedBytes+piece.Length > input.MaxUnverifiedBytes {
148 piece.t.unverifiedBytes += piece.Length
149 allTorrentsUnverifiedBytes += piece.Length
150 f(piece.t.Torrent, piece.Piece, piece.index)
157 MaxUnverifiedBytes int64
160 // TODO: We could do metainfo requests here.
161 func Run(input Input) map[PeerId]PeerNextRequestState {
162 var requestPieces []requestablePiece
163 GetRequestablePieces(input, func(t *Torrent, piece *Piece, pieceIndex int) {
164 requestPieces = append(requestPieces, requestablePiece{
167 NumPendingChunks: piece.NumPendingChunks,
168 IterPendingChunks: piece.iterPendingChunksWrapper,
169 alwaysReallocate: piece.Priority >= types.PiecePriorityNext,
172 torrents := input.Torrents
173 allPeers := make(map[uintptr][]*requestsPeer, len(torrents))
174 for _, t := range torrents {
175 peers := make([]*requestsPeer, 0, len(t.Peers))
176 for _, p := range t.Peers {
177 peers = append(peers, &requestsPeer{
179 nextState: PeerNextRequestState{
180 Requests: make(map[Request]struct{}, p.MaxRequests),
184 allPeers[t.StableId] = peers
186 for _, piece := range requestPieces {
187 for _, peer := range allPeers[piece.t.StableId] {
188 if peer.canRequestPiece(piece.index) {
189 peer.requestablePiecesRemaining++
193 for _, piece := range requestPieces {
194 allocatePendingChunks(piece, allPeers[piece.t.StableId])
196 ret := make(map[PeerId]PeerNextRequestState)
197 for _, peers := range allPeers {
198 for _, rp := range peers {
199 if rp.requestablePiecesRemaining != 0 {
200 panic(rp.requestablePiecesRemaining)
202 if _, ok := ret[rp.Id]; ok {
203 panic(fmt.Sprintf("duplicate peer id: %v", rp.Id))
205 ret[rp.Id] = rp.nextState
211 // Checks that a sorted peersForPiece slice makes sense.
212 func ensureValidSortedPeersForPieceRequests(peers *peersForPieceSorter) {
213 if !sort.IsSorted(peers) {
216 peerMap := make(map[*peersForPieceRequests]struct{}, peers.Len())
217 for _, p := range peers.peersForPiece {
218 if _, ok := peerMap[p]; ok {
221 peerMap[p] = struct{}{}
225 var peersForPiecesPool sync.Pool
227 func makePeersForPiece(cap int) []*peersForPieceRequests {
228 got := peersForPiecesPool.Get()
230 return make([]*peersForPieceRequests, 0, cap)
232 return got.([]*peersForPieceRequests)[:0]
235 type peersForPieceSorter struct {
236 peersForPiece []*peersForPieceRequests
241 func (me *peersForPieceSorter) Len() int {
242 return len(me.peersForPiece)
245 func (me *peersForPieceSorter) Swap(i, j int) {
246 me.peersForPiece[i], me.peersForPiece[j] = me.peersForPiece[j], me.peersForPiece[i]
249 func (me *peersForPieceSorter) Less(_i, _j int) bool {
250 i := me.peersForPiece[_i]
251 j := me.peersForPiece[_j]
254 byHasRequest := func() multiless.Computation {
255 ml := multiless.New()
257 _, iHas := i.nextState.Requests[*req]
258 _, jHas := j.nextState.Requests[*req]
259 ml = ml.Bool(jHas, iHas)
263 ml := multiless.New()
264 // We always "reallocate", that is force even striping amongst peers that are either on
265 // the last piece they can contribute too, or for pieces marked for this behaviour.
266 // Striping prevents starving peers of requests, and will always re-balance to the
267 // fastest known peers.
268 if !p.alwaysReallocate {
270 j.requestablePiecesRemaining == 1,
271 i.requestablePiecesRemaining == 1)
273 if p.alwaysReallocate || j.requestablePiecesRemaining == 1 {
278 ml = ml.AndThen(byHasRequest)
281 i.requestablePiecesRemaining,
282 j.requestablePiecesRemaining,
290 ml = ml.AndThen(byHasRequest)
292 int64(j.Age), int64(i.Age),
293 // TODO: Probably peer priority can come next
300 func allocatePendingChunks(p requestablePiece, peers []*requestsPeer) {
301 peersForPiece := makePeersForPiece(len(peers))
302 for _, peer := range peers {
303 if !peer.canRequestPiece(p.index) {
306 if !peer.canFitRequest() {
307 peer.requestablePiecesRemaining--
310 peersForPiece = append(peersForPiece, &peersForPieceRequests{
316 for _, peer := range peersForPiece {
317 peer.requestablePiecesRemaining--
319 peersForPiecesPool.Put(peersForPiece)
321 peersForPieceSorter := peersForPieceSorter{
322 peersForPiece: peersForPiece,
325 sortPeersForPiece := func(req *Request) {
326 peersForPieceSorter.req = req
327 sort.Sort(&peersForPieceSorter)
328 //ensureValidSortedPeersForPieceRequests(&peersForPieceSorter)
330 // Chunks can be preassigned several times, if peers haven't been able to update their "actual"
331 // with "next" request state before another request strategy run occurs.
332 preallocated := make(map[ChunkSpec][]*peersForPieceRequests, p.NumPendingChunks)
333 p.IterPendingChunks(func(spec ChunkSpec) {
334 req := Request{pp.Integer(p.index), spec}
335 for _, peer := range peersForPiece {
336 if h := peer.HasExistingRequest; h == nil || !h(req) {
339 if !peer.canFitRequest() {
342 preallocated[spec] = append(preallocated[spec], peer)
343 peer.addNextRequest(req)
346 pendingChunksRemaining := int(p.NumPendingChunks)
347 p.IterPendingChunks(func(chunk types.ChunkSpec) {
348 if _, ok := preallocated[chunk]; ok {
351 req := Request{pp.Integer(p.index), chunk}
352 defer func() { pendingChunksRemaining-- }()
353 sortPeersForPiece(nil)
354 for _, peer := range peersForPiece {
355 if !peer.canFitRequest() {
358 if !peer.pieceAllowedFastOrDefault(p.index) {
359 // TODO: Verify that's okay to stay uninterested if we request allowed fast pieces.
360 peer.nextState.Interested = true
365 peer.addNextRequest(req)
370 for chunk, prePeers := range preallocated {
371 pendingChunksRemaining--
372 req := Request{pp.Integer(p.index), chunk}
373 for _, pp := range prePeers {
376 sortPeersForPiece(&req)
377 for _, pp := range prePeers {
378 delete(pp.nextState.Requests, req)
380 for _, peer := range peersForPiece {
381 if !peer.canFitRequest() {
384 if !peer.pieceAllowedFastOrDefault(p.index) {
385 // TODO: Verify that's okay to stay uninterested if we request allowed fast pieces.
386 peer.nextState.Interested = true
391 peer.addNextRequest(req)
395 if pendingChunksRemaining != 0 {
396 panic(pendingChunksRemaining)