]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
Make Reader log through its parent
[btrtrc.git] / reader.go
1 package torrent
2
3 import (
4         "context"
5         "errors"
6         "io"
7         "sync"
8
9         "github.com/anacrolix/log"
10         "github.com/anacrolix/missinggo"
11 )
12
13 type Reader interface {
14         io.Reader
15         io.Seeker
16         io.Closer
17         missinggo.ReadContexter
18         SetReadahead(int64)
19         SetResponsive()
20 }
21
22 // Piece range by piece index, [begin, end).
23 type pieceRange struct {
24         begin, end pieceIndex
25 }
26
27 // Accesses Torrent data via a Client. Reads block until the data is
28 // available. Seeks and readahead also drive Client behaviour.
29 type reader struct {
30         t          *Torrent
31         responsive bool
32         // Adjust the read/seek window to handle Readers locked to File extents
33         // and the like.
34         offset, length int64
35         // Ensure operations that change the position are exclusive, like Read()
36         // and Seek().
37         opMu sync.Mutex
38
39         // Required when modifying pos and readahead, or reading them without
40         // opMu.
41         mu        sync.Locker
42         pos       int64
43         readahead int64
44         // The cached piece range this reader wants downloaded. The zero value
45         // corresponds to nothing. We cache this so that changes can be detected,
46         // and bubbled up to the Torrent only as required.
47         pieces pieceRange
48 }
49
50 var _ io.ReadCloser = &reader{}
51
52 // Don't wait for pieces to complete and be verified. Read calls return as
53 // soon as they can when the underlying chunks become available.
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 // Configure the number of bytes ahead of a read that should also be
66 // prioritized in preparation for further reads.
67 func (r *reader) SetReadahead(readahead int64) {
68         r.mu.Lock()
69         r.readahead = readahead
70         r.mu.Unlock()
71         r.t.cl.lock()
72         defer r.t.cl.unlock()
73         r.posChanged()
74 }
75
76 func (r *reader) readable(off int64) (ret bool) {
77         if r.t.closed.IsSet() {
78                 return true
79         }
80         req, ok := r.t.offsetRequest(r.torrentOffset(off))
81         if !ok {
82                 panic(off)
83         }
84         if r.responsive {
85                 return r.t.haveChunk(req)
86         }
87         return r.t.pieceComplete(pieceIndex(req.Index))
88 }
89
90 // How many bytes are available to read. Max is the most we could require.
91 func (r *reader) available(off, max int64) (ret int64) {
92         off += r.offset
93         for max > 0 {
94                 req, ok := r.t.offsetRequest(off)
95                 if !ok {
96                         break
97                 }
98                 if !r.t.haveChunk(req) {
99                         break
100                 }
101                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
102                 max -= len1
103                 ret += len1
104                 off += len1
105         }
106         // Ensure that ret hasn't exceeded our original max.
107         if max < 0 {
108                 ret += max
109         }
110         return
111 }
112
113 func (r *reader) waitReadable(off int64) {
114         // We may have been sent back here because we were told we could read but
115         // it failed.
116         r.t.cl.event.Wait()
117 }
118
119 // Calculates the pieces this reader wants downloaded, ignoring the cached
120 // value at r.pieces.
121 func (r *reader) piecesUncached() (ret pieceRange) {
122         ra := r.readahead
123         if ra < 1 {
124                 // Needs to be at least 1, because [x, x) means we don't want
125                 // anything.
126                 ra = 1
127         }
128         if ra > r.length-r.pos {
129                 ra = r.length - r.pos
130         }
131         ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra)
132         return
133 }
134
135 func (r *reader) Read(b []byte) (n int, err error) {
136         return r.ReadContext(context.Background(), b)
137 }
138
139 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
140         // This is set under the Client lock if the Context is canceled.
141         var ctxErr error
142         if ctx.Done() != nil {
143                 ctx, cancel := context.WithCancel(ctx)
144                 // Abort the goroutine when the function returns.
145                 defer cancel()
146                 go func() {
147                         <-ctx.Done()
148                         r.t.cl.lock()
149                         ctxErr = ctx.Err()
150                         r.t.tickleReaders()
151                         r.t.cl.unlock()
152                 }()
153         }
154         // Hmmm, if a Read gets stuck, this means you can't change position for
155         // other purposes. That seems reasonable, but unusual.
156         r.opMu.Lock()
157         defer r.opMu.Unlock()
158         for len(b) != 0 {
159                 var n1 int
160                 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
161                 if n1 == 0 {
162                         if err == nil {
163                                 panic("expected error")
164                         }
165                         break
166                 }
167                 b = b[n1:]
168                 n += n1
169                 r.mu.Lock()
170                 r.pos += int64(n1)
171                 r.posChanged()
172                 r.mu.Unlock()
173         }
174         if r.pos >= r.length {
175                 err = io.EOF
176         } else if err == io.EOF {
177                 err = io.ErrUnexpectedEOF
178         }
179         return
180 }
181
182 // Wait until some data should be available to read. Tickles the client if it
183 // isn't. Returns how much should be readable without blocking.
184 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
185         r.t.cl.lock()
186         defer r.t.cl.unlock()
187         for !r.readable(pos) && *ctxErr == nil {
188                 r.waitReadable(pos)
189         }
190         return r.available(pos, wanted)
191 }
192
193 func (r *reader) torrentOffset(readerPos int64) int64 {
194         return r.offset + readerPos
195 }
196
197 // Performs at most one successful read to torrent storage.
198 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
199         if pos >= r.length {
200                 err = io.EOF
201                 return
202         }
203         for {
204                 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
205                 if avail == 0 {
206                         if r.t.closed.IsSet() {
207                                 err = errors.New("torrent closed")
208                                 return
209                         }
210                         if *ctxErr != nil {
211                                 err = *ctxErr
212                                 return
213                         }
214                 }
215                 pi := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength)
216                 ip := r.t.info.Piece(pi)
217                 po := r.torrentOffset(pos) % r.t.info.PieceLength
218                 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
219                 n, err = r.t.readAt(b1, r.torrentOffset(pos))
220                 if n != 0 {
221                         err = nil
222                         return
223                 }
224                 r.t.cl.lock()
225                 // TODO: Just reset pieces in the readahead window. This might help
226                 // prevent thrashing with small caches and file and piece priorities.
227                 r.log(log.Fstr("error reading torrent %s piece %d offset %d, %d bytes: %v",
228                         r.t.infoHash.HexString(), pi, po, len(b1), err))
229                 if !r.t.updatePieceCompletion(pi) {
230                         r.log(log.Fstr("piece %d completion unchanged", pi))
231                 }
232                 r.t.cl.unlock()
233         }
234 }
235
236 func (r *reader) Close() error {
237         r.t.cl.lock()
238         defer r.t.cl.unlock()
239         r.t.deleteReader(r)
240         return nil
241 }
242
243 func (r *reader) posChanged() {
244         to := r.piecesUncached()
245         from := r.pieces
246         if to == from {
247                 return
248         }
249         r.pieces = to
250         // log.Printf("reader pos changed %v->%v", from, to)
251         r.t.readerPosChanged(from, to)
252 }
253
254 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
255         r.opMu.Lock()
256         defer r.opMu.Unlock()
257
258         r.mu.Lock()
259         defer r.mu.Unlock()
260         switch whence {
261         case io.SeekStart:
262                 r.pos = off
263         case io.SeekCurrent:
264                 r.pos += off
265         case io.SeekEnd:
266                 r.pos = r.length + off
267         default:
268                 err = errors.New("bad whence")
269         }
270         ret = r.pos
271
272         r.posChanged()
273         return
274 }
275
276 func (r *reader) log(m log.Msg) {
277         r.t.logger.Log(m)
278 }