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.
46 // Function to dynamically calculate readahead. If nil, readahead is static.
47 readaheadFunc func() int64
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
56 var _ io.ReadCloser = (*reader)(nil)
58 func (r *reader) SetResponsive() {
60 r.t.cl.event.Broadcast()
63 // Disable responsive mode. TODO: Remove?
64 func (r *reader) SetNonResponsive() {
66 r.t.cl.event.Broadcast()
69 func (r *reader) SetReadahead(readahead int64) {
71 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
116 if ra > r.length-r.pos {
117 ra = r.length - r.pos
119 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
123 func (r *reader) Read(b []byte) (n int, err error) {
124 return r.ReadContext(context.Background(), b)
127 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
128 // Hmmm, if a Read gets stuck, this means you can't change position for other purposes. That
129 // seems reasonable, but unusual.
131 defer r.opMu.Unlock()
132 n, err = r.readOnceAt(ctx, b, r.pos)
134 if err == nil && len(b) > 0 {
135 panic("expected error")
145 if r.pos >= r.length {
147 } else if err == io.EOF {
148 err = io.ErrUnexpectedEOF
153 var closedChan = make(chan struct{})
159 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
160 // much should be readable without blocking.
161 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
165 avail = r.available(pos, wanted)
166 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
171 var dontWait <-chan struct{}
172 if !wait || wanted == 0 {
173 dontWait = closedChan
176 case <-r.t.closed.Done():
177 err = errors.New("torrent closed")
182 case <-r.t.dataDownloadDisallowed.On():
183 err = errors.New("torrent data downloading disabled")
184 case <-r.t.networkingEnabled.Off():
185 err = errors.New("torrent networking disabled")
194 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
195 // constrainted to a particular file within the torrent).
196 func (r *reader) torrentOffset(readerPos int64) int64 {
197 return r.offset + readerPos
200 // Performs at most one successful read to torrent storage.
201 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
208 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
212 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
213 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
214 b1 := missinggo.LimitLen(b, avail)
215 n, err = r.t.readAt(b1, r.torrentOffset(pos))
221 // TODO: Just reset pieces in the readahead window. This might help
222 // prevent thrashing with small caches and file and piece priorities.
223 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
224 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
225 if !r.t.updatePieceCompletion(firstPieceIndex) {
226 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
228 // Update the rest of the piece completions in the readahead window, without alerting to
229 // changes (since only the first piece, the one above, could have generated the read error
230 // we're currently handling).
231 if r.pieces.begin != firstPieceIndex {
232 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
234 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
235 r.t.updatePieceCompletion(index)
242 func (r *reader) Close() error {
244 defer r.t.cl.unlock()
249 func (r *reader) posChanged() {
250 to := r.piecesUncached()
256 // log.Printf("reader pos changed %v->%v", from, to)
257 r.t.readerPosChanged(from, to)
260 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
262 defer r.opMu.Unlock()
265 newPos, err = func() (int64, error) {
270 return r.pos + off, nil
272 return r.length + off, nil
274 return r.pos, errors.New("bad whence")
284 r.contiguousReadStartPos = newPos
290 func (r *reader) log(m log.Msg) {
291 r.t.logger.Log(m.Skip(1))
294 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
295 func (r *reader) defaultReadaheadFunc() int64 {
296 return r.pos - r.contiguousReadStartPos