10 "github.com/anacrolix/log"
11 "github.com/anacrolix/missinggo/v2"
14 // Accesses Torrent data via a Client. Reads block until the data is available. Seeks and readahead
15 // also drive Client behaviour.
16 type Reader interface {
18 missinggo.ReadContexter
19 // Configure the number of bytes ahead of a read that should also be prioritized in preparation
22 // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
23 // the underlying chunks become available.
27 // Piece range by piece index, [begin, end).
28 type pieceRange struct {
34 // Adjust the read/seek window to handle Readers locked to File extents and the like.
37 // Function to dynamically calculate readahead. If nil, readahead is static.
38 readaheadFunc func() int64
40 // Required when modifying pos and readahead.
44 // Position that reads have continued contiguously from.
45 contiguousReadStartPos int64
46 // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
47 // We cache this so that changes can be detected, and bubbled up to the Torrent only as
51 // Reads have been initiated since the last seek. This is used to prevent readaheads occurring
52 // after a seek or with a new reader at the starting position.
58 var _ io.ReadSeekCloser = (*reader)(nil)
60 func (r *reader) SetResponsive() {
62 r.t.cl.event.Broadcast()
65 // Disable responsive mode. TODO: Remove?
66 func (r *reader) SetNonResponsive() {
68 r.t.cl.event.Broadcast()
71 func (r *reader) SetReadahead(readahead int64) {
74 r.readahead = readahead
79 // How many bytes are available to read. Max is the most we could require.
80 func (r *reader) available(off, max int64) (ret int64) {
83 req, ok := r.t.offsetRequest(off)
87 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
90 if !r.t.haveChunk(req) {
93 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
98 // Ensure that ret hasn't exceeded our original max.
105 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
106 func (r *reader) piecesUncached() (ret pieceRange) {
108 if r.readaheadFunc != nil {
109 ra = r.readaheadFunc()
112 // Needs to be at least 1, because [x, x) means we don't want
119 if ra > r.length-r.pos {
120 ra = r.length - r.pos
122 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
126 func (r *reader) Read(b []byte) (n int, err error) {
127 return r.ReadContext(context.Background(), b)
130 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
133 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
134 // and take the lock here.
139 n, err = r.readOnceAt(ctx, b, r.pos)
141 if err == nil && len(b) > 0 {
142 panic("expected error")
152 if r.pos >= r.length {
154 } else if err == io.EOF {
155 err = io.ErrUnexpectedEOF
160 var closedChan = make(chan struct{})
166 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
167 // much should be readable without blocking.
168 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
172 avail = r.available(pos, wanted)
173 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
178 var dontWait <-chan struct{}
179 if !wait || wanted == 0 {
180 dontWait = closedChan
183 case <-r.t.closed.Done():
184 err = errors.New("torrent closed")
189 case <-r.t.dataDownloadDisallowed.On():
190 err = errors.New("torrent data downloading disabled")
191 case <-r.t.networkingEnabled.Off():
192 err = errors.New("torrent networking disabled")
201 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
202 // constrainted to a particular file within the torrent).
203 func (r *reader) torrentOffset(readerPos int64) int64 {
204 return r.offset + readerPos
207 // Performs at most one successful read to torrent storage.
208 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
215 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
219 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
220 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
221 b1 := missinggo.LimitLen(b, avail)
222 n, err = r.t.readAt(b1, r.torrentOffset(pos))
228 // TODO: Just reset pieces in the readahead window. This might help
229 // prevent thrashing with small caches and file and piece priorities.
230 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
231 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
232 if !r.t.updatePieceCompletion(firstPieceIndex) {
233 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
235 // Update the rest of the piece completions in the readahead window, without alerting to
236 // changes (since only the first piece, the one above, could have generated the read error
237 // we're currently handling).
238 if r.pieces.begin != firstPieceIndex {
239 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
241 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
242 r.t.updatePieceCompletion(index)
249 func (r *reader) Close() error {
251 defer r.t.cl.unlock()
256 func (r *reader) posChanged() {
257 to := r.piecesUncached()
263 // log.Printf("reader pos changed %v->%v", from, to)
264 r.t.readerPosChanged(from, to)
267 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
270 newPos, err = func() (int64, error) {
275 return r.pos + off, nil
277 return r.length + off, nil
279 return r.pos, errors.New("bad whence")
290 r.contiguousReadStartPos = newPos
296 func (r *reader) log(m log.Msg) {
297 r.t.logger.Log(m.Skip(1))
300 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
301 func (r *reader) defaultReadaheadFunc() int64 {
302 return r.pos - r.contiguousReadStartPos