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