14 "crawshaw.io/sqlite/sqlitex"
16 "github.com/anacrolix/torrent/metainfo"
17 "github.com/anacrolix/torrent/storage"
20 type NewDirectStorageOpts struct {
26 BlobFlushInterval time.Duration
29 // A convenience function that creates a connection pool, resource provider, and a pieces storage
30 // ClientImpl and returns them all with a Close attached.
31 func NewDirectStorage(opts NewDirectStorageOpts) (_ storage.ClientImplCloser, err error) {
32 conn, err := newConn(opts.NewConnOpts)
36 if opts.PageSize == 0 {
37 // The largest size sqlite supports. I think we want this to be the smallest piece size we
38 // can expect, which is probably 1<<17.
39 opts.PageSize = 1 << 16
41 err = initDatabase(conn, opts.InitDbOpts)
46 err = initConn(conn, opts.InitConnOpts)
51 if opts.BlobFlushInterval == 0 && !opts.GcBlobs {
52 // This is influenced by typical busy timeouts, of 5-10s. We want to give other connections
53 // a few chances at getting a transaction through.
54 opts.BlobFlushInterval = time.Second
58 blobs: make(map[string]*sqlite.Blob),
61 // Avoid race with cl.blobFlusherFunc
64 if opts.BlobFlushInterval != 0 {
65 cl.blobFlusher = time.AfterFunc(opts.BlobFlushInterval, cl.blobFlusherFunc)
67 cl.capacity = cl.getCapacity
71 func (cl *client) getCapacity() (ret *int64) {
74 err := sqlitex.Exec(cl.conn, "select value from setting where name='capacity'", func(stmt *sqlite.Stmt) error {
76 *ret = stmt.ColumnInt64(0)
88 blobs map[string]*sqlite.Blob
89 blobFlusher *time.Timer
90 opts NewDirectStorageOpts
92 capacity func() *int64
95 func (c *client) blobFlusherFunc() {
100 c.blobFlusher.Reset(c.opts.BlobFlushInterval)
104 func (c *client) flushBlobs() {
105 for key, b := range c.blobs {
106 // Need the lock to prevent racing with the GC finalizers.
112 func (c *client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (storage.TorrentImpl, error) {
114 return storage.TorrentImpl{Piece: t.Piece, Close: t.Close, Capacity: &c.capacity}, nil
117 func (c *client) Close() (err error) {
121 if c.opts.BlobFlushInterval != 0 {
132 type torrent struct {
136 func rowidForBlob(c conn, name string, length int64, create bool) (rowid int64, err error) {
138 err = sqlitex.Exec(c, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
140 panic("expected at most one row")
142 // TODO: How do we know if we got this wrong?
143 rowid = stmt.ColumnInt64(0)
154 err = errors.New("no existing row")
157 err = sqlitex.Exec(c, "insert into blob(name, data) values(?, zeroblob(?))", nil, name, length)
161 rowid = c.LastInsertRowID()
165 func (t torrent) Piece(p metainfo.Piece) storage.PieceImpl {
168 name := p.Hash().HexString()
176 func (t torrent) Close() error {
186 func (p piece) doAtIoWithBlob(
187 atIo func(*sqlite.Blob) func([]byte, int64) (int, error),
191 ) (n int, err error) {
194 if p.opts.NoCacheBlobs {
197 blob, err := p.getBlob(create)
199 err = fmt.Errorf("getting blob: %w", err)
202 n, err = atIo(blob)(b, off)
207 if !errors.As(err, &se) {
210 // "ABORT" occurs if the row the blob is on is modified elsewhere. "ERROR: invalid blob" occurs
211 // if the blob has been closed. We don't forget blobs that are closed by our GC finalizers,
212 // because they may be attached to names that have since moved on to another blob.
213 if se.Code != sqlite.SQLITE_ABORT && !(p.opts.GcBlobs && se.Code == sqlite.SQLITE_ERROR && se.Msg == "invalid blob") {
217 // Try again, this time we're guaranteed to get a fresh blob, and so errors are no excuse. It
218 // might be possible to skip to this version if we don't cache blobs.
219 blob, err = p.getBlob(create)
221 err = fmt.Errorf("getting blob: %w", err)
224 return atIo(blob)(b, off)
227 func (p piece) ReadAt(b []byte, off int64) (n int, err error) {
228 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
233 func (p piece) WriteAt(b []byte, off int64) (n int, err error) {
234 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
239 func (p piece) MarkComplete() error {
242 err := sqlitex.Exec(p.conn, "update blob set verified=true where name=?", nil, p.name)
246 changes := p.conn.Changes()
253 func (p piece) forgetBlob() {
254 blob, ok := p.blobs[p.name]
259 delete(p.blobs, p.name)
262 func (p piece) MarkNotComplete() error {
265 return sqlitex.Exec(p.conn, "update blob set verified=false where name=?", nil, p.name)
268 func (p piece) Completion() (ret storage.Completion) {
271 err := sqlitex.Exec(p.conn, "select verified from blob where name=?", func(stmt *sqlite.Stmt) error {
272 ret.Complete = stmt.ColumnInt(0) != 0
282 func (p piece) getBlob(create bool) (*sqlite.Blob, error) {
283 blob, ok := p.blobs[p.name]
285 rowid, err := rowidForBlob(p.conn, p.name, p.length, create)
287 return nil, fmt.Errorf("getting rowid for blob: %w", err)
289 blob, err = p.conn.OpenBlob("main", "blob", "data", rowid, true)
295 runtime.SetFinalizer(herp, func(*byte) {
298 // Note there's no guarantee that the finalizer fired while this blob is the same
299 // one in the blob cache. It might be possible to rework this so that we check, or
300 // strip finalizers as appropriate.
304 p.blobs[p.name] = blob