]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
Drop support for go 1.20
[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/v2"
12 )
13
14 // Accesses Torrent data via a Client. Reads block until the data is available. Seeks and readahead
15 // also drive Client behaviour. Not safe for concurrent use.
16 type Reader interface {
17         io.ReadSeekCloser
18         missinggo.ReadContexter
19         // Configure the number of bytes ahead of a read that should also be prioritized in preparation
20         // for further reads. Overridden by non-nil readahead func, see SetReadaheadFunc.
21         SetReadahead(int64)
22         // If non-nil, the provided function is called when the implementation needs to know the
23         // readahead for the current reader. Calls occur during Reads and Seeks, and while the Client is
24         // locked.
25         SetReadaheadFunc(ReadaheadFunc)
26         // Don't wait for pieces to complete and be verified. Read calls return as soon as they can when
27         // the underlying chunks become available.
28         SetResponsive()
29 }
30
31 // Piece range by piece index, [begin, end).
32 type pieceRange struct {
33         begin, end pieceIndex
34 }
35
36 type ReadaheadContext struct {
37         ContiguousReadStartPos int64
38         CurrentPos             int64
39 }
40
41 // Returns the desired readahead for a Reader.
42 type ReadaheadFunc func(ReadaheadContext) int64
43
44 type reader struct {
45         t *Torrent
46         // Adjust the read/seek window to handle Readers locked to File extents and the like.
47         offset, length int64
48
49         // Function to dynamically calculate readahead. If nil, readahead is static.
50         readaheadFunc ReadaheadFunc
51
52         // Required when modifying pos and readahead.
53         mu sync.Locker
54
55         readahead, pos int64
56         // Position that reads have continued contiguously from.
57         contiguousReadStartPos int64
58         // The cached piece range this reader wants downloaded. The zero value corresponds to nothing.
59         // We cache this so that changes can be detected, and bubbled up to the Torrent only as
60         // required.
61         pieces pieceRange
62
63         // Reads have been initiated since the last seek. This is used to prevent readaheads occurring
64         // after a seek or with a new reader at the starting position.
65         reading    bool
66         responsive bool
67 }
68
69 var _ io.ReadSeekCloser = (*reader)(nil)
70
71 func (r *reader) SetResponsive() {
72         r.responsive = true
73         r.t.cl.event.Broadcast()
74 }
75
76 // Disable responsive mode. TODO: Remove?
77 func (r *reader) SetNonResponsive() {
78         r.responsive = false
79         r.t.cl.event.Broadcast()
80 }
81
82 func (r *reader) SetReadahead(readahead int64) {
83         r.mu.Lock()
84         r.readahead = readahead
85         r.readaheadFunc = nil
86         r.posChanged()
87         r.mu.Unlock()
88 }
89
90 func (r *reader) SetReadaheadFunc(f ReadaheadFunc) {
91         r.mu.Lock()
92         r.readaheadFunc = f
93         r.posChanged()
94         r.mu.Unlock()
95 }
96
97 // How many bytes are available to read. Max is the most we could require.
98 func (r *reader) available(off, max int64) (ret int64) {
99         off += r.offset
100         for max > 0 {
101                 req, ok := r.t.offsetRequest(off)
102                 if !ok {
103                         break
104                 }
105                 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
106                         break
107                 }
108                 if !r.t.haveChunk(req) {
109                         break
110                 }
111                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
112                 max -= len1
113                 ret += len1
114                 off += len1
115         }
116         // Ensure that ret hasn't exceeded our original max.
117         if max < 0 {
118                 ret += max
119         }
120         return
121 }
122
123 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
124 func (r *reader) piecesUncached() (ret pieceRange) {
125         ra := r.readahead
126         if r.readaheadFunc != nil {
127                 ra = r.readaheadFunc(ReadaheadContext{
128                         ContiguousReadStartPos: r.contiguousReadStartPos,
129                         CurrentPos:             r.pos,
130                 })
131         }
132         if ra < 1 {
133                 // Needs to be at least 1, because [x, x) means we don't want
134                 // anything.
135                 ra = 1
136         }
137         if !r.reading {
138                 ra = 0
139         }
140         if ra > r.length-r.pos {
141                 ra = r.length - r.pos
142         }
143         ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
144         return
145 }
146
147 func (r *reader) Read(b []byte) (n int, err error) {
148         return r.ReadContext(context.Background(), b)
149 }
150
151 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
152         if len(b) > 0 {
153                 r.reading = true
154                 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
155                 // and take the lock here.
156                 r.mu.Lock()
157                 r.posChanged()
158                 r.mu.Unlock()
159         }
160         n, err = r.readOnceAt(ctx, b, r.pos)
161         if n == 0 {
162                 if err == nil && len(b) > 0 {
163                         panic("expected error")
164                 } else {
165                         return
166                 }
167         }
168
169         r.mu.Lock()
170         r.pos += int64(n)
171         r.posChanged()
172         r.mu.Unlock()
173         if r.pos >= r.length {
174                 err = io.EOF
175         } else if err == io.EOF {
176                 err = io.ErrUnexpectedEOF
177         }
178         return
179 }
180
181 var closedChan = make(chan struct{})
182
183 func init() {
184         close(closedChan)
185 }
186
187 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
188 // much should be readable without blocking.
189 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
190         t := r.t
191         for {
192                 r.t.cl.rLock()
193                 avail = r.available(pos, wanted)
194                 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
195                 r.t.cl.rUnlock()
196                 if avail != 0 {
197                         return
198                 }
199                 var dontWait <-chan struct{}
200                 if !wait || wanted == 0 {
201                         dontWait = closedChan
202                 }
203                 select {
204                 case <-r.t.closed.Done():
205                         err = errors.New("torrent closed")
206                         return
207                 case <-ctx.Done():
208                         err = ctx.Err()
209                         return
210                 case <-r.t.dataDownloadDisallowed.On():
211                         err = errors.New("torrent data downloading disabled")
212                 case <-r.t.networkingEnabled.Off():
213                         err = errors.New("torrent networking disabled")
214                         return
215                 case <-dontWait:
216                         return
217                 case <-readerCond:
218                 }
219         }
220 }
221
222 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
223 // constrainted to a particular file within the torrent).
224 func (r *reader) torrentOffset(readerPos int64) int64 {
225         return r.offset + readerPos
226 }
227
228 // Performs at most one successful read to torrent storage.
229 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
230         if pos >= r.length {
231                 err = io.EOF
232                 return
233         }
234         for {
235                 var avail int64
236                 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
237                 if avail == 0 {
238                         return
239                 }
240                 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
241                 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
242                 b1 := missinggo.LimitLen(b, avail)
243                 n, err = r.t.readAt(b1, r.torrentOffset(pos))
244                 if n != 0 {
245                         err = nil
246                         return
247                 }
248                 if r.t.closed.IsSet() {
249                         err = fmt.Errorf("reading from closed torrent: %w", err)
250                         return
251                 }
252                 r.t.cl.lock()
253                 // I think there's a panic here caused by the Client being closed before obtaining this
254                 // lock. TestDropTorrentWithMmapStorageWhileHashing seems to tickle occasionally in CI.
255                 func() {
256                         // Just add exceptions already.
257                         defer r.t.cl.unlock()
258                         if r.t.closed.IsSet() {
259                                 // Can't update because Torrent's piece order is removed from Client.
260                                 return
261                         }
262                         // TODO: Just reset pieces in the readahead window. This might help
263                         // prevent thrashing with small caches and file and piece priorities.
264                         r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
265                                 r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
266                         if !r.t.updatePieceCompletion(firstPieceIndex) {
267                                 r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
268                         }
269                         // Update the rest of the piece completions in the readahead window, without alerting to
270                         // changes (since only the first piece, the one above, could have generated the read error
271                         // we're currently handling).
272                         if r.pieces.begin != firstPieceIndex {
273                                 panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
274                         }
275                         for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
276                                 r.t.updatePieceCompletion(index)
277                         }
278                 }()
279         }
280 }
281
282 // Hodor
283 func (r *reader) Close() error {
284         r.t.cl.lock()
285         r.t.deleteReader(r)
286         r.t.cl.unlock()
287         return nil
288 }
289
290 func (r *reader) posChanged() {
291         to := r.piecesUncached()
292         from := r.pieces
293         if to == from {
294                 return
295         }
296         r.pieces = to
297         // log.Printf("reader pos changed %v->%v", from, to)
298         r.t.readerPosChanged(from, to)
299 }
300
301 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
302         switch whence {
303         case io.SeekStart:
304                 newPos = off
305                 r.mu.Lock()
306         case io.SeekCurrent:
307                 r.mu.Lock()
308                 newPos = r.pos + off
309         case io.SeekEnd:
310                 newPos = r.length + off
311                 r.mu.Lock()
312         default:
313                 return 0, errors.New("bad whence")
314         }
315         if newPos != r.pos {
316                 r.reading = false
317                 r.pos = newPos
318                 r.contiguousReadStartPos = newPos
319                 r.posChanged()
320         }
321         r.mu.Unlock()
322         return
323 }
324
325 func (r *reader) log(m log.Msg) {
326         r.t.logger.LogLevel(log.Debug, m.Skip(1))
327 }
328
329 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
330 func defaultReadaheadFunc(r ReadaheadContext) int64 {
331         return r.CurrentPos - r.ContiguousReadStartPos
332 }