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 opts.PageSize = 1 << 14
304 err = InitSchema(conn, opts.PageSize, !opts.NoTriggers)
309 if opts.Capacity != 0 {
310 err = SetCapacity(conn, opts.Capacity)
318 func initPoolDatabase(pool ConnPool, opts InitDbOpts) (err error) {
319 withPoolConn(pool, func(c conn) {
320 err = initDatabase(c, opts)
325 func newConn(opts NewConnOpts) (conn, error) {
326 return sqlite.OpenConn(newOpenUri(opts), 0)
329 type poolWithNumConns struct {
334 func (me poolWithNumConns) NumConns() int {
338 func NewPool(opts NewPoolOpts) (_ ConnPool, err error) {
339 if opts.NumConns == 0 {
340 opts.NumConns = runtime.NumCPU()
342 conns, err := func() (ConnPool, error) {
343 switch opts.NumConns {
345 conn, err := newConn(opts.NewConnOpts)
346 return &poolFromConn{conn: conn}, err
348 _pool, err := sqlitex.Open(newOpenUri(opts.NewConnOpts), 0, opts.NumConns)
349 return poolWithNumConns{_pool, opts.NumConns}, err
360 return conns, initPoolConns(nil, conns, InitPoolOpts{
361 NumConns: opts.NumConns,
362 InitConnOpts: opts.InitConnOpts,
366 // Emulates a ConnPool from a single Conn. Might be faster than using a sqlitex.Pool.
367 type poolFromConn struct {
372 func (me *poolFromConn) Get(ctx context.Context) conn {
377 func (me *poolFromConn) Put(conn conn) {
379 panic("expected to same conn")
384 func (me *poolFromConn) Close() error {
385 return me.conn.Close()
388 func (poolFromConn) NumConns() int { return 1 }
390 type ProviderOpts struct {
394 // Needs the ConnPool size so it can initialize all the connections with pragmas. Takes ownership of
395 // the ConnPool (since it has to initialize all the connections anyway).
396 func NewProvider(pool ConnPool, opts ProviderOpts) (_ *provider, err error) {
397 prov := &provider{pool: pool, opts: opts}
398 if opts.BatchWrites {
399 writes := make(chan writeRequest)
401 // This is retained for backwards compatibility. It may not be necessary.
402 runtime.SetFinalizer(prov, func(p *provider) {
405 go providerWriter(writes, prov.pool)
410 type InitPoolOpts struct {
415 func initPoolConns(ctx context.Context, pool ConnPool, opts InitPoolOpts) (err error) {
418 for _, c := range conns {
422 for range iter.N(opts.NumConns) {
423 conn := pool.Get(ctx)
427 conns = append(conns, conn)
428 err = initConn(conn, opts.InitConnOpts)
430 err = fmt.Errorf("initing conn %v: %w", len(conns), err)
437 type ConnPool interface {
438 Get(context.Context) conn
444 func withPoolConn(pool ConnPool, with func(conn)) {
450 type provider struct {
452 writes chan<- writeRequest
459 var _ storage.ConsecutiveChunkReader = (*provider)(nil)
461 func (p *provider) ReadConsecutiveChunks(prefix string) (io.ReadCloser, error) {
463 runner, err := p.getReadWithConnRunner()
470 defer p.closeMu.RUnlock()
471 err = runner(func(_ context.Context, conn conn) error {
473 err = sqlitex.Exec(conn, `
476 cast(substr(name, ?+1) as integer) as offset
478 where name like ?||'%'
480 func(stmt *sqlite.Stmt) error {
481 offset := stmt.ColumnInt64(1)
482 if offset != written {
483 return fmt.Errorf("got chunk at offset %v, expected offset %v", offset, written)
485 // TODO: Avoid intermediate buffers here
486 r := stmt.ColumnReader(0)
487 w1, err := io.Copy(w, r)
496 w.CloseWithError(err)
501 func (me *provider) Close() error {
503 defer me.closeMu.Unlock()
507 if me.writes != nil {
510 me.closeErr = me.pool.Close()
515 type writeRequest struct {
518 labels pprof.LabelSet
521 var expvars = expvar.NewMap("sqliteStorage")
523 func runQueryWithLabels(query withConn, labels pprof.LabelSet, conn conn) (err error) {
524 pprof.Do(context.Background(), labels, func(ctx context.Context) {
525 // We pass in the context in the hope that the CPU profiler might incorporate sqlite
526 // activity the action that triggered it. It doesn't seem that way, since those calls don't
527 // take a context.Context themselves. It may come in useful in the goroutine profiles
528 // though, and doesn't hurt to expose it here for other purposes should things change.
529 err = query(ctx, conn)
534 // Intentionally avoids holding a reference to *provider to allow it to use a finalizer, and to have
535 // stronger typing on the writes channel.
536 func providerWriter(writes <-chan writeRequest, pool ConnPool) {
537 conn := pool.Get(context.TODO())
543 first, ok := <-writes
550 defer sqlitex.Save(conn)(&cantFail)
551 firstErr := runQueryWithLabels(first.query, first.labels, conn)
552 buf = append(buf, func() { first.done <- firstErr })
555 case wr, ok := <-writes:
557 err := runQueryWithLabels(wr.query, wr.labels, conn)
558 buf = append(buf, func() { wr.done <- err })
566 // Not sure what to do if this failed.
568 expvars.Add("batchTransactionErrors", 1)
570 // Signal done after we know the transaction succeeded.
571 for _, done := range buf {
574 expvars.Add("batchTransactions", 1)
575 expvars.Add("batchedQueries", int64(len(buf)))
576 //log.Printf("batched %v write queries", len(buf))
580 func (p *provider) NewInstance(s string) (resource.Instance, error) {
581 return instance{s, p}, nil
584 type instance struct {
589 func getLabels(skip int) pprof.LabelSet {
590 return pprof.Labels("sqlite-storage-action", func() string {
592 runtime.Callers(skip+3, pcs[:])
593 fs := runtime.CallersFrames(pcs[:])
595 funcName := f.Func.Name()
596 funcName = funcName[strings.LastIndexByte(funcName, '.')+1:]
597 //log.Printf("func name: %q", funcName)
602 func (p *provider) withConn(with withConn, write bool, skip int) error {
604 // I think we need to check this here because it may not be valid to send to the writes channel
605 // if we're already closed. So don't try to move this check into getReadWithConnRunner.
608 return errors.New("closed")
610 if write && p.opts.BatchWrites {
611 done := make(chan error)
612 p.writes <- writeRequest{
615 labels: getLabels(skip + 1),
620 defer p.closeMu.RUnlock()
621 runner, err := p.getReadWithConnRunner()
629 // Obtains a DB conn and returns a withConn for executing with it. If no error is returned from this
630 // function, the runner *must* be used or the conn is leaked. You should check the provider isn't
631 // closed before using this.
632 func (p *provider) getReadWithConnRunner() (with func(withConn) error, err error) {
633 conn := p.pool.Get(context.TODO())
635 err = errors.New("couldn't get pool conn")
638 with = func(with withConn) error {
639 defer p.pool.Put(conn)
640 return runQueryWithLabels(with, getLabels(1), conn)
645 type withConn func(context.Context, conn) error
647 func (i instance) withConn(with withConn, write bool) error {
648 return i.p.withConn(with, write, 1)
651 func (i instance) getConn() *sqlite.Conn {
652 return i.p.pool.Get(context.TODO())
655 func (i instance) putConn(conn *sqlite.Conn) {
659 func (i instance) Readdirnames() (names []string, err error) {
660 prefix := i.location + "/"
661 err = i.withConn(func(_ context.Context, conn conn) error {
662 return sqlitex.Exec(conn, "select name from blob where name like ?", func(stmt *sqlite.Stmt) error {
663 names = append(names, stmt.ColumnText(0)[len(prefix):])
667 //log.Printf("readdir %q gave %q", i.location, names)
671 func (i instance) getBlobRowid(conn conn) (rowid int64, err error) {
673 err = sqlitex.Exec(conn, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
674 rowid = stmt.ColumnInt64(0)
685 err = errors.New("blob not found")
691 type connBlob struct {
696 func (me connBlob) Close() error {
697 err := me.Blob.Close()
702 func (i instance) Get() (ret io.ReadCloser, err error) {
705 panic("nil sqlite conn")
707 blob, err := i.openBlob(conn, false, true)
713 return connBlob{blob, func() {
714 once.Do(func() { i.putConn(conn) })
718 func (i instance) openBlob(conn conn, write, updateAccess bool) (*sqlite.Blob, error) {
719 rowid, err := i.getBlobRowid(conn)
723 // This seems to cause locking issues with in-memory databases. Is it something to do with not
726 err = sqlitex.Exec(conn, "update blob set last_used=datetime('now') where rowid=?", nil, rowid)
728 err = fmt.Errorf("updating last_used: %w", err)
731 if conn.Changes() != 1 {
732 panic(conn.Changes())
735 return conn.OpenBlob("main", "blob", "data", rowid, write)
738 func (i instance) PutSized(reader io.Reader, size int64) (err error) {
739 err = i.withConn(func(_ context.Context, conn conn) error {
740 err := sqlitex.Exec(conn, "insert or replace into blob(name, data) values(?, zeroblob(?))",
746 blob, err := i.openBlob(conn, true, false)
751 _, err = io.Copy(blob, reader)
757 func (i instance) Put(reader io.Reader) (err error) {
759 _, err = io.Copy(&buf, reader)
764 return i.PutSized(&buf, int64(buf.Len()))
766 return i.withConn(func(_ context.Context, conn conn) error {
767 for range iter.N(10) {
768 err = sqlitex.Exec(conn,
769 "insert or replace into blob(name, data) values(?, cast(? as blob))",
771 i.location, buf.Bytes())
772 if err, ok := err.(sqlite.Error); ok && err.Code == sqlite.SQLITE_BUSY {
773 log.Print("sqlite busy")
774 time.Sleep(time.Second)
784 type fileInfo struct {
788 func (f fileInfo) Name() string {
789 panic("implement me")
792 func (f fileInfo) Size() int64 {
796 func (f fileInfo) Mode() os.FileMode {
797 panic("implement me")
800 func (f fileInfo) ModTime() time.Time {
801 panic("implement me")
804 func (f fileInfo) IsDir() bool {
805 panic("implement me")
808 func (f fileInfo) Sys() interface{} {
809 panic("implement me")
812 func (i instance) Stat() (ret os.FileInfo, err error) {
813 err = i.withConn(func(_ context.Context, conn conn) error {
814 var blob *sqlite.Blob
815 blob, err = i.openBlob(conn, false, false)
820 ret = fileInfo{blob.Size()}
826 func (i instance) ReadAt(p []byte, off int64) (n int, err error) {
827 err = i.withConn(func(_ context.Context, conn conn) error {
829 var blob *sqlite.Blob
830 blob, err = i.openBlob(conn, false, true)
835 if off >= blob.Size() {
839 if off+int64(len(p)) > blob.Size() {
840 p = p[:blob.Size()-off]
842 n, err = blob.ReadAt(p, off)
847 "select substr(data, ?, ?) from blob where name=?",
848 func(stmt *sqlite.Stmt) error {
850 panic("found multiple matching blobs")
854 n = stmt.ColumnBytes(0, p)
857 off+1, len(p), i.location,
863 err = errors.New("blob not found")
875 func (i instance) WriteAt(bytes []byte, i2 int64) (int, error) {
876 panic("implement me")
879 func (i instance) Delete() error {
880 return i.withConn(func(_ context.Context, conn conn) error {
881 return sqlitex.Exec(conn, "delete from blob where name=?", nil, i.location)