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 if opts.BlobFlushInterval != 0 {
62 cl.blobFlusher = time.AfterFunc(opts.BlobFlushInterval, cl.blobFlusherFunc)
70 blobs map[string]*sqlite.Blob
71 blobFlusher *time.Timer
72 opts NewDirectStorageOpts
76 func (c *client) blobFlusherFunc() {
81 c.blobFlusher.Reset(c.opts.BlobFlushInterval)
85 func (c *client) flushBlobs() {
86 for key, b := range c.blobs {
87 // Need the lock to prevent racing with the GC finalizers.
93 func (c *client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (storage.TorrentImpl, error) {
94 return torrent{c}, nil
97 func (c *client) Close() error {
102 if c.opts.BlobFlushInterval != 0 {
105 return c.conn.Close()
108 type torrent struct {
112 func rowidForBlob(c conn, name string, length int64, create bool) (rowid int64, err error) {
114 err = sqlitex.Exec(c, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
116 panic("expected at most one row")
118 // TODO: How do we know if we got this wrong?
119 rowid = stmt.ColumnInt64(0)
130 err = errors.New("no existing row")
133 err = sqlitex.Exec(c, "insert into blob(name, data) values(?, zeroblob(?))", nil, name, length)
137 rowid = c.LastInsertRowID()
141 func (t torrent) Piece(p metainfo.Piece) storage.PieceImpl {
144 name := p.Hash().HexString()
152 func (t torrent) Close() error {
162 func (p piece) doAtIoWithBlob(
163 atIo func(*sqlite.Blob) func([]byte, int64) (int, error),
167 ) (n int, err error) {
170 if p.opts.NoCacheBlobs {
173 blob, err := p.getBlob(create)
175 err = fmt.Errorf("getting blob: %w", err)
178 n, err = atIo(blob)(b, off)
183 if !errors.As(err, &se) {
186 // "ABORT" occurs if the row the blob is on is modified elsewhere. "ERROR: invalid blob" occurs
187 // if the blob has been closed. We don't forget blobs that are closed by our GC finalizers,
188 // because they may be attached to names that have since moved on to another blob.
189 if se.Code != sqlite.SQLITE_ABORT && !(p.opts.GcBlobs && se.Code == sqlite.SQLITE_ERROR && se.Msg == "invalid blob") {
193 // Try again, this time we're guaranteed to get a fresh blob, and so errors are no excuse. It
194 // might be possible to skip to this version if we don't cache blobs.
195 blob, err = p.getBlob(create)
197 err = fmt.Errorf("getting blob: %w", err)
200 return atIo(blob)(b, off)
203 func (p piece) ReadAt(b []byte, off int64) (n int, err error) {
204 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
209 func (p piece) WriteAt(b []byte, off int64) (n int, err error) {
210 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
215 func (p piece) MarkComplete() error {
218 err := sqlitex.Exec(p.conn, "update blob set verified=true where name=?", nil, p.name)
222 changes := p.conn.Changes()
229 func (p piece) forgetBlob() {
230 blob, ok := p.blobs[p.name]
235 delete(p.blobs, p.name)
238 func (p piece) MarkNotComplete() error {
241 return sqlitex.Exec(p.conn, "update blob set verified=false where name=?", nil, p.name)
244 func (p piece) Completion() (ret storage.Completion) {
247 err := sqlitex.Exec(p.conn, "select verified from blob where name=?", func(stmt *sqlite.Stmt) error {
248 ret.Complete = stmt.ColumnInt(0) != 0
258 func (p piece) getBlob(create bool) (*sqlite.Blob, error) {
259 blob, ok := p.blobs[p.name]
261 rowid, err := rowidForBlob(p.conn, p.name, p.length, create)
263 return nil, fmt.Errorf("getting rowid for blob: %w", err)
265 blob, err = p.conn.OpenBlob("main", "blob", "data", rowid, true)
271 runtime.SetFinalizer(herp, func(*byte) {
274 // Note there's no guarantee that the finalizer fired while this blob is the same
275 // one in the blob cache. It might be possible to rework this so that we check, or
276 // strip finalizers as appropriate.
280 p.blobs[p.name] = blob