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