]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
Use iotest.TestReader
[btrtrc.git] / reader.go
1 package torrent
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "io"
8         "sync"
9
10         "github.com/anacrolix/log"
11         "github.com/anacrolix/missinggo"
12 )
13
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 {
17         io.Reader
18         io.Seeker
19         io.Closer
20         missinggo.ReadContexter
21         // Configure the number of bytes ahead of a read that should also be prioritized in preparation
22         // for further reads.
23         SetReadahead(int64)
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.
26         SetResponsive()
27 }
28
29 // Piece range by piece index, [begin, end).
30 type pieceRange struct {
31         begin, end pieceIndex
32 }
33
34 type reader struct {
35         t          *Torrent
36         responsive bool
37         // Adjust the read/seek window to handle Readers locked to File extents and the like.
38         offset, length int64
39         // Ensure operations that change the position are exclusive, like Read() and Seek().
40         opMu sync.Mutex
41
42         // Required when modifying pos and readahead, or reading them without opMu.
43         mu        sync.Locker
44         pos       int64
45         readahead int64
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
48         // required.
49         pieces pieceRange
50 }
51
52 var _ io.ReadCloser = (*reader)(nil)
53
54 func (r *reader) SetResponsive() {
55         r.responsive = true
56         r.t.cl.event.Broadcast()
57 }
58
59 // Disable responsive mode. TODO: Remove?
60 func (r *reader) SetNonResponsive() {
61         r.responsive = false
62         r.t.cl.event.Broadcast()
63 }
64
65 func (r *reader) SetReadahead(readahead int64) {
66         r.mu.Lock()
67         r.readahead = readahead
68         r.mu.Unlock()
69         r.t.cl.lock()
70         defer r.t.cl.unlock()
71         r.posChanged()
72 }
73
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) {
76         off += r.offset
77         for max > 0 {
78                 req, ok := r.t.offsetRequest(off)
79                 if !ok {
80                         break
81                 }
82                 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
83                         break
84                 }
85                 if !r.t.haveChunk(req) {
86                         break
87                 }
88                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
89                 max -= len1
90                 ret += len1
91                 off += len1
92         }
93         // Ensure that ret hasn't exceeded our original max.
94         if max < 0 {
95                 ret += max
96         }
97         return
98 }
99
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.
102         r.t.cl.event.Wait()
103 }
104
105 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
106 func (r *reader) piecesUncached() (ret pieceRange) {
107         ra := r.readahead
108         if ra < 1 {
109                 // Needs to be at least 1, because [x, x) means we don't want
110                 // anything.
111                 ra = 1
112         }
113         if ra > r.length-r.pos {
114                 ra = r.length - r.pos
115         }
116         ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
117         return
118 }
119
120 func (r *reader) Read(b []byte) (n int, err error) {
121         return r.ReadContext(context.Background(), b)
122 }
123
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
127         // synchronized.
128         var ctxErr error
129         if ctx.Done() != nil {
130                 ctx, cancel := context.WithCancel(ctx)
131                 // Abort the goroutine when the function returns.
132                 defer cancel()
133                 go func() {
134                         <-ctx.Done()
135                         r.t.cl.lock()
136                         ctxErr = ctx.Err()
137                         r.t.tickleReaders()
138                         r.t.cl.unlock()
139                 }()
140         }
141         // Hmmm, if a Read gets stuck, this means you can't change position for other purposes. That
142         // seems reasonable, but unusual.
143         r.opMu.Lock()
144         defer r.opMu.Unlock()
145         n, err = r.readOnceAt(b, r.pos, &ctxErr)
146         if n == 0 {
147                 if err == nil && len(b) > 0 {
148                         panic("expected error")
149                 } else {
150                         return
151                 }
152         }
153
154         r.mu.Lock()
155         r.pos += int64(n)
156         r.posChanged()
157         r.mu.Unlock()
158         if r.pos >= r.length {
159                 err = io.EOF
160         } else if err == io.EOF {
161                 err = io.ErrUnexpectedEOF
162         }
163         return
164 }
165
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) {
169         r.t.cl.lock()
170         defer r.t.cl.unlock()
171         for {
172                 avail = r.available(pos, wanted)
173                 if avail != 0 {
174                         return
175                 }
176                 if r.t.closed.IsSet() {
177                         err = errors.New("torrent closed")
178                         return
179                 }
180                 if *ctxErr != nil {
181                         err = *ctxErr
182                         return
183                 }
184                 if r.t.dataDownloadDisallowed || !r.t.networkingEnabled {
185                         err = errors.New("downloading disabled and data not already available")
186                         return
187                 }
188                 if !wait || wanted == 0 {
189                         return
190                 }
191                 r.waitReadable(pos)
192         }
193 }
194
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
199 }
200
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) {
203         if pos >= r.length {
204                 err = io.EOF
205                 return
206         }
207         for {
208                 var avail int64
209                 avail, err = r.waitAvailable(pos, int64(len(b)), ctxErr, n == 0)
210                 if avail == 0 {
211                         return
212                 }
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))
217                 if n != 0 {
218                         err = nil
219                         return
220                 }
221                 r.t.cl.lock()
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))
228                 }
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))
234                 }
235                 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
236                         r.t.updatePieceCompletion(index)
237                 }
238                 r.t.cl.unlock()
239         }
240 }
241
242 // Hodor
243 func (r *reader) Close() error {
244         r.t.cl.lock()
245         defer r.t.cl.unlock()
246         r.t.deleteReader(r)
247         return nil
248 }
249
250 func (r *reader) posChanged() {
251         to := r.piecesUncached()
252         from := r.pieces
253         if to == from {
254                 return
255         }
256         r.pieces = to
257         // log.Printf("reader pos changed %v->%v", from, to)
258         r.t.readerPosChanged(from, to)
259 }
260
261 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
262         r.opMu.Lock()
263         defer r.opMu.Unlock()
264
265         r.mu.Lock()
266         defer r.mu.Unlock()
267         switch whence {
268         case io.SeekStart:
269                 r.pos = off
270         case io.SeekCurrent:
271                 r.pos += off
272         case io.SeekEnd:
273                 r.pos = r.length + off
274         default:
275                 err = errors.New("bad whence")
276         }
277         ret = r.pos
278
279         r.posChanged()
280         return
281 }
282
283 func (r *reader) log(m log.Msg) {
284         r.t.logger.Log(m.Skip(1))
285 }