]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
Add default sqrt readahead algorithm
[btrtrc.git] / reader.go
1 package torrent
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "io"
8         "math"
9         "sync"
10
11         "github.com/anacrolix/log"
12         "github.com/anacrolix/missinggo/v2"
13 )
14
15 // Accesses Torrent data via a Client. Reads block until the data is available. Seeks and readahead
16 // also drive Client behaviour.
17 type Reader interface {
18         io.Reader
19         io.Seeker
20         io.Closer
21         missinggo.ReadContexter
22         // Configure the number of bytes ahead of a read that should also be prioritized in preparation
23         // for further reads.
24         SetReadahead(int64)
25         // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
26         // the underlying chunks become available.
27         SetResponsive()
28 }
29
30 // Piece range by piece index, [begin, end).
31 type pieceRange struct {
32         begin, end pieceIndex
33 }
34
35 type reader struct {
36         t          *Torrent
37         responsive bool
38         // Adjust the read/seek window to handle Readers locked to File extents and the like.
39         offset, length int64
40         // Ensure operations that change the position are exclusive, like Read() and Seek().
41         opMu sync.Mutex
42
43         // Required when modifying pos and readahead, or reading them without opMu.
44         mu        sync.Locker
45         pos       int64
46         readahead int64
47         // Function to dynamically calculate readahead. If nil, readahead is static.
48         readaheadFunc func() int64
49         // Position that reads have continued contiguously from.
50         contiguousReadStartPos int64
51         // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
52         // We cache this so that changes can be detected, and bubbled up to the Torrent only as
53         // required.
54         pieces pieceRange
55 }
56
57 var _ io.ReadCloser = (*reader)(nil)
58
59 func (r *reader) SetResponsive() {
60         r.responsive = true
61         r.t.cl.event.Broadcast()
62 }
63
64 // Disable responsive mode. TODO: Remove?
65 func (r *reader) SetNonResponsive() {
66         r.responsive = false
67         r.t.cl.event.Broadcast()
68 }
69
70 func (r *reader) SetReadahead(readahead int64) {
71         r.mu.Lock()
72         r.readahead = readahead
73         r.readaheadFunc = nil
74         r.mu.Unlock()
75         r.t.cl.lock()
76         defer r.t.cl.unlock()
77         r.posChanged()
78 }
79
80 // How many bytes are available to read. Max is the most we could require.
81 func (r *reader) available(off, max int64) (ret int64) {
82         off += r.offset
83         for max > 0 {
84                 req, ok := r.t.offsetRequest(off)
85                 if !ok {
86                         break
87                 }
88                 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
89                         break
90                 }
91                 if !r.t.haveChunk(req) {
92                         break
93                 }
94                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
95                 max -= len1
96                 ret += len1
97                 off += len1
98         }
99         // Ensure that ret hasn't exceeded our original max.
100         if max < 0 {
101                 ret += max
102         }
103         return
104 }
105
106 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
107 func (r *reader) piecesUncached() (ret pieceRange) {
108         ra := r.readahead
109         if r.readaheadFunc != nil {
110                 ra = r.readaheadFunc()
111         }
112         if ra < 1 {
113                 // Needs to be at least 1, because [x, x) means we don't want
114                 // anything.
115                 ra = 1
116         }
117         if ra > r.length-r.pos {
118                 ra = r.length - r.pos
119         }
120         ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
121         return
122 }
123
124 func (r *reader) Read(b []byte) (n int, err error) {
125         return r.ReadContext(context.Background(), b)
126 }
127
128 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
129         // Hmmm, if a Read gets stuck, this means you can't change position for other purposes. That
130         // seems reasonable, but unusual.
131         r.opMu.Lock()
132         defer r.opMu.Unlock()
133         n, err = r.readOnceAt(ctx, b, r.pos)
134         if n == 0 {
135                 if err == nil && len(b) > 0 {
136                         panic("expected error")
137                 } else {
138                         return
139                 }
140         }
141
142         r.mu.Lock()
143         r.pos += int64(n)
144         r.posChanged()
145         r.mu.Unlock()
146         if r.pos >= r.length {
147                 err = io.EOF
148         } else if err == io.EOF {
149                 err = io.ErrUnexpectedEOF
150         }
151         return
152 }
153
154 var closedChan = make(chan struct{})
155
156 func init() {
157         close(closedChan)
158 }
159
160 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
161 // much should be readable without blocking.
162 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
163         t := r.t
164         for {
165                 r.t.cl.rLock()
166                 avail = r.available(pos, wanted)
167                 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
168                 r.t.cl.rUnlock()
169                 if avail != 0 {
170                         return
171                 }
172                 var dontWait <-chan struct{}
173                 if !wait || wanted == 0 {
174                         dontWait = closedChan
175                 }
176                 select {
177                 case <-r.t.closed.Done():
178                         err = errors.New("torrent closed")
179                         return
180                 case <-ctx.Done():
181                         err = ctx.Err()
182                         return
183                 case <-r.t.dataDownloadDisallowed.On():
184                         err = errors.New("torrent data downloading disabled")
185                 case <-r.t.networkingEnabled.Off():
186                         err = errors.New("torrent networking disabled")
187                         return
188                 case <-dontWait:
189                         return
190                 case <-readerCond:
191                 }
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(ctx context.Context, b []byte, pos int64) (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(ctx, pos, int64(len(b)), 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) (newPos int64, err error) {
262         r.opMu.Lock()
263         defer r.opMu.Unlock()
264         r.mu.Lock()
265         defer r.mu.Unlock()
266         newPos, err = func() (int64, error) {
267                 switch whence {
268                 case io.SeekStart:
269                         return off, err
270                 case io.SeekCurrent:
271                         return r.pos + off, nil
272                 case io.SeekEnd:
273                         return r.length + off, nil
274                 default:
275                         return r.pos, errors.New("bad whence")
276                 }
277         }()
278         if err != nil {
279                 return
280         }
281         if newPos == r.pos {
282                 return
283         }
284         r.pos = newPos
285         r.contiguousReadStartPos = newPos
286
287         r.posChanged()
288         return
289 }
290
291 func (r *reader) log(m log.Msg) {
292         r.t.logger.Log(m.Skip(1))
293 }
294
295 // Implementation inspired from an arbitrary comment I found on HN.
296 func (r *reader) sqrtReadahead() int64 {
297         return int64(math.Sqrt(float64(r.pos - r.contiguousReadStartPos)))
298 }