12 g "github.com/anacrolix/generics"
13 "github.com/anacrolix/missinggo/v2/resource"
14 "github.com/anacrolix/sync"
16 "github.com/anacrolix/torrent/metainfo"
19 type piecePerResource struct {
21 opts ResourcePiecesOpts
24 type ResourcePiecesOpts struct {
25 // After marking a piece complete, don't bother deleting its incomplete blobs.
26 LeaveIncompleteChunks bool
27 // Sized puts require being able to stream from a statement executed on another connection.
28 // Without them, we buffer the entire read and then put that.
33 func NewResourcePieces(p PieceProvider) ClientImpl {
34 return NewResourcePiecesOpts(p, ResourcePiecesOpts{})
37 func NewResourcePiecesOpts(p PieceProvider, opts ResourcePiecesOpts) ClientImpl {
38 return &piecePerResource{
44 type piecePerResourceTorrentImpl struct {
49 func (piecePerResourceTorrentImpl) Close() error {
53 func (s piecePerResource) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
54 t := piecePerResourceTorrentImpl{
56 make([]sync.RWMutex, info.NumPieces()),
58 return TorrentImpl{PieceWithHash: t.Piece, Close: t.Close}, nil
61 func (s piecePerResourceTorrentImpl) Piece(p metainfo.Piece, pieceHash g.Option[[]byte]) PieceImpl {
62 return piecePerResourcePiece{
65 piecePerResource: s.piecePerResource,
66 mu: &s.locks[p.Index()],
70 type PieceProvider interface {
74 type ConsecutiveChunkReader interface {
75 ReadConsecutiveChunks(prefix string) (io.ReadCloser, error)
78 type piecePerResourcePiece struct {
80 // The piece hash if we have it. It could be 20 or 32 bytes depending on the info version.
81 pieceHash g.Option[[]byte]
83 // This protects operations that move complete/incomplete pieces around, which can trigger read
84 // errors that may cause callers to do more drastic things.
88 var _ io.WriterTo = piecePerResourcePiece{}
90 func (s piecePerResourcePiece) WriteTo(w io.Writer) (int64, error) {
93 if s.mustIsComplete() {
94 r, err := s.completed().Get()
96 return 0, fmt.Errorf("getting complete instance: %w", err)
101 if ccr, ok := s.rp.(ConsecutiveChunkReader); ok {
102 return s.writeConsecutiveIncompleteChunks(ccr, w)
104 return io.Copy(w, io.NewSectionReader(s, 0, s.mp.Length()))
107 func (s piecePerResourcePiece) writeConsecutiveIncompleteChunks(ccw ConsecutiveChunkReader, w io.Writer) (int64, error) {
108 r, err := ccw.ReadConsecutiveChunks(s.incompleteDirPath() + "/")
116 // Returns if the piece is complete. Ok should be true, because we are the definitive source of
118 func (s piecePerResourcePiece) mustIsComplete() bool {
119 completion := s.Completion()
121 panic("must know complete definitively")
123 return completion.Complete
126 func (s piecePerResourcePiece) Completion() (_ Completion) {
132 fi, err := s.completed().Stat()
134 Complete: err == nil && fi.Size() == s.mp.Length(),
139 type SizedPutter interface {
140 PutSized(io.Reader, int64) error
143 func (s piecePerResourcePiece) MarkComplete() error {
146 incompleteChunks := s.getChunks()
147 r, err := func() (io.ReadCloser, error) {
148 if ccr, ok := s.rp.(ConsecutiveChunkReader); ok {
149 return ccr.ReadConsecutiveChunks(s.incompleteDirPath() + "/")
151 return io.NopCloser(io.NewSectionReader(incompleteChunks, 0, s.mp.Length())), nil
154 return fmt.Errorf("getting incomplete chunks reader: %w", err)
157 completedInstance := s.completed()
159 if sp, ok := completedInstance.(SizedPutter); ok && !s.opts.NoSizedPuts {
160 return sp.PutSized(r, s.mp.Length())
162 return completedInstance.Put(r)
165 if err == nil && !s.opts.LeaveIncompleteChunks {
166 // I think we do this synchronously here since we don't want callers to act on the completed
167 // piece if we're concurrently still deleting chunks. The caller may decide to start
168 // downloading chunks again and won't expect us to delete them. It seems to be much faster
169 // to let the resource provider do this if possible.
170 var wg sync.WaitGroup
171 for _, c := range incompleteChunks {
183 func (s piecePerResourcePiece) MarkNotComplete() error {
186 return s.completed().Delete()
189 func (s piecePerResourcePiece) ReadAt(b []byte, off int64) (int, error) {
192 if s.mustIsComplete() {
193 return s.completed().ReadAt(b, off)
195 return s.getChunks().ReadAt(b, off)
198 func (s piecePerResourcePiece) WriteAt(b []byte, off int64) (n int, err error) {
201 i, err := s.rp.NewInstance(path.Join(s.incompleteDirPath(), strconv.FormatInt(off, 10)))
205 r := bytes.NewReader(b)
206 if sp, ok := i.(SizedPutter); ok {
207 err = sp.PutSized(r, r.Size())
217 instance resource.Instance
222 func (me chunks) ReadAt(b []byte, off int64) (int, error) {
227 if me[0].offset <= off {
232 n, err := me[0].instance.ReadAt(b, off-me[0].offset)
236 if err == nil || err == io.EOF {
237 n_, err := me[1:].ReadAt(b[n:], off+int64(n))
243 func (s piecePerResourcePiece) getChunks() (chunks chunks) {
244 names, err := s.incompleteDir().Readdirnames()
248 for _, n := range names {
249 offset, err := strconv.ParseInt(n, 10, 64)
253 i, err := s.rp.NewInstance(path.Join(s.incompleteDirPath(), n))
257 chunks = append(chunks, chunk{offset, i})
259 sort.Slice(chunks, func(i, j int) bool {
260 return chunks[i].offset < chunks[j].offset
265 func (s piecePerResourcePiece) completedInstancePath() string {
266 return path.Join("completed", s.hashHex())
269 func (s piecePerResourcePiece) completed() resource.Instance {
270 i, err := s.rp.NewInstance(s.completedInstancePath())
277 func (s piecePerResourcePiece) incompleteDirPath() string {
278 return path.Join("incompleted", s.hashHex())
281 func (s piecePerResourcePiece) incompleteDir() resource.DirInstance {
282 i, err := s.rp.NewInstance(s.incompleteDirPath())
286 return i.(resource.DirInstance)
289 func (me piecePerResourcePiece) hashHex() string {
290 return hex.EncodeToString(me.pieceHash.Unwrap())