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 {
35 // Adjust the read/seek window to handle Readers locked to File extents and the like.
38 // Required when modifying pos and readahead, or reading them without opMu.
41 // Reads have been initiated since the last seek. This is used to prevent readahead occuring
42 // after a seek or with a new reader at the starting position.
45 // Function to dynamically calculate readahead. If nil, readahead is static.
46 readaheadFunc func() int64
47 // Position that reads have continued contiguously from.
48 contiguousReadStartPos int64
49 // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
50 // We cache this so that changes can be detected, and bubbled up to the Torrent only as
55 var _ io.ReadSeekCloser = (*reader)(nil)
57 func (r *reader) SetResponsive() {
59 r.t.cl.event.Broadcast()
62 // Disable responsive mode. TODO: Remove?
63 func (r *reader) SetNonResponsive() {
65 r.t.cl.event.Broadcast()
68 func (r *reader) SetReadahead(readahead int64) {
71 r.readahead = readahead
76 // How many bytes are available to read. Max is the most we could require.
77 func (r *reader) available(off, max int64) (ret int64) {
80 req, ok := r.t.offsetRequest(off)
84 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
87 if !r.t.haveChunk(req) {
90 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
95 // Ensure that ret hasn't exceeded our original max.
102 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
103 func (r *reader) piecesUncached() (ret pieceRange) {
105 if r.readaheadFunc != nil {
106 ra = r.readaheadFunc()
109 // 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) {
130 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
131 // and take the lock here.
136 n, err = r.readOnceAt(ctx, b, r.pos)
138 if err == nil && len(b) > 0 {
139 panic("expected error")
149 if r.pos >= r.length {
151 } else if err == io.EOF {
152 err = io.ErrUnexpectedEOF
157 var closedChan = make(chan struct{})
163 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
164 // much should be readable without blocking.
165 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
169 avail = r.available(pos, wanted)
170 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
175 var dontWait <-chan struct{}
176 if !wait || wanted == 0 {
177 dontWait = closedChan
180 case <-r.t.closed.Done():
181 err = errors.New("torrent closed")
186 case <-r.t.dataDownloadDisallowed.On():
187 err = errors.New("torrent data downloading disabled")
188 case <-r.t.networkingEnabled.Off():
189 err = errors.New("torrent networking disabled")
198 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
199 // constrainted to a particular file within the torrent).
200 func (r *reader) torrentOffset(readerPos int64) int64 {
201 return r.offset + readerPos
204 // Performs at most one successful read to torrent storage.
205 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
212 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
216 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
217 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
218 b1 := missinggo.LimitLen(b, avail)
219 n, err = r.t.readAt(b1, r.torrentOffset(pos))
225 // TODO: Just reset pieces in the readahead window. This might help
226 // prevent thrashing with small caches and file and piece priorities.
227 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
228 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
229 if !r.t.updatePieceCompletion(firstPieceIndex) {
230 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
232 // Update the rest of the piece completions in the readahead window, without alerting to
233 // changes (since only the first piece, the one above, could have generated the read error
234 // we're currently handling).
235 if r.pieces.begin != firstPieceIndex {
236 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
238 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
239 r.t.updatePieceCompletion(index)
246 func (r *reader) Close() error {
248 defer r.t.cl.unlock()
253 func (r *reader) posChanged() {
254 to := r.piecesUncached()
260 // log.Printf("reader pos changed %v->%v", from, to)
261 r.t.readerPosChanged(from, to)
264 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
267 newPos, err = func() (int64, error) {
272 return r.pos + off, nil
274 return r.length + off, nil
276 return r.pos, errors.New("bad whence")
287 r.contiguousReadStartPos = newPos
293 func (r *reader) log(m log.Msg) {
294 r.t.logger.Log(m.Skip(1))
297 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
298 func (r *reader) defaultReadaheadFunc() int64 {
299 return r.pos - r.contiguousReadStartPos