10 "github.com/anacrolix/log"
11 "github.com/anacrolix/missinggo"
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 // 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
52 var _ io.ReadCloser = (*reader)(nil)
54 func (r *reader) SetResponsive() {
56 r.t.cl.event.Broadcast()
59 // Disable responsive mode. TODO: Remove?
60 func (r *reader) SetNonResponsive() {
62 r.t.cl.event.Broadcast()
65 func (r *reader) SetReadahead(readahead int64) {
67 r.readahead = readahead
74 // How many bytes are available to read. Max is the most we could require.
75 func (r *reader) available(off, max int64) (ret int64) {
78 req, ok := r.t.offsetRequest(off)
82 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
85 if !r.t.haveChunk(req) {
88 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
93 // Ensure that ret hasn't exceeded our original max.
100 func (r *reader) waitReadable(off int64) {
101 // We may have been sent back here because we were told we could read but it failed.
105 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
106 func (r *reader) piecesUncached() (ret pieceRange) {
109 // Needs to be at least 1, because [x, x) means we don't want
113 if ra > r.length-r.pos {
114 ra = r.length - r.pos
116 ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
120 func (r *reader) Read(b []byte) (n int, err error) {
121 return r.ReadContext(context.Background(), b)
124 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
125 // This is set under the Client lock if the Context is canceled. I think we coordinate on a
126 // separate variable so as to avoid false negatives with race conditions due to Contexts being
129 if ctx.Done() != nil {
130 ctx, cancel := context.WithCancel(ctx)
131 // Abort the goroutine when the function returns.
141 // Hmmm, if a Read gets stuck, this means you can't change position for other purposes. That
142 // seems reasonable, but unusual.
144 defer r.opMu.Unlock()
145 n, err = r.readOnceAt(b, r.pos, &ctxErr)
148 panic("expected error")
158 if r.pos >= r.length {
160 } else if err == io.EOF {
161 err = io.ErrUnexpectedEOF
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(pos, wanted int64, ctxErr *error, wait bool) (avail int64, err error) {
170 defer r.t.cl.unlock()
172 avail = r.available(pos, wanted)
176 if r.t.closed.IsSet() {
177 err = errors.New("torrent closed")
184 if r.t.dataDownloadDisallowed || !r.t.networkingEnabled {
185 err = errors.New("downloading disabled and data not already available")
195 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
196 // constrainted to a particular file within the torrent).
197 func (r *reader) torrentOffset(readerPos int64) int64 {
198 return r.offset + readerPos
201 // Performs at most one successful read to torrent storage.
202 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
209 avail, err = r.waitAvailable(pos, int64(len(b)), ctxErr, n == 0)
213 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
214 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
215 b1 := missinggo.LimitLen(b, avail)
216 n, err = r.t.readAt(b1, r.torrentOffset(pos))
222 // TODO: Just reset pieces in the readahead window. This might help
223 // prevent thrashing with small caches and file and piece priorities.
224 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
225 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
226 if !r.t.updatePieceCompletion(firstPieceIndex) {
227 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
229 // Update the rest of the piece completions in the readahead window, without alerting to
230 // changes (since only the first piece, the one above, could have generated the read error
231 // we're currently handling).
232 if r.pieces.begin != firstPieceIndex {
233 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
235 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
236 r.t.updatePieceCompletion(index)
243 func (r *reader) Close() error {
245 defer r.t.cl.unlock()
250 func (r *reader) posChanged() {
251 to := r.piecesUncached()
257 // log.Printf("reader pos changed %v->%v", from, to)
258 r.t.readerPosChanged(from, to)
261 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
263 defer r.opMu.Unlock()
273 r.pos = r.length + off
275 err = errors.New("bad whence")
283 func (r *reader) log(m log.Msg) {
284 r.t.logger.Log(m.Skip(1))