20 "crawshaw.io/sqlite/sqlitex"
21 "github.com/anacrolix/missinggo/iter"
22 "github.com/anacrolix/missinggo/v2/resource"
23 "github.com/anacrolix/torrent/storage"
26 type conn = *sqlite.Conn
28 type InitConnOpts struct {
30 MmapSizeOk bool // If false, a package-specific default will be used.
31 MmapSize int64 // If MmapSizeOk is set, use sqlite default if < 0, otherwise this value.
34 func (me InitConnOpts) JournalMode() string {
35 if me.SetJournalMode != "" {
36 return me.SetJournalMode
41 var UnexpectedJournalMode = errors.New("unexpected journal mode")
43 func initConn(conn conn, opts InitConnOpts) error {
44 // Recursive triggers are required because we need to trim the blob_meta size after trimming to
45 // capacity. Hopefully we don't hit the recursion limit, and if we do, there's an error thrown.
46 err := sqlitex.ExecTransient(conn, "pragma recursive_triggers=on", nil)
50 err = sqlitex.ExecTransient(conn, `pragma synchronous=off`, nil)
54 if opts.SetJournalMode != "" {
55 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma journal_mode=%s`, opts.SetJournalMode), func(stmt *sqlite.Stmt) error {
56 ret := stmt.ColumnText(0)
57 if ret != opts.SetJournalMode {
58 return UnexpectedJournalMode
67 // Set the default. Currently it seems the library picks reasonable defaults, especially for
70 //opts.MmapSize = 1 << 24 // 8 MiB
72 if opts.MmapSize >= 0 {
73 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma mmap_size=%d`, opts.MmapSize), nil)
81 func InitSchema(conn conn, pageSize int, triggers bool) error {
83 err := sqlitex.ExecScript(conn, fmt.Sprintf("pragma page_size=%d", pageSize))
88 err := sqlitex.ExecScript(conn, `
89 -- We have to opt into this before creating any tables, or before a vacuum to enable it. It means we
90 -- can trim the database file size with partial vacuums without having to do a full vacuum, which
92 pragma auto_vacuum=incremental;
94 create table if not exists blob (
96 last_used timestamp default (datetime('now')),
102 create table if not exists blob_meta (
103 key text primary key,
107 create index if not exists blob_last_used on blob(last_used);
109 -- While sqlite *seems* to be faster to get sum(length(data)) instead of
110 -- sum(length(data)), it may still require a large table scan at start-up or with a
111 -- cold-cache. With this we can be assured that it doesn't.
112 insert or ignore into blob_meta values ('size', 0);
114 create table if not exists setting (
115 name primary key on conflict replace,
119 create view if not exists deletable_blob as
120 with recursive excess (
129 (select value from blob_meta where key='size') as usage_with,
133 from blob order by last_used, rowid limit 1
135 where usage_with > (select value from setting where name='capacity')
138 usage_with-data_length as new_usage_with,
142 from excess join blob
143 on blob.rowid=(select rowid from blob where (last_used, rowid) > (excess.last_used, blob_rowid))
144 where new_usage_with > (select value from setting where name='capacity')
146 select * from excess;
152 err := sqlitex.ExecScript(conn, `
153 create trigger if not exists after_insert_blob
156 update blob_meta set value=value+length(cast(new.data as blob)) where key='size';
157 delete from blob where rowid in (select blob_rowid from deletable_blob);
160 create trigger if not exists after_update_blob
161 after update of data on blob
163 update blob_meta set value=value+length(cast(new.data as blob))-length(cast(old.data as blob)) where key='size';
164 delete from blob where rowid in (select blob_rowid from deletable_blob);
167 create trigger if not exists after_delete_blob
170 update blob_meta set value=value-length(cast(old.data as blob)) where key='size';
180 type NewPiecesStorageOpts struct {
183 ProvOpts func(*ProviderOpts)
184 StorageOpts func(*storage.ResourcePiecesOpts)
187 // A convenience function that creates a connection pool, resource provider, and a pieces storage
188 // ClientImpl and returns them all with a Close attached.
189 func NewPiecesStorage(opts NewPiecesStorageOpts) (_ storage.ClientImplCloser, err error) {
190 conns, err := NewPool(opts.NewPoolOpts)
194 err = initPoolDatabase(conns, opts.InitDbOpts)
198 provOpts := ProviderOpts{
199 BatchWrites: conns.NumConns() > 1,
201 if f := opts.ProvOpts; f != nil {
204 prov, err := NewProvider(conns, provOpts)
212 withPoolConn(conns, func(c conn) {
213 err = sqlitex.Exec(c, "pragma journal_mode", func(stmt *sqlite.Stmt) error {
214 journalMode = stmt.ColumnText(0)
219 err = fmt.Errorf("getting journal mode: %w", err)
223 if journalMode == "" {
224 err = errors.New("didn't get journal mode")
228 storageOpts := storage.ResourcePiecesOpts{
229 NoSizedPuts: journalMode != "wal" || conns.NumConns() == 1,
231 if f := opts.StorageOpts; f != nil {
234 store := storage.NewResourcePiecesOpts(prov, storageOpts)
244 type NewPoolOpts struct {
250 type InitDbOpts struct {
253 // If non-zero, overrides the existing setting.
258 // There's some overlap here with NewPoolOpts, and I haven't decided what needs to be done. For now,
259 // the fact that the pool opts are a superset, means our helper NewPiecesStorage can just take the
260 // top-level option type.
261 type PoolConf struct {
266 // Remove any capacity limits.
267 func UnlimitCapacity(conn conn) error {
268 return sqlitex.Exec(conn, "delete from setting where key='capacity'", nil)
271 // Set the capacity limit to exactly this value.
272 func SetCapacity(conn conn, cap int64) error {
273 return sqlitex.Exec(conn, "insert into setting values ('capacity', ?)", nil, cap)
276 type NewConnOpts struct {
277 // See https://www.sqlite.org/c3ref/open.html. NB: "If the filename is an empty string, then a
278 // private, temporary on-disk database will be created. This private database will be
279 // automatically deleted as soon as the database connection is closed."
282 // Whether multiple blobs will not be read simultaneously. Enables journal mode other than WAL,
284 NoConcurrentBlobReads bool
287 func newOpenUri(opts NewConnOpts) string {
288 path := url.PathEscape(opts.Path)
292 values := make(url.Values)
293 if opts.NoConcurrentBlobReads || opts.Memory {
294 values.Add("cache", "shared")
296 return fmt.Sprintf("file:%s?%s", path, values.Encode())
299 func initDatabase(conn conn, opts InitDbOpts) (err error) {
300 if !opts.DontInitSchema {
301 if opts.PageSize == 0 {
302 // There doesn't seem to be an optimal size. I did try with the standard chunk size, but
303 // the difference is not convincing.
305 //opts.PageSize = 1 << 14
307 err = InitSchema(conn, opts.PageSize, !opts.NoTriggers)
312 if opts.Capacity != 0 {
313 err = SetCapacity(conn, opts.Capacity)
321 func initPoolDatabase(pool ConnPool, opts InitDbOpts) (err error) {
322 withPoolConn(pool, func(c conn) {
323 err = initDatabase(c, opts)
328 func newConn(opts NewConnOpts) (conn, error) {
329 return sqlite.OpenConn(newOpenUri(opts), 0)
332 type poolWithNumConns struct {
337 func (me poolWithNumConns) NumConns() int {
341 func NewPool(opts NewPoolOpts) (_ ConnPool, err error) {
342 if opts.NumConns == 0 {
343 opts.NumConns = runtime.NumCPU()
345 conns, err := func() (ConnPool, error) {
346 switch opts.NumConns {
348 conn, err := newConn(opts.NewConnOpts)
349 return &poolFromConn{conn: conn}, err
351 _pool, err := sqlitex.Open(newOpenUri(opts.NewConnOpts), 0, opts.NumConns)
352 return poolWithNumConns{_pool, opts.NumConns}, err
363 return conns, initPoolConns(nil, conns, InitPoolOpts{
364 NumConns: opts.NumConns,
365 InitConnOpts: opts.InitConnOpts,
369 // Emulates a ConnPool from a single Conn. Might be faster than using a sqlitex.Pool.
370 type poolFromConn struct {
375 func (me *poolFromConn) Get(ctx context.Context) conn {
380 func (me *poolFromConn) Put(conn conn) {
382 panic("expected to same conn")
387 func (me *poolFromConn) Close() error {
388 return me.conn.Close()
391 func (poolFromConn) NumConns() int { return 1 }
393 type ProviderOpts struct {
397 // Needs the ConnPool size so it can initialize all the connections with pragmas. Takes ownership of
398 // the ConnPool (since it has to initialize all the connections anyway).
399 func NewProvider(pool ConnPool, opts ProviderOpts) (_ *provider, err error) {
400 prov := &provider{pool: pool, opts: opts}
401 if opts.BatchWrites {
402 writes := make(chan writeRequest)
404 // This is retained for backwards compatibility. It may not be necessary.
405 runtime.SetFinalizer(prov, func(p *provider) {
408 go providerWriter(writes, prov.pool)
413 type InitPoolOpts struct {
418 func initPoolConns(ctx context.Context, pool ConnPool, opts InitPoolOpts) (err error) {
421 for _, c := range conns {
425 for range iter.N(opts.NumConns) {
426 conn := pool.Get(ctx)
430 conns = append(conns, conn)
431 err = initConn(conn, opts.InitConnOpts)
433 err = fmt.Errorf("initing conn %v: %w", len(conns), err)
440 type ConnPool interface {
441 Get(context.Context) conn
447 func withPoolConn(pool ConnPool, with func(conn)) {
453 type provider struct {
455 writes chan<- writeRequest
462 var _ storage.ConsecutiveChunkReader = (*provider)(nil)
464 func (p *provider) ReadConsecutiveChunks(prefix string) (io.ReadCloser, error) {
466 runner, err := p.getReadWithConnRunner()
473 defer p.closeMu.RUnlock()
474 err = runner(func(_ context.Context, conn conn) error {
476 err = sqlitex.Exec(conn, `
479 cast(substr(name, ?+1) as integer) as offset
481 where name like ?||'%'
483 func(stmt *sqlite.Stmt) error {
484 offset := stmt.ColumnInt64(1)
485 if offset != written {
486 return fmt.Errorf("got chunk at offset %v, expected offset %v", offset, written)
488 // TODO: Avoid intermediate buffers here
489 r := stmt.ColumnReader(0)
490 w1, err := io.Copy(w, r)
499 w.CloseWithError(err)
504 func (me *provider) Close() error {
506 defer me.closeMu.Unlock()
510 if me.writes != nil {
513 me.closeErr = me.pool.Close()
518 type writeRequest struct {
521 labels pprof.LabelSet
524 var expvars = expvar.NewMap("sqliteStorage")
526 func runQueryWithLabels(query withConn, labels pprof.LabelSet, conn conn) (err error) {
527 pprof.Do(context.Background(), labels, func(ctx context.Context) {
528 // We pass in the context in the hope that the CPU profiler might incorporate sqlite
529 // activity the action that triggered it. It doesn't seem that way, since those calls don't
530 // take a context.Context themselves. It may come in useful in the goroutine profiles
531 // though, and doesn't hurt to expose it here for other purposes should things change.
532 err = query(ctx, conn)
537 // Intentionally avoids holding a reference to *provider to allow it to use a finalizer, and to have
538 // stronger typing on the writes channel.
539 func providerWriter(writes <-chan writeRequest, pool ConnPool) {
540 conn := pool.Get(context.TODO())
546 first, ok := <-writes
553 defer sqlitex.Save(conn)(&cantFail)
554 firstErr := runQueryWithLabels(first.query, first.labels, conn)
555 buf = append(buf, func() { first.done <- firstErr })
558 case wr, ok := <-writes:
560 err := runQueryWithLabels(wr.query, wr.labels, conn)
561 buf = append(buf, func() { wr.done <- err })
569 // Not sure what to do if this failed.
571 expvars.Add("batchTransactionErrors", 1)
573 // Signal done after we know the transaction succeeded.
574 for _, done := range buf {
577 expvars.Add("batchTransactions", 1)
578 expvars.Add("batchedQueries", int64(len(buf)))
579 //log.Printf("batched %v write queries", len(buf))
583 func (p *provider) NewInstance(s string) (resource.Instance, error) {
584 return instance{s, p}, nil
587 type instance struct {
592 func getLabels(skip int) pprof.LabelSet {
593 return pprof.Labels("sqlite-storage-action", func() string {
595 runtime.Callers(skip+3, pcs[:])
596 fs := runtime.CallersFrames(pcs[:])
598 funcName := f.Func.Name()
599 funcName = funcName[strings.LastIndexByte(funcName, '.')+1:]
600 //log.Printf("func name: %q", funcName)
605 func (p *provider) withConn(with withConn, write bool, skip int) error {
607 // I think we need to check this here because it may not be valid to send to the writes channel
608 // if we're already closed. So don't try to move this check into getReadWithConnRunner.
611 return errors.New("closed")
613 if write && p.opts.BatchWrites {
614 done := make(chan error)
615 p.writes <- writeRequest{
618 labels: getLabels(skip + 1),
623 defer p.closeMu.RUnlock()
624 runner, err := p.getReadWithConnRunner()
632 // Obtains a DB conn and returns a withConn for executing with it. If no error is returned from this
633 // function, the runner *must* be used or the conn is leaked. You should check the provider isn't
634 // closed before using this.
635 func (p *provider) getReadWithConnRunner() (with func(withConn) error, err error) {
636 conn := p.pool.Get(context.TODO())
638 err = errors.New("couldn't get pool conn")
641 with = func(with withConn) error {
642 defer p.pool.Put(conn)
643 return runQueryWithLabels(with, getLabels(1), conn)
648 type withConn func(context.Context, conn) error
650 func (i instance) withConn(with withConn, write bool) error {
651 return i.p.withConn(with, write, 1)
654 func (i instance) getConn() *sqlite.Conn {
655 return i.p.pool.Get(context.TODO())
658 func (i instance) putConn(conn *sqlite.Conn) {
662 func (i instance) Readdirnames() (names []string, err error) {
663 prefix := i.location + "/"
664 err = i.withConn(func(_ context.Context, conn conn) error {
665 return sqlitex.Exec(conn, "select name from blob where name like ?", func(stmt *sqlite.Stmt) error {
666 names = append(names, stmt.ColumnText(0)[len(prefix):])
670 //log.Printf("readdir %q gave %q", i.location, names)
674 func (i instance) getBlobRowid(conn conn) (rowid int64, err error) {
676 err = sqlitex.Exec(conn, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
677 rowid = stmt.ColumnInt64(0)
688 err = errors.New("blob not found")
694 type connBlob struct {
699 func (me connBlob) Close() error {
700 err := me.Blob.Close()
705 func (i instance) Get() (ret io.ReadCloser, err error) {
708 panic("nil sqlite conn")
710 blob, err := i.openBlob(conn, false, true)
716 return connBlob{blob, func() {
717 once.Do(func() { i.putConn(conn) })
721 func (i instance) openBlob(conn conn, write, updateAccess bool) (*sqlite.Blob, error) {
722 rowid, err := i.getBlobRowid(conn)
726 // This seems to cause locking issues with in-memory databases. Is it something to do with not
729 err = sqlitex.Exec(conn, "update blob set last_used=datetime('now') where rowid=?", nil, rowid)
731 err = fmt.Errorf("updating last_used: %w", err)
734 if conn.Changes() != 1 {
735 panic(conn.Changes())
738 return conn.OpenBlob("main", "blob", "data", rowid, write)
741 func (i instance) PutSized(reader io.Reader, size int64) (err error) {
742 err = i.withConn(func(_ context.Context, conn conn) error {
743 err := sqlitex.Exec(conn, "insert or replace into blob(name, data) values(?, zeroblob(?))",
749 blob, err := i.openBlob(conn, true, false)
754 _, err = io.Copy(blob, reader)
760 func (i instance) Put(reader io.Reader) (err error) {
762 _, err = io.Copy(&buf, reader)
767 return i.PutSized(&buf, int64(buf.Len()))
769 return i.withConn(func(_ context.Context, conn conn) error {
770 for range iter.N(10) {
771 err = sqlitex.Exec(conn,
772 "insert or replace into blob(name, data) values(?, cast(? as blob))",
774 i.location, buf.Bytes())
775 if err, ok := err.(sqlite.Error); ok && err.Code == sqlite.SQLITE_BUSY {
776 log.Print("sqlite busy")
777 time.Sleep(time.Second)
787 type fileInfo struct {
791 func (f fileInfo) Name() string {
792 panic("implement me")
795 func (f fileInfo) Size() int64 {
799 func (f fileInfo) Mode() os.FileMode {
800 panic("implement me")
803 func (f fileInfo) ModTime() time.Time {
804 panic("implement me")
807 func (f fileInfo) IsDir() bool {
808 panic("implement me")
811 func (f fileInfo) Sys() interface{} {
812 panic("implement me")
815 func (i instance) Stat() (ret os.FileInfo, err error) {
816 err = i.withConn(func(_ context.Context, conn conn) error {
817 var blob *sqlite.Blob
818 blob, err = i.openBlob(conn, false, false)
823 ret = fileInfo{blob.Size()}
829 func (i instance) ReadAt(p []byte, off int64) (n int, err error) {
830 err = i.withConn(func(_ context.Context, conn conn) error {
832 var blob *sqlite.Blob
833 blob, err = i.openBlob(conn, false, true)
838 if off >= blob.Size() {
842 if off+int64(len(p)) > blob.Size() {
843 p = p[:blob.Size()-off]
845 n, err = blob.ReadAt(p, off)
850 "select substr(data, ?, ?) from blob where name=?",
851 func(stmt *sqlite.Stmt) error {
853 panic("found multiple matching blobs")
857 n = stmt.ColumnBytes(0, p)
860 off+1, len(p), i.location,
866 err = errors.New("blob not found")
878 func (i instance) WriteAt(bytes []byte, i2 int64) (int, error) {
879 panic("implement me")
882 func (i instance) Delete() error {
883 return i.withConn(func(_ context.Context, conn conn) error {
884 return sqlitex.Exec(conn, "delete from blob where name=?", nil, i.location)