]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
go fmt ./...
[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.
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.
21         SetReadahead(int64)
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.
24         SetResponsive()
25 }
26
27 // Piece range by piece index, [begin, end).
28 type pieceRange struct {
29         begin, end pieceIndex
30 }
31
32 type reader struct {
33         t *Torrent
34         // Adjust the read/seek window to handle Readers locked to File extents and the like.
35         offset, length int64
36
37         // Function to dynamically calculate readahead. If nil, readahead is static.
38         readaheadFunc func() int64
39
40         // Required when modifying pos and readahead.
41         mu sync.Locker
42
43         readahead, pos int64
44         // Position that reads have continued contiguously from.
45         contiguousReadStartPos 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         // Reads have been initiated since the last seek. This is used to prevent readaheads occurring
52         // after a seek or with a new reader at the starting position.
53         reading    bool
54         responsive bool
55 }
56
57 var _ io.ReadSeekCloser = (*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.posChanged()
75         r.mu.Unlock()
76 }
77
78 // How many bytes are available to read. Max is the most we could require.
79 func (r *reader) available(off, max int64) (ret int64) {
80         off += r.offset
81         for max > 0 {
82                 req, ok := r.t.offsetRequest(off)
83                 if !ok {
84                         break
85                 }
86                 if !r.responsive && !r.t.pieceComplete(pieceIndex(req.Index)) {
87                         break
88                 }
89                 if !r.t.haveChunk(req) {
90                         break
91                 }
92                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
93                 max -= len1
94                 ret += len1
95                 off += len1
96         }
97         // Ensure that ret hasn't exceeded our original max.
98         if max < 0 {
99                 ret += max
100         }
101         return
102 }
103
104 // Calculates the pieces this reader wants downloaded, ignoring the cached value at r.pieces.
105 func (r *reader) piecesUncached() (ret pieceRange) {
106         ra := r.readahead
107         if r.readaheadFunc != nil {
108                 ra = r.readaheadFunc()
109         }
110         if ra < 1 {
111                 // Needs to be at least 1, because [x, x) means we don't want
112                 // anything.
113                 ra = 1
114         }
115         if !r.reading {
116                 ra = 0
117         }
118         if ra > r.length-r.pos {
119                 ra = r.length - r.pos
120         }
121         ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
122         return
123 }
124
125 func (r *reader) Read(b []byte) (n int, err error) {
126         return r.ReadContext(context.Background(), b)
127 }
128
129 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
130         if len(b) > 0 {
131                 r.reading = true
132                 // TODO: Rework reader piece priorities so we don't have to push updates in to the Client
133                 // and take the lock here.
134                 r.mu.Lock()
135                 r.posChanged()
136                 r.mu.Unlock()
137         }
138         n, err = r.readOnceAt(ctx, b, r.pos)
139         if n == 0 {
140                 if err == nil && len(b) > 0 {
141                         panic("expected error")
142                 } else {
143                         return
144                 }
145         }
146
147         r.mu.Lock()
148         r.pos += int64(n)
149         r.posChanged()
150         r.mu.Unlock()
151         if r.pos >= r.length {
152                 err = io.EOF
153         } else if err == io.EOF {
154                 err = io.ErrUnexpectedEOF
155         }
156         return
157 }
158
159 var closedChan = make(chan struct{})
160
161 func init() {
162         close(closedChan)
163 }
164
165 // Wait until some data should be available to read. Tickles the client if it isn't. Returns how
166 // much should be readable without blocking.
167 func (r *reader) waitAvailable(ctx context.Context, pos, wanted int64, wait bool) (avail int64, err error) {
168         t := r.t
169         for {
170                 r.t.cl.rLock()
171                 avail = r.available(pos, wanted)
172                 readerCond := t.piece(int((r.offset + pos) / t.info.PieceLength)).readerCond.Signaled()
173                 r.t.cl.rUnlock()
174                 if avail != 0 {
175                         return
176                 }
177                 var dontWait <-chan struct{}
178                 if !wait || wanted == 0 {
179                         dontWait = closedChan
180                 }
181                 select {
182                 case <-r.t.closed.Done():
183                         err = errors.New("torrent closed")
184                         return
185                 case <-ctx.Done():
186                         err = ctx.Err()
187                         return
188                 case <-r.t.dataDownloadDisallowed.On():
189                         err = errors.New("torrent data downloading disabled")
190                 case <-r.t.networkingEnabled.Off():
191                         err = errors.New("torrent networking disabled")
192                         return
193                 case <-dontWait:
194                         return
195                 case <-readerCond:
196                 }
197         }
198 }
199
200 // Adds the reader's torrent offset to the reader object offset (for example the reader might be
201 // constrainted to a particular file within the torrent).
202 func (r *reader) torrentOffset(readerPos int64) int64 {
203         return r.offset + readerPos
204 }
205
206 // Performs at most one successful read to torrent storage.
207 func (r *reader) readOnceAt(ctx context.Context, b []byte, pos int64) (n int, err error) {
208         if pos >= r.length {
209                 err = io.EOF
210                 return
211         }
212         for {
213                 var avail int64
214                 avail, err = r.waitAvailable(ctx, pos, int64(len(b)), n == 0)
215                 if avail == 0 {
216                         return
217                 }
218                 firstPieceIndex := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
219                 firstPieceOffset := r.torrentOffset(pos) % r.t.info.PieceLength
220                 b1 := missinggo.LimitLen(b, avail)
221                 n, err = r.t.readAt(b1, r.torrentOffset(pos))
222                 if n != 0 {
223                         err = nil
224                         return
225                 }
226                 r.t.cl.lock()
227                 // TODO: Just reset pieces in the readahead window. This might help
228                 // prevent thrashing with small caches and file and piece priorities.
229                 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
230                         r.t.infoHash.HexString(), firstPieceIndex, firstPieceOffset, len(b1), err))
231                 if !r.t.updatePieceCompletion(firstPieceIndex) {
232                         r.log(log.Fstr("piece %d completion unchanged", firstPieceIndex))
233                 }
234                 // Update the rest of the piece completions in the readahead window, without alerting to
235                 // changes (since only the first piece, the one above, could have generated the read error
236                 // we're currently handling).
237                 if r.pieces.begin != firstPieceIndex {
238                         panic(fmt.Sprint(r.pieces.begin, firstPieceIndex))
239                 }
240                 for index := r.pieces.begin + 1; index < r.pieces.end; index++ {
241                         r.t.updatePieceCompletion(index)
242                 }
243                 r.t.cl.unlock()
244         }
245 }
246
247 // Hodor
248 func (r *reader) Close() error {
249         r.t.cl.lock()
250         r.t.deleteReader(r)
251         r.t.cl.unlock()
252         return nil
253 }
254
255 func (r *reader) posChanged() {
256         to := r.piecesUncached()
257         from := r.pieces
258         if to == from {
259                 return
260         }
261         r.pieces = to
262         // log.Printf("reader pos changed %v->%v", from, to)
263         r.t.readerPosChanged(from, to)
264 }
265
266 func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
267         switch whence {
268         case io.SeekStart:
269                 newPos = off
270                 r.mu.Lock()
271         case io.SeekCurrent:
272                 r.mu.Lock()
273                 newPos = r.pos + off
274         case io.SeekEnd:
275                 newPos = r.length + off
276                 r.mu.Lock()
277         default:
278                 return 0, errors.New("bad whence")
279         }
280         if newPos != r.pos {
281                 r.reading = false
282                 r.pos = newPos
283                 r.contiguousReadStartPos = newPos
284                 r.posChanged()
285         }
286         r.mu.Unlock()
287         return
288 }
289
290 func (r *reader) log(m log.Msg) {
291         r.t.logger.Log(m.Skip(1))
292 }
293
294 // Implementation inspired by https://news.ycombinator.com/item?id=27019613.
295 func (r *reader) defaultReadaheadFunc() int64 {
296         return r.pos - r.contiguousReadStartPos
297 }