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