11 "github.com/anacrolix/log"
12 "github.com/anacrolix/missinggo/v2"
15 // Accesses Torrent data via a Client. Reads block until the data is available. Seeks and readahead
16 // also drive Client behaviour.
17 type Reader interface {
21 missinggo.ReadContexter
22 // Configure the number of bytes ahead of a read that should also be prioritized in preparation
25 // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
26 // the underlying chunks become available.
30 // Piece range by piece index, [begin, end).
31 type pieceRange struct {
38 // Adjust the read/seek window to handle Readers locked to File extents and the like.
40 // Ensure operations that change the position are exclusive, like Read() and Seek().
43 // Required when modifying pos and readahead, or reading them without opMu.
47 // Function to dynamically calculate readahead. If nil, readahead is static.
48 readaheadFunc func() int64
49 // Position that reads have continued contiguously from.
50 contiguousReadStartPos int64
51 // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
52 // We cache this so that changes can be detected, and bubbled up to the Torrent only as
57 var _ io.ReadCloser = (*reader)(nil)
59 func (r *reader) SetResponsive() {
61 r.t.cl.event.Broadcast()
64 // Disable responsive mode. TODO: Remove?
65 func (r *reader) SetNonResponsive() {
67 r.t.cl.event.Broadcast()
70 func (r *reader) SetReadahead(readahead int64) {
72 r.readahead = readahead
80 // How many bytes are available to read. Max is the most we could require.
81 func (r *reader) available(off, max int64) (ret int64) {
84 req, ok := r.t.offsetRequest(off)
88 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
91 if !r.t.haveChunk(req) {
94 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
99 // Ensure that ret hasn't exceeded our original max.
106 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
107 func (r *reader) piecesUncached() (ret pieceRange) {
109 if r.readaheadFunc != nil {
110 ra = r.readaheadFunc()
113 // Needs to be at least 1, because [x, x) means we don't want
117 if ra > r.length-r.pos {
118 ra = r.length - r.pos
120 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
124 func (r *reader) Read(b []byte) (n int, err error) {
125 return r.ReadContext(context.Background(), b)
128 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
129 // Hmmm, if a Read gets stuck, this means you can't change position for other purposes. That
130 // seems reasonable, but unusual.
132 defer r.opMu.Unlock()
133 n, err = r.readOnceAt(ctx, b, r.pos)
135 if err == nil && len(b) > 0 {
136 panic("expected error")
146 if r.pos >= r.length {
148 } else if err == io.EOF {
149 err = io.ErrUnexpectedEOF
154 var closedChan = make(chan struct{})
160 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
161 // much should be readable without blocking.
162 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
166 avail = r.available(pos, wanted)
167 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
172 var dontWait <-chan struct{}
173 if !wait || wanted == 0 {
174 dontWait = closedChan
177 case <-r.t.closed.Done():
178 err = errors.New("torrent closed")
183 case <-r.t.dataDownloadDisallowed.On():
184 err = errors.New("torrent data downloading disabled")
185 case <-r.t.networkingEnabled.Off():
186 err = errors.New("torrent networking disabled")
195 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
196 // constrainted to a particular file within the torrent).
197 func (r *reader) torrentOffset(readerPos int64) int64 {
198 return r.offset + readerPos
201 // Performs at most one successful read to torrent storage.
202 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
209 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
213 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
214 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
215 b1 := missinggo.LimitLen(b, avail)
216 n, err = r.t.readAt(b1, r.torrentOffset(pos))
222 // TODO: Just reset pieces in the readahead window. This might help
223 // prevent thrashing with small caches and file and piece priorities.
224 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
225 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
226 if !r.t.updatePieceCompletion(firstPieceIndex) {
227 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
229 // Update the rest of the piece completions in the readahead window, without alerting to
230 // changes (since only the first piece, the one above, could have generated the read error
231 // we're currently handling).
232 if r.pieces.begin != firstPieceIndex {
233 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
235 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
236 r.t.updatePieceCompletion(index)
243 func (r *reader) Close() error {
245 defer r.t.cl.unlock()
250 func (r *reader) posChanged() {
251 to := r.piecesUncached()
257 // log.Printf("reader pos changed %v->%v", from, to)
258 r.t.readerPosChanged(from, to)
261 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
263 defer r.opMu.Unlock()
266 newPos, err = func() (int64, error) {
271 return r.pos + off, nil
273 return r.length + off, nil
275 return r.pos, errors.New("bad whence")
285 r.contiguousReadStartPos = newPos
291 func (r *reader) log(m log.Msg) {
292 r.t.logger.Log(m.Skip(1))
295 // Implementation inspired from an arbitrary comment I found on HN.
296 func (r *reader) sqrtReadahead() int64 {
297 return int64(math.Sqrt(float64(r.pos - r.contiguousReadStartPos)))