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
20 // for further reads. Overridden by non-nil readahead func, see SetReadaheadFunc.
22 // If non-nil, the provided function is called when the implementation needs to know the
23 // readahead for the current reader. Calls occur during Reads and Seeks, and while the Client is
25 SetReadaheadFunc(func() int64)
26 // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
27 // the underlying chunks become available.
31 // Piece range by piece index, [begin, end).
32 type pieceRange struct {
38 // Adjust the read/seek window to handle Readers locked to File extents and the like.
41 // Function to dynamically calculate readahead. If nil, readahead is static.
42 readaheadFunc func() int64
44 // Required when modifying pos and readahead.
48 // Position that reads have continued contiguously from.
49 contiguousReadStartPos int64
50 // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
51 // We cache this so that changes can be detected, and bubbled up to the Torrent only as
55 // Reads have been initiated since the last seek. This is used to prevent readaheads occurring
56 // after a seek or with a new reader at the starting position.
61 var _ io.ReadSeekCloser = (*reader)(nil)
63 func (r *reader) SetResponsive() {
65 r.t.cl.event.Broadcast()
68 // Disable responsive mode. TODO: Remove?
69 func (r *reader) SetNonResponsive() {
71 r.t.cl.event.Broadcast()
74 func (r *reader) SetReadahead(readahead int64) {
76 r.readahead = readahead
82 func (r *reader) SetReadaheadFunc(f func() int64) {
89 // How many bytes are available to read. Max is the most we could require.
90 func (r *reader) available(off, max int64) (ret int64) {
93 req, ok := r.t.offsetRequest(off)
97 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
100 if !r.t.haveChunk(req) {
103 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
108 // Ensure that ret hasn't exceeded our original max.
115 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
116 func (r *reader) piecesUncached() (ret pieceRange) {
118 if r.readaheadFunc != nil {
119 ra = r.readaheadFunc()
122 // Needs to be at least 1, because [x, x) means we don't want
129 if ra > r.length-r.pos {
130 ra = r.length - r.pos
132 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
136 func (r *reader) Read(b []byte) (n int, err error) {
137 return r.ReadContext(context.Background(), b)
140 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
143 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
144 // and take the lock here.
149 n, err = r.readOnceAt(ctx, b, r.pos)
151 if err == nil && len(b) > 0 {
152 panic("expected error")
162 if r.pos >= r.length {
164 } else if err == io.EOF {
165 err = io.ErrUnexpectedEOF
170 var closedChan = make(chan struct{})
176 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
177 // much should be readable without blocking.
178 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
182 avail = r.available(pos, wanted)
183 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
188 var dontWait <-chan struct{}
189 if !wait || wanted == 0 {
190 dontWait = closedChan
193 case <-r.t.closed.Done():
194 err = errors.New("torrent closed")
199 case <-r.t.dataDownloadDisallowed.On():
200 err = errors.New("torrent data downloading disabled")
201 case <-r.t.networkingEnabled.Off():
202 err = errors.New("torrent networking disabled")
211 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
212 // constrainted to a particular file within the torrent).
213 func (r *reader) torrentOffset(readerPos int64) int64 {
214 return r.offset + readerPos
217 // Performs at most one successful read to torrent storage.
218 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
225 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
229 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
230 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
231 b1 := missinggo.LimitLen(b, avail)
232 n, err = r.t.readAt(b1, r.torrentOffset(pos))
238 // TODO: Just reset pieces in the readahead window. This might help
239 // prevent thrashing with small caches and file and piece priorities.
240 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
241 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
242 if !r.t.updatePieceCompletion(firstPieceIndex) {
243 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
245 // Update the rest of the piece completions in the readahead window, without alerting to
246 // changes (since only the first piece, the one above, could have generated the read error
247 // we're currently handling).
248 if r.pieces.begin != firstPieceIndex {
249 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
251 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
252 r.t.updatePieceCompletion(index)
259 func (r *reader) Close() error {
266 func (r *reader) posChanged() {
267 to := r.piecesUncached()
273 // log.Printf("reader pos changed %v->%v", from, to)
274 r.t.readerPosChanged(from, to)
277 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
286 newPos = r.length + off
289 return 0, errors.New("bad whence")
294 r.contiguousReadStartPos = newPos
301 func (r *reader) log(m log.Msg) {
302 r.t.logger.Log(m.Skip(1))
305 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
306 func (r *reader) defaultReadaheadFunc() int64 {
307 return r.pos - r.contiguousReadStartPos