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 func initConn(conn conn, opts InitConnOpts) error {
42 // Recursive triggers are required because we need to trim the blob_meta size after trimming to
43 // capacity. Hopefully we don't hit the recursion limit, and if we do, there's an error thrown.
44 err := sqlitex.ExecTransient(conn, "pragma recursive_triggers=on", nil)
48 err = sqlitex.ExecTransient(conn, `pragma synchronous=off`, nil)
52 if opts.SetJournalMode != "" {
53 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma journal_mode=%s`, opts.SetJournalMode), func(stmt *sqlite.Stmt) error {
54 ret := stmt.ColumnText(0)
55 if ret != opts.SetJournalMode {
65 opts.MmapSize = 1 << 24 // 8 MiB
67 if opts.MmapSize >= 0 {
68 err = sqlitex.ExecTransient(conn, fmt.Sprintf(`pragma mmap_size=%d`, opts.MmapSize), nil)
76 func InitSchema(conn conn, pageSize int, triggers bool) error {
78 err := sqlitex.ExecScript(conn, fmt.Sprintf("pragma page_size=%d", pageSize))
83 err := sqlitex.ExecScript(conn, `
84 -- We have to opt into this before creating any tables, or before a vacuum to enable it. It means we
85 -- can trim the database file size with partial vacuums without having to do a full vacuum, which
87 pragma auto_vacuum=incremental;
89 create table if not exists blob (
91 last_used timestamp default (datetime('now')),
97 create table if not exists blob_meta (
102 create index if not exists blob_last_used on blob(last_used);
104 -- While sqlite *seems* to be faster to get sum(length(data)) instead of
105 -- sum(length(data)), it may still require a large table scan at start-up or with a
106 -- cold-cache. With this we can be assured that it doesn't.
107 insert or ignore into blob_meta values ('size', 0);
109 create table if not exists setting (
110 name primary key on conflict replace,
114 create view if not exists deletable_blob as
115 with recursive excess (
124 (select value from blob_meta where key='size') as usage_with,
128 from blob order by last_used, rowid limit 1
130 where usage_with > (select value from setting where name='capacity')
133 usage_with-data_length as new_usage_with,
137 from excess join blob
138 on blob.rowid=(select rowid from blob where (last_used, rowid) > (excess.last_used, blob_rowid))
139 where new_usage_with > (select value from setting where name='capacity')
141 select * from excess;
147 err := sqlitex.ExecScript(conn, `
148 create trigger if not exists after_insert_blob
151 update blob_meta set value=value+length(cast(new.data as blob)) where key='size';
152 delete from blob where rowid in (select blob_rowid from deletable_blob);
155 create trigger if not exists after_update_blob
156 after update of data on blob
158 update blob_meta set value=value+length(cast(new.data as blob))-length(cast(old.data as blob)) where key='size';
159 delete from blob where rowid in (select blob_rowid from deletable_blob);
162 create trigger if not exists after_delete_blob
165 update blob_meta set value=value-length(cast(old.data as blob)) where key='size';
175 type NewPiecesStorageOpts struct {
178 ProvOpts func(*ProviderOpts)
179 StorageOpts func(*storage.ResourcePiecesOpts)
182 // A convenience function that creates a connection pool, resource provider, and a pieces storage
183 // ClientImpl and returns them all with a Close attached.
184 func NewPiecesStorage(opts NewPiecesStorageOpts) (_ storage.ClientImplCloser, err error) {
185 conns, err := NewPool(opts.NewPoolOpts)
189 err = initPoolDatabase(conns, opts.InitDbOpts)
193 provOpts := ProviderOpts{
194 BatchWrites: conns.NumConns() > 1,
196 if f := opts.ProvOpts; f != nil {
199 prov, err := NewProvider(conns, provOpts)
207 withPoolConn(conns, func(c conn) {
208 err = sqlitex.Exec(c, "pragma journal_mode", func(stmt *sqlite.Stmt) error {
209 journalMode = stmt.ColumnText(0)
214 err = fmt.Errorf("getting journal mode: %w", err)
218 if journalMode == "" {
219 err = errors.New("didn't get journal mode")
223 storageOpts := storage.ResourcePiecesOpts{
224 NoSizedPuts: journalMode != "wal" || conns.NumConns() == 1,
226 if f := opts.StorageOpts; f != nil {
229 store := storage.NewResourcePiecesOpts(prov, storageOpts)
239 type NewPoolOpts struct {
245 type InitDbOpts struct {
248 // If non-zero, overrides the existing setting.
252 // There's some overlap here with NewPoolOpts, and I haven't decided what needs to be done. For now,
253 // the fact that the pool opts are a superset, means our helper NewPiecesStorage can just take the
254 // top-level option type.
255 type PoolConf struct {
260 // Remove any capacity limits.
261 func UnlimitCapacity(conn conn) error {
262 return sqlitex.Exec(conn, "delete from setting where key='capacity'", nil)
265 // Set the capacity limit to exactly this value.
266 func SetCapacity(conn conn, cap int64) error {
267 return sqlitex.Exec(conn, "insert into setting values ('capacity', ?)", nil, cap)
270 type NewConnOpts struct {
271 // See https://www.sqlite.org/c3ref/open.html. NB: "If the filename is an empty string, then a
272 // private, temporary on-disk database will be created. This private database will be
273 // automatically deleted as soon as the database connection is closed."
276 // Whether multiple blobs will not be read simultaneously. Enables journal mode other than WAL,
278 NoConcurrentBlobReads bool
281 func newOpenUri(opts NewConnOpts) string {
282 path := url.PathEscape(opts.Path)
286 values := make(url.Values)
287 if opts.NoConcurrentBlobReads || opts.Memory {
288 values.Add("cache", "shared")
290 return fmt.Sprintf("file:%s?%s", path, values.Encode())
293 func initDatabase(conn conn, opts InitDbOpts) (err error) {
294 if !opts.DontInitSchema {
295 if opts.PageSize == 0 {
296 opts.PageSize = 1 << 14
298 err = InitSchema(conn, opts.PageSize, true)
303 if opts.Capacity != 0 {
304 err = SetCapacity(conn, opts.Capacity)
312 func initPoolDatabase(pool ConnPool, opts InitDbOpts) (err error) {
313 withPoolConn(pool, func(c conn) {
314 err = initDatabase(c, opts)
319 func newConn(opts NewConnOpts) (conn, error) {
320 return sqlite.OpenConn(newOpenUri(opts), 0)
323 type poolWithNumConns struct {
328 func (me poolWithNumConns) NumConns() int {
332 func NewPool(opts NewPoolOpts) (_ ConnPool, err error) {
333 if opts.NumConns == 0 {
334 opts.NumConns = runtime.NumCPU()
336 conns, err := func() (ConnPool, error) {
337 switch opts.NumConns {
339 conn, err := newConn(opts.NewConnOpts)
340 return &poolFromConn{conn: conn}, err
342 _pool, err := sqlitex.Open(newOpenUri(opts.NewConnOpts), 0, opts.NumConns)
343 return poolWithNumConns{_pool, opts.NumConns}, err
354 return conns, initPoolConns(nil, conns, InitPoolOpts{
355 NumConns: opts.NumConns,
356 InitConnOpts: opts.InitConnOpts,
360 // Emulates a ConnPool from a single Conn. Might be faster than using a sqlitex.Pool.
361 type poolFromConn struct {
366 func (me *poolFromConn) Get(ctx context.Context) conn {
371 func (me *poolFromConn) Put(conn conn) {
373 panic("expected to same conn")
378 func (me *poolFromConn) Close() error {
379 return me.conn.Close()
382 func (poolFromConn) NumConns() int { return 1 }
384 type ProviderOpts struct {
388 // Needs the ConnPool size so it can initialize all the connections with pragmas. Takes ownership of
389 // the ConnPool (since it has to initialize all the connections anyway).
390 func NewProvider(pool ConnPool, opts ProviderOpts) (_ *provider, err error) {
391 prov := &provider{pool: pool, opts: opts}
392 if opts.BatchWrites {
393 writes := make(chan writeRequest)
395 // This is retained for backwards compatibility. It may not be necessary.
396 runtime.SetFinalizer(prov, func(p *provider) {
399 go providerWriter(writes, prov.pool)
404 type InitPoolOpts struct {
409 func initPoolConns(ctx context.Context, pool ConnPool, opts InitPoolOpts) (err error) {
412 for _, c := range conns {
416 for range iter.N(opts.NumConns) {
417 conn := pool.Get(ctx)
421 conns = append(conns, conn)
422 err = initConn(conn, opts.InitConnOpts)
424 err = fmt.Errorf("initing conn %v: %w", len(conns), err)
431 type ConnPool interface {
432 Get(context.Context) conn
438 func withPoolConn(pool ConnPool, with func(conn)) {
444 type provider struct {
446 writes chan<- writeRequest
453 var _ storage.ConsecutiveChunkReader = (*provider)(nil)
455 func (p *provider) ReadConsecutiveChunks(prefix string) (io.ReadCloser, error) {
457 runner, err := p.getReadWithConnRunner()
464 defer p.closeMu.RUnlock()
465 err = runner(func(_ context.Context, conn conn) error {
467 err = sqlitex.Exec(conn, `
470 cast(substr(name, ?+1) as integer) as offset
472 where name like ?||'%'
474 func(stmt *sqlite.Stmt) error {
475 offset := stmt.ColumnInt64(1)
476 if offset != written {
477 return fmt.Errorf("got chunk at offset %v, expected offset %v", offset, written)
479 // TODO: Avoid intermediate buffers here
480 r := stmt.ColumnReader(0)
481 w1, err := io.Copy(w, r)
490 w.CloseWithError(err)
495 func (me *provider) Close() error {
497 defer me.closeMu.Unlock()
501 if me.writes != nil {
504 me.closeErr = me.pool.Close()
509 type writeRequest struct {
512 labels pprof.LabelSet
515 var expvars = expvar.NewMap("sqliteStorage")
517 func runQueryWithLabels(query withConn, labels pprof.LabelSet, conn conn) (err error) {
518 pprof.Do(context.Background(), labels, func(ctx context.Context) {
519 // We pass in the context in the hope that the CPU profiler might incorporate sqlite
520 // activity the action that triggered it. It doesn't seem that way, since those calls don't
521 // take a context.Context themselves. It may come in useful in the goroutine profiles
522 // though, and doesn't hurt to expose it here for other purposes should things change.
523 err = query(ctx, conn)
528 // Intentionally avoids holding a reference to *provider to allow it to use a finalizer, and to have
529 // stronger typing on the writes channel.
530 func providerWriter(writes <-chan writeRequest, pool ConnPool) {
531 conn := pool.Get(context.TODO())
537 first, ok := <-writes
544 defer sqlitex.Save(conn)(&cantFail)
545 firstErr := runQueryWithLabels(first.query, first.labels, conn)
546 buf = append(buf, func() { first.done <- firstErr })
549 case wr, ok := <-writes:
551 err := runQueryWithLabels(wr.query, wr.labels, conn)
552 buf = append(buf, func() { wr.done <- err })
560 // Not sure what to do if this failed.
562 expvars.Add("batchTransactionErrors", 1)
564 // Signal done after we know the transaction succeeded.
565 for _, done := range buf {
568 expvars.Add("batchTransactions", 1)
569 expvars.Add("batchedQueries", int64(len(buf)))
570 //log.Printf("batched %v write queries", len(buf))
574 func (p *provider) NewInstance(s string) (resource.Instance, error) {
575 return instance{s, p}, nil
578 type instance struct {
583 func getLabels(skip int) pprof.LabelSet {
584 return pprof.Labels("sqlite-storage-action", func() string {
586 runtime.Callers(skip+3, pcs[:])
587 fs := runtime.CallersFrames(pcs[:])
589 funcName := f.Func.Name()
590 funcName = funcName[strings.LastIndexByte(funcName, '.')+1:]
591 //log.Printf("func name: %q", funcName)
596 func (p *provider) withConn(with withConn, write bool, skip int) error {
598 // I think we need to check this here because it may not be valid to send to the writes channel
599 // if we're already closed. So don't try to move this check into getReadWithConnRunner.
602 return errors.New("closed")
604 if write && p.opts.BatchWrites {
605 done := make(chan error)
606 p.writes <- writeRequest{
609 labels: getLabels(skip + 1),
614 defer p.closeMu.RUnlock()
615 runner, err := p.getReadWithConnRunner()
623 // Obtains a DB conn and returns a withConn for executing with it. If no error is returned from this
624 // function, the runner *must* be used or the conn is leaked. You should check the provider isn't
625 // closed before using this.
626 func (p *provider) getReadWithConnRunner() (with func(withConn) error, err error) {
627 conn := p.pool.Get(context.TODO())
629 err = errors.New("couldn't get pool conn")
632 with = func(with withConn) error {
633 defer p.pool.Put(conn)
634 return runQueryWithLabels(with, getLabels(1), conn)
639 type withConn func(context.Context, conn) error
641 func (i instance) withConn(with withConn, write bool) error {
642 return i.p.withConn(with, write, 1)
645 func (i instance) getConn() *sqlite.Conn {
646 return i.p.pool.Get(context.TODO())
649 func (i instance) putConn(conn *sqlite.Conn) {
653 func (i instance) Readdirnames() (names []string, err error) {
654 prefix := i.location + "/"
655 err = i.withConn(func(_ context.Context, conn conn) error {
656 return sqlitex.Exec(conn, "select name from blob where name like ?", func(stmt *sqlite.Stmt) error {
657 names = append(names, stmt.ColumnText(0)[len(prefix):])
661 //log.Printf("readdir %q gave %q", i.location, names)
665 func (i instance) getBlobRowid(conn conn) (rowid int64, err error) {
667 err = sqlitex.Exec(conn, "select rowid from blob where name=?", func(stmt *sqlite.Stmt) error {
668 rowid = stmt.ColumnInt64(0)
679 err = errors.New("blob not found")
685 type connBlob struct {
690 func (me connBlob) Close() error {
691 err := me.Blob.Close()
696 func (i instance) Get() (ret io.ReadCloser, err error) {
699 panic("nil sqlite conn")
701 blob, err := i.openBlob(conn, false, true)
707 return connBlob{blob, func() {
708 once.Do(func() { i.putConn(conn) })
712 func (i instance) openBlob(conn conn, write, updateAccess bool) (*sqlite.Blob, error) {
713 rowid, err := i.getBlobRowid(conn)
717 // This seems to cause locking issues with in-memory databases. Is it something to do with not
720 err = sqlitex.Exec(conn, "update blob set last_used=datetime('now') where rowid=?", nil, rowid)
722 err = fmt.Errorf("updating last_used: %w", err)
725 if conn.Changes() != 1 {
726 panic(conn.Changes())
729 return conn.OpenBlob("main", "blob", "data", rowid, write)
732 func (i instance) PutSized(reader io.Reader, size int64) (err error) {
733 err = i.withConn(func(_ context.Context, conn conn) error {
734 err := sqlitex.Exec(conn, "insert or replace into blob(name, data) values(?, zeroblob(?))",
740 blob, err := i.openBlob(conn, true, false)
745 _, err = io.Copy(blob, reader)
751 func (i instance) Put(reader io.Reader) (err error) {
753 _, err = io.Copy(&buf, reader)
758 return i.PutSized(&buf, int64(buf.Len()))
760 return i.withConn(func(_ context.Context, conn conn) error {
761 for range iter.N(10) {
762 err = sqlitex.Exec(conn,
763 "insert or replace into blob(name, data) values(?, cast(? as blob))",
765 i.location, buf.Bytes())
766 if err, ok := err.(sqlite.Error); ok && err.Code == sqlite.SQLITE_BUSY {
767 log.Print("sqlite busy")
768 time.Sleep(time.Second)
778 type fileInfo struct {
782 func (f fileInfo) Name() string {
783 panic("implement me")
786 func (f fileInfo) Size() int64 {
790 func (f fileInfo) Mode() os.FileMode {
791 panic("implement me")
794 func (f fileInfo) ModTime() time.Time {
795 panic("implement me")
798 func (f fileInfo) IsDir() bool {
799 panic("implement me")
802 func (f fileInfo) Sys() interface{} {
803 panic("implement me")
806 func (i instance) Stat() (ret os.FileInfo, err error) {
807 err = i.withConn(func(_ context.Context, conn conn) error {
808 var blob *sqlite.Blob
809 blob, err = i.openBlob(conn, false, false)
814 ret = fileInfo{blob.Size()}
820 func (i instance) ReadAt(p []byte, off int64) (n int, err error) {
821 err = i.withConn(func(_ context.Context, conn conn) error {
823 var blob *sqlite.Blob
824 blob, err = i.openBlob(conn, false, true)
829 if off >= blob.Size() {
833 if off+int64(len(p)) > blob.Size() {
834 p = p[:blob.Size()-off]
836 n, err = blob.ReadAt(p, off)
841 "select substr(data, ?, ?) from blob where name=?",
842 func(stmt *sqlite.Stmt) error {
844 panic("found multiple matching blobs")
848 n = stmt.ColumnBytes(0, p)
851 off+1, len(p), i.location,
857 err = errors.New("blob not found")
869 func (i instance) WriteAt(bytes []byte, i2 int64) (int, error) {
870 panic("implement me")
873 func (i instance) Delete() error {
874 return i.withConn(func(_ context.Context, conn conn) error {
875 return sqlitex.Exec(conn, "delete from blob where name=?", nil, i.location)