forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
requesting.go
236 lines (222 loc) · 5.86 KB
/
requesting.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package torrent
import (
"time"
"unsafe"
"github.com/RoaringBitmap/roaring"
"github.com/anacrolix/missinggo/v2/bitmap"
"github.com/anacrolix/chansync"
request_strategy "github.com/anacrolix/torrent/request-strategy"
)
// Calculate requests individually for each peer.
const peerRequesting = false
func (cl *Client) requester() {
for {
update := func() chansync.Signaled {
cl.lock()
defer cl.unlock()
cl.doRequests()
return cl.updateRequests.Signaled()
}()
minWait := time.After(100 * time.Millisecond)
maxWait := time.After(1000 * time.Millisecond)
select {
case <-cl.closed.Done():
return
case <-minWait:
case <-maxWait:
}
select {
case <-cl.closed.Done():
return
case <-update:
case <-maxWait:
}
}
}
func (cl *Client) tickleRequester() {
cl.updateRequests.Broadcast()
}
func (cl *Client) getRequestStrategyInput() request_strategy.Input {
ts := make([]request_strategy.Torrent, 0, len(cl.torrents))
for _, t := range cl.torrents {
if !t.haveInfo() {
// This would be removed if metadata is handled here. We have to guard against not
// knowing the piece size. If we have no info, we have no pieces too, so the end result
// is the same.
continue
}
rst := request_strategy.Torrent{
InfoHash: t.infoHash,
ChunksPerPiece: (t.usualPieceSize() + int(t.chunkSize) - 1) / int(t.chunkSize),
}
if t.storage != nil {
rst.Capacity = t.storage.Capacity
}
rst.Pieces = make([]request_strategy.Piece, 0, len(t.pieces))
for i := range t.pieces {
p := &t.pieces[i]
rst.Pieces = append(rst.Pieces, request_strategy.Piece{
Request: !t.ignorePieceForRequests(i),
Priority: p.purePriority(),
Partial: t.piecePartiallyDownloaded(i),
Availability: p.availability,
Length: int64(p.length()),
NumPendingChunks: int(t.pieceNumPendingChunks(i)),
IterPendingChunks: p.iterUndirtiedChunks,
})
}
t.iterPeers(func(p *Peer) {
if p.closed.IsSet() {
return
}
if p.piecesReceivedSinceLastRequestUpdate > p.maxPiecesReceivedBetweenRequestUpdates {
p.maxPiecesReceivedBetweenRequestUpdates = p.piecesReceivedSinceLastRequestUpdate
}
p.piecesReceivedSinceLastRequestUpdate = 0
rst.Peers = append(rst.Peers, request_strategy.Peer{
HasPiece: p.peerHasPiece,
MaxRequests: p.nominalMaxRequests(),
HasExistingRequest: func(r RequestIndex) bool {
return p.actualRequestState.Requests.Contains(r)
},
Choking: p.peerChoking,
PieceAllowedFast: func(i pieceIndex) bool {
return p.peerAllowedFast.Contains(bitmap.BitIndex(i))
},
DownloadRate: p.downloadRate(),
Age: time.Since(p.completedHandshake),
Id: peerId{
Peer: p,
ptr: uintptr(unsafe.Pointer(p)),
},
})
})
ts = append(ts, rst)
}
return request_strategy.Input{
Torrents: ts,
MaxUnverifiedBytes: cl.config.MaxUnverifiedBytes,
}
}
func (cl *Client) doRequests() {
nextPeerStates := request_strategy.Run(cl.getRequestStrategyInput())
for p, state := range nextPeerStates {
setPeerNextRequestState(p, state)
}
}
type peerId struct {
*Peer
ptr uintptr
}
func (p peerId) Uintptr() uintptr {
return p.ptr
}
func setPeerNextRequestState(_p request_strategy.PeerId, rp request_strategy.PeerNextRequestState) {
p := _p.(peerId).Peer
p.nextRequestState = rp
p.onNextRequestStateChanged()
}
type RequestIndex = request_strategy.RequestIndex
type chunkIndexType = request_strategy.ChunkIndex
func (p *Peer) applyNextRequestState() bool {
if peerRequesting {
if p.actualRequestState.Requests.GetCardinality() > uint64(p.nominalMaxRequests()/2) {
return true
}
type piece struct {
index int
endGame bool
}
var pieceOrder []piece
request_strategy.GetRequestablePieces(
p.t.cl.getRequestStrategyInput(),
func(t *request_strategy.Torrent, rsp *request_strategy.Piece, pieceIndex int) {
if t.InfoHash != p.t.infoHash {
return
}
if !p.peerHasPiece(pieceIndex) {
return
}
pieceOrder = append(pieceOrder, piece{
index: pieceIndex,
endGame: rsp.Priority == PiecePriorityNow,
})
},
)
more := true
interested := false
for _, endGameIter := range []bool{false, true} {
for _, piece := range pieceOrder {
tp := p.t.piece(piece.index)
tp.iterUndirtiedChunks(func(cs chunkIndexType) {
req := cs + tp.requestIndexOffset()
if !piece.endGame && !endGameIter && p.t.pendingRequests[req] > 0 {
return
}
interested = true
more = p.setInterested(true)
if !more {
return
}
if maxRequests(p.actualRequestState.Requests.GetCardinality()) >= p.nominalMaxRequests() {
return
}
if p.peerChoking && !p.peerAllowedFast.Contains(bitmap.BitIndex(piece.index)) {
return
}
var err error
more, err = p.request(req)
if err != nil {
panic(err)
}
})
if interested && maxRequests(p.actualRequestState.Requests.GetCardinality()) >= p.nominalMaxRequests() {
break
}
if !more {
break
}
}
if !more {
break
}
}
if !more {
return false
}
if !interested {
p.setInterested(false)
}
return more
}
next := p.nextRequestState
current := p.actualRequestState
if !p.setInterested(next.Interested) {
return false
}
more := true
cancel := roaring.AndNot(¤t.Requests, &next.Requests)
cancel.Iterate(func(req uint32) bool {
more = p.cancel(req)
return more
})
if !more {
return false
}
next.Requests.Iterate(func(req uint32) bool {
// This could happen if the peer chokes us between the next state being generated, and us
// trying to transmit the state.
if p.peerChoking && !p.peerAllowedFast.Contains(bitmap.BitIndex(req/p.t.chunksPerRegularPiece())) {
return true
}
var err error
more, err = p.request(req)
if err != nil {
panic(err)
} /* else {
log.Print(req)
} */
return more
})
return more
}