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 {
20 missinggo.ReadContexter
21 // Configure the number of bytes ahead of a read that should also be prioritized in preparation
24 // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
25 // the underlying chunks become available.
29 // Piece range by piece index, [begin, end).
30 type pieceRange struct {
37 // Adjust the read/seek window to handle Readers locked to File extents and the like.
39 // Ensure operations that change the position are exclusive, like Read() and Seek().
42 // Required when modifying pos and readahead, or reading them without opMu.
45 // Reads have been initiated since the last seek. This is used to prevent readahead occuring
46 // after a seek or with a new reader at the starting position.
49 // Function to dynamically calculate readahead. If nil, readahead is static.
50 readaheadFunc func() int64
51 // Position that reads have continued contiguously from.
52 contiguousReadStartPos int64
53 // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
54 // We cache this so that changes can be detected, and bubbled up to the Torrent only as
59 var _ io.ReadCloser = (*reader)(nil)
61 func (r *reader) SetResponsive() {
63 r.t.cl.event.Broadcast()
66 // Disable responsive mode. TODO: Remove?
67 func (r *reader) SetNonResponsive() {
69 r.t.cl.event.Broadcast()
72 func (r *reader) SetReadahead(readahead int64) {
74 r.readahead = readahead
82 // How many bytes are available to read. Max is the most we could require.
83 func (r *reader) available(off, max int64) (ret int64) {
86 req, ok := r.t.offsetRequest(off)
90 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
93 if !r.t.haveChunk(req) {
96 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
101 // Ensure that ret hasn't exceeded our original max.
108 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
109 func (r *reader) piecesUncached() (ret pieceRange) {
111 if r.readaheadFunc != nil {
112 ra = r.readaheadFunc()
115 // Needs to be at least 1, because [x, x) means we don't want
122 if ra > r.length-r.pos {
123 ra = r.length - r.pos
125 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
129 func (r *reader) Read(b []byte) (n int, err error) {
130 return r.ReadContext(context.Background(), b)
133 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
134 // Hmmm, if a Read gets stuck, this means you can't change position for other purposes. That
135 // seems reasonable, but unusual.
137 defer r.opMu.Unlock()
140 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
141 // and take the lock here.
146 n, err = r.readOnceAt(ctx, b, r.pos)
148 if err == nil && len(b) > 0 {
149 panic("expected error")
159 if r.pos >= r.length {
161 } else if err == io.EOF {
162 err = io.ErrUnexpectedEOF
167 var closedChan = make(chan struct{})
173 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
174 // much should be readable without blocking.
175 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
179 avail = r.available(pos, wanted)
180 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
185 var dontWait <-chan struct{}
186 if !wait || wanted == 0 {
187 dontWait = closedChan
190 case <-r.t.closed.Done():
191 err = errors.New("torrent closed")
196 case <-r.t.dataDownloadDisallowed.On():
197 err = errors.New("torrent data downloading disabled")
198 case <-r.t.networkingEnabled.Off():
199 err = errors.New("torrent networking disabled")
208 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
209 // constrainted to a particular file within the torrent).
210 func (r *reader) torrentOffset(readerPos int64) int64 {
211 return r.offset + readerPos
214 // Performs at most one successful read to torrent storage.
215 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
222 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
226 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
227 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
228 b1 := missinggo.LimitLen(b, avail)
229 n, err = r.t.readAt(b1, r.torrentOffset(pos))
235 // TODO: Just reset pieces in the readahead window. This might help
236 // prevent thrashing with small caches and file and piece priorities.
237 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
238 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
239 if !r.t.updatePieceCompletion(firstPieceIndex) {
240 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
242 // Update the rest of the piece completions in the readahead window, without alerting to
243 // changes (since only the first piece, the one above, could have generated the read error
244 // we're currently handling).
245 if r.pieces.begin != firstPieceIndex {
246 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
248 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
249 r.t.updatePieceCompletion(index)
256 func (r *reader) Close() error {
258 defer r.t.cl.unlock()
263 func (r *reader) posChanged() {
264 to := r.piecesUncached()
270 // log.Printf("reader pos changed %v->%v", from, to)
271 r.t.readerPosChanged(from, to)
274 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
276 defer r.opMu.Unlock()
279 newPos, err = func() (int64, error) {
284 return r.pos + off, nil
286 return r.length + off, nil
288 return r.pos, errors.New("bad whence")
299 r.contiguousReadStartPos = newPos
305 func (r *reader) log(m log.Msg) {
306 r.t.logger.Log(m.Skip(1))
309 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
310 func (r *reader) defaultReadaheadFunc() int64 {
311 return r.pos - r.contiguousReadStartPos