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() error {
122 if c.opts.BlobFlushInterval != 0 {
125 return c.conn.Close()
128 type torrent struct {
132 func rowidForBlob(c conn, name string, length int64, create bool) (rowid int64, err error) {
134 err = sqlitex.Exec(c, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
136 panic("expected at most one row")
138 // TODO: How do we know if we got this wrong?
139 rowid = stmt.ColumnInt64(0)
150 err = errors.New("no existing row")
153 err = sqlitex.Exec(c, "insert into blob(name, data) values(?, zeroblob(?))", nil, name, length)
157 rowid = c.LastInsertRowID()
161 func (t torrent) Piece(p metainfo.Piece) storage.PieceImpl {
164 name := p.Hash().HexString()
172 func (t torrent) Close() error {
182 func (p piece) doAtIoWithBlob(
183 atIo func(*sqlite.Blob) func([]byte, int64) (int, error),
187 ) (n int, err error) {
190 if p.opts.NoCacheBlobs {
193 blob, err := p.getBlob(create)
195 err = fmt.Errorf("getting blob: %w", err)
198 n, err = atIo(blob)(b, off)
203 if !errors.As(err, &se) {
206 // "ABORT" occurs if the row the blob is on is modified elsewhere. "ERROR: invalid blob" occurs
207 // if the blob has been closed. We don't forget blobs that are closed by our GC finalizers,
208 // because they may be attached to names that have since moved on to another blob.
209 if se.Code != sqlite.SQLITE_ABORT && !(p.opts.GcBlobs && se.Code == sqlite.SQLITE_ERROR && se.Msg == "invalid blob") {
213 // Try again, this time we're guaranteed to get a fresh blob, and so errors are no excuse. It
214 // might be possible to skip to this version if we don't cache blobs.
215 blob, err = p.getBlob(create)
217 err = fmt.Errorf("getting blob: %w", err)
220 return atIo(blob)(b, off)
223 func (p piece) ReadAt(b []byte, off int64) (n int, err error) {
224 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
229 func (p piece) WriteAt(b []byte, off int64) (n int, err error) {
230 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
235 func (p piece) MarkComplete() error {
238 err := sqlitex.Exec(p.conn, "update blob set verified=true where name=?", nil, p.name)
242 changes := p.conn.Changes()
249 func (p piece) forgetBlob() {
250 blob, ok := p.blobs[p.name]
255 delete(p.blobs, p.name)
258 func (p piece) MarkNotComplete() error {
261 return sqlitex.Exec(p.conn, "update blob set verified=false where name=?", nil, p.name)
264 func (p piece) Completion() (ret storage.Completion) {
267 err := sqlitex.Exec(p.conn, "select verified from blob where name=?", func(stmt *sqlite.Stmt) error {
268 ret.Complete = stmt.ColumnInt(0) != 0
278 func (p piece) getBlob(create bool) (*sqlite.Blob, error) {
279 blob, ok := p.blobs[p.name]
281 rowid, err := rowidForBlob(p.conn, p.name, p.length, create)
283 return nil, fmt.Errorf("getting rowid for blob: %w", err)
285 blob, err = p.conn.OpenBlob("main", "blob", "data", rowid, true)
291 runtime.SetFinalizer(herp, func(*byte) {
294 // Note there's no guarantee that the finalizer fired while this blob is the same
295 // one in the blob cache. It might be possible to rework this so that we check, or
296 // strip finalizers as appropriate.
300 p.blobs[p.name] = blob