11 "crawshaw.io/sqlite/sqlitex"
12 "github.com/anacrolix/torrent/metainfo"
13 "github.com/anacrolix/torrent/storage"
16 type NewDirectStorageOpts struct {
22 BlobFlushInterval time.Duration
25 // A convenience function that creates a connection pool, resource provider, and a pieces storage
26 // ClientImpl and returns them all with a Close attached.
27 func NewDirectStorage(opts NewDirectStorageOpts) (_ storage.ClientImplCloser, err error) {
28 conn, err := newConn(opts.NewConnOpts)
32 if opts.PageSize == 0 {
33 // The largest size sqlite supports. I think we want this to be the smallest piece size we
34 // can expect, which is probably 1<<17.
35 opts.PageSize = 1 << 16
37 err = initDatabase(conn, opts.InitDbOpts)
42 err = initConn(conn, opts.InitConnOpts)
47 if opts.BlobFlushInterval == 0 && !opts.GcBlobs {
48 // This is influenced by typical busy timeouts, of 5-10s. We want to give other connections
49 // a few chances at getting a transaction through.
50 opts.BlobFlushInterval = time.Second
54 blobs: make(map[string]*sqlite.Blob),
57 if opts.BlobFlushInterval != 0 {
58 cl.blobFlusher = time.AfterFunc(opts.BlobFlushInterval, cl.blobFlusherFunc)
66 blobs map[string]*sqlite.Blob
67 blobFlusher *time.Timer
68 opts NewDirectStorageOpts
72 func (c *client) blobFlusherFunc() {
77 c.blobFlusher.Reset(c.opts.BlobFlushInterval)
81 func (c *client) flushBlobs() {
82 for key, b := range c.blobs {
83 // Need the lock to prevent racing with the GC finalizers.
89 func (c *client) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (storage.TorrentImpl, error) {
90 return torrent{c}, nil
93 func (c *client) Close() error {
98 if c.opts.BlobFlushInterval != 0 {
101 return c.conn.Close()
104 type torrent struct {
108 func rowidForBlob(c conn, name string, length int64, create bool) (rowid int64, err error) {
110 err = sqlitex.Exec(c, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
112 panic("expected at most one row")
114 // TODO: How do we know if we got this wrong?
115 rowid = stmt.ColumnInt64(0)
126 err = errors.New("no existing row")
129 err = sqlitex.Exec(c, "insert into blob(name, data) values(?, zeroblob(?))", nil, name, length)
133 rowid = c.LastInsertRowID()
137 func (t torrent) Piece(p metainfo.Piece) storage.PieceImpl {
140 name := p.Hash().HexString()
148 func (t torrent) Close() error {
158 func (p piece) doAtIoWithBlob(
159 atIo func(*sqlite.Blob) func([]byte, int64) (int, error),
163 ) (n int, err error) {
166 if p.opts.NoCacheBlobs {
169 blob, err := p.getBlob(create)
171 err = fmt.Errorf("getting blob: %w", err)
174 n, err = atIo(blob)(b, off)
179 if !errors.As(err, &se) {
182 // "ABORT" occurs if the row the blob is on is modified elsewhere. "ERROR: invalid blob" occurs
183 // if the blob has been closed. We don't forget blobs that are closed by our GC finalizers,
184 // because they may be attached to names that have since moved on to another blob.
185 if se.Code != sqlite.SQLITE_ABORT && !(p.opts.GcBlobs && se.Code == sqlite.SQLITE_ERROR && se.Msg == "invalid blob") {
189 // Try again, this time we're guaranteed to get a fresh blob, and so errors are no excuse. It
190 // might be possible to skip to this version if we don't cache blobs.
191 blob, err = p.getBlob(create)
193 err = fmt.Errorf("getting blob: %w", err)
196 return atIo(blob)(b, off)
199 func (p piece) ReadAt(b []byte, off int64) (n int, err error) {
200 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
205 func (p piece) WriteAt(b []byte, off int64) (n int, err error) {
206 return p.doAtIoWithBlob(func(blob *sqlite.Blob) func([]byte, int64) (int, error) {
211 func (p piece) MarkComplete() error {
214 err := sqlitex.Exec(p.conn, "update blob set verified=true where name=?", nil, p.name)
218 changes := p.conn.Changes()
225 func (p piece) forgetBlob() {
226 blob, ok := p.blobs[p.name]
231 delete(p.blobs, p.name)
234 func (p piece) MarkNotComplete() error {
237 return sqlitex.Exec(p.conn, "update blob set verified=false where name=?", nil, p.name)
240 func (p piece) Completion() (ret storage.Completion) {
243 err := sqlitex.Exec(p.conn, "select verified from blob where name=?", func(stmt *sqlite.Stmt) error {
244 ret.Complete = stmt.ColumnInt(0) != 0
254 func (p piece) getBlob(create bool) (*sqlite.Blob, error) {
255 blob, ok := p.blobs[p.name]
257 rowid, err := rowidForBlob(p.conn, p.name, p.length, create)
259 return nil, fmt.Errorf("getting rowid for blob: %w", err)
261 blob, err = p.conn.OpenBlob("main", "blob", "data", rowid, true)
267 runtime.SetFinalizer(herp, func(*byte) {
270 // Note there's no guarantee that the finalizer fired while this blob is the same
271 // one in the blob cache. It might be possible to rework this so that we check, or
272 // strip finalizers as appropriate.
276 p.blobs[p.name] = blob