1 package request_strategy
7 "github.com/anacrolix/multiless"
8 "github.com/anacrolix/torrent/metainfo"
10 "github.com/anacrolix/torrent/types"
15 ChunkIndex = RequestIndex
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 func pieceOrderLess(i, j *pieceRequestOrderItem) multiless.Computation {
24 return multiless.New().Int(
25 int(j.state.Priority), int(i.state.Priority),
26 // TODO: Should we match on complete here to prevent churn when availability changes?
28 j.state.Partial, i.state.Partial,
30 // If this is done with relative availability, do we lose some determinism? If completeness
31 // is used, would that push this far enough down?
32 i.state.Availability, j.state.Availability,
34 i.key.Index, j.key.Index,
35 ).Lazy(func() multiless.Computation {
36 return multiless.New().Cmp(bytes.Compare(
43 var packageExpvarMap = expvar.NewMap("request-strategy")
45 // Calls f with requestable pieces in order.
46 func GetRequestablePieces(
47 input Input, pro *PieceRequestOrder,
48 f func(ih metainfo.Hash, pieceIndex int, orderState PieceRequestOrderState),
50 // Storage capacity left for this run, keyed by the storage capacity pointer on the storage
51 // TorrentImpl. A nil value means no capacity limit.
52 var storageLeft *int64
53 if cap, ok := input.Capacity(); ok {
56 var allTorrentsUnverifiedBytes int64
57 pro.tree.Scan(func(_i pieceRequestOrderItem) bool {
59 var t = input.Torrent(ih)
60 pieceLength := t.PieceLength()
61 if storageLeft != nil {
62 if *storageLeft < pieceLength {
65 *storageLeft -= pieceLength
67 if t.IgnorePiece(_i.key.Index) {
68 // TODO: Clarify exactly what is verified. Stuff that's being hashed should be
69 // considered unverified and hold up further requests.
72 if input.MaxUnverifiedBytes() != 0 && allTorrentsUnverifiedBytes+pieceLength > input.MaxUnverifiedBytes() {
75 allTorrentsUnverifiedBytes += pieceLength
76 f(ih, _i.key.Index, _i.state)
82 type Input interface {
83 Torrent(metainfo.Hash) Torrent
84 // Storage capacity, shared among all Torrents with the same storage.TorrentCapacity pointer in
85 // their storage.Torrent references.
86 Capacity() (cap int64, capped bool)
87 // Across all the Torrents. This might be partitioned by storage capacity key now.
88 MaxUnverifiedBytes() int64