]> Sergey Matveev's repositories - btrtrc.git/blob - reader.go
Readers obtained from File.NewReader should not readahead into other Files
[btrtrc.git] / reader.go
1 package torrent
2
3 import (
4         "errors"
5         "io"
6         "log"
7         "sync"
8
9         "github.com/anacrolix/missinggo"
10         "golang.org/x/net/context"
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 int
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.mu.Lock()
72         defer r.t.cl.mu.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.offset + off)
81         if !ok {
82                 panic(off)
83         }
84         if r.responsive {
85                 return r.t.haveChunk(req)
86         }
87         return r.t.pieceComplete(int(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         for max > 0 {
93                 req, ok := r.t.offsetRequest(off)
94                 if !ok {
95                         break
96                 }
97                 if !r.t.haveChunk(req) {
98                         break
99                 }
100                 len1 := int64(req.Length) - (off - r.t.requestOffset(req))
101                 max -= len1
102                 ret += len1
103                 off += len1
104         }
105         // Ensure that ret hasn't exceeded our original max.
106         if max < 0 {
107                 ret += max
108         }
109         return
110 }
111
112 func (r *reader) waitReadable(off int64) {
113         // We may have been sent back here because we were told we could read but
114         // it failed.
115         r.t.cl.event.Wait()
116 }
117
118 // Calculates the pieces this reader wants downloaded, ignoring the cached
119 // value at r.pieces.
120 func (r *reader) piecesUncached() (ret pieceRange) {
121         ra := r.readahead
122         if ra < 1 {
123                 // Needs to be at least 1, because [x, x) means we don't want
124                 // anything.
125                 ra = 1
126         }
127         if ra > r.length-r.pos {
128                 ra = r.length - r.pos
129         }
130         ret.begin, ret.end = r.t.byteRegionPieces(r.offset+r.pos, ra)
131         return
132 }
133
134 func (r *reader) Read(b []byte) (n int, err error) {
135         return r.ReadContext(context.Background(), b)
136 }
137
138 func (r *reader) ReadContext(ctx context.Context, b []byte) (n int, err error) {
139         // This is set under the Client lock if the Context is canceled.
140         var ctxErr error
141         if ctx.Done() != nil {
142                 ctx, cancel := context.WithCancel(ctx)
143                 // Abort the goroutine when the function returns.
144                 defer cancel()
145                 go func() {
146                         <-ctx.Done()
147                         r.t.cl.mu.Lock()
148                         ctxErr = ctx.Err()
149                         r.t.cl.event.Broadcast()
150                         r.t.cl.mu.Unlock()
151                 }()
152         }
153         // Hmmm, if a Read gets stuck, this means you can't change position for
154         // other purposes. That seems reasonable, but unusual.
155         r.opMu.Lock()
156         defer r.opMu.Unlock()
157         for len(b) != 0 {
158                 var n1 int
159                 n1, err = r.readOnceAt(b, r.pos, &ctxErr)
160                 if n1 == 0 {
161                         if err == nil {
162                                 panic("expected error")
163                         }
164                         break
165                 }
166                 b = b[n1:]
167                 n += n1
168                 r.mu.Lock()
169                 r.pos += int64(n1)
170                 r.posChanged()
171                 r.mu.Unlock()
172         }
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 // Wait until some data should be available to read. Tickles the client if it
182 // isn't. Returns how much should be readable without blocking.
183 func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) {
184         r.t.cl.mu.Lock()
185         defer r.t.cl.mu.Unlock()
186         for !r.readable(pos) && *ctxErr == nil {
187                 r.waitReadable(pos)
188         }
189         return r.available(pos, wanted)
190 }
191
192 // Performs at most one successful read to torrent storage.
193 func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) {
194         if pos >= r.length {
195                 err = io.EOF
196                 return
197         }
198         for {
199                 avail := r.waitAvailable(pos, int64(len(b)), ctxErr)
200                 if avail == 0 {
201                         if r.t.closed.IsSet() {
202                                 err = errors.New("torrent closed")
203                                 return
204                         }
205                         if *ctxErr != nil {
206                                 err = *ctxErr
207                                 return
208                         }
209                 }
210                 pi := int(pos / r.t.info.PieceLength)
211                 ip := r.t.info.Piece(pi)
212                 po := pos % r.t.info.PieceLength
213                 b1 := missinggo.LimitLen(b, ip.Length()-po, avail)
214                 n, err = r.t.readAt(b1, pos)
215                 if n != 0 {
216                         err = nil
217                         return
218                 }
219                 r.t.cl.mu.Lock()
220                 log.Printf("error reading torrent %q piece %d offset %d, %d bytes: %s", r.t, pi, po, len(b1), err)
221                 r.t.updateAllPieceCompletions()
222                 r.t.updateAllPiecePriorities()
223                 r.t.cl.mu.Unlock()
224         }
225 }
226
227 func (r *reader) Close() error {
228         r.t.cl.mu.Lock()
229         defer r.t.cl.mu.Unlock()
230         r.t.deleteReader(r)
231         return nil
232 }
233
234 func (r *reader) posChanged() {
235         to := r.piecesUncached()
236         from := r.pieces
237         if to == from {
238                 return
239         }
240         r.pieces = to
241         r.t.readerPosChanged(from, to)
242 }
243
244 func (r *reader) Seek(off int64, whence int) (ret int64, err error) {
245         r.opMu.Lock()
246         defer r.opMu.Unlock()
247
248         r.mu.Lock()
249         defer r.mu.Unlock()
250         switch whence {
251         case io.SeekStart:
252                 r.pos = off
253         case io.SeekCurrent:
254                 r.pos += off
255         case io.SeekEnd:
256                 r.pos = r.length + off
257         default:
258                 err = errors.New("bad whence")
259         }
260         ret = r.pos
261
262         r.posChanged()
263         return
264 }