mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 10:27:08 +02:00
* fix(artwork): pause the artwork worker while a scan is running The artwork worker added in 0.64 writes to the database continuously, including while a scan runs. On slow storage the scanner holds the write lock for many seconds per folder, so the two writers keep timing each other out: artwork writes fail with "database is locked", and a single busy timeout on the scanner side aborts the whole scan. The worker now stops dispatching queue items while scanner.IsScanning reports true, including mid-batch, and resumes on the next poll after the scan ends. Artwork requests are unaffected, since they serve local art without the worker. * fix(db): run ANALYZE one index at a time so writers are not starved A full ANALYZE is a single write transaction, so every other write waits for it to finish and fails after the 15s busy timeout. On slow NAS storage it was measured taking over 26 minutes. The analysis now runs ANALYZE per index (per table for unindexed and WITHOUT ROWID tables), which produces the same sqlite_stat1 rows as a full ANALYZE, and pauses briefly between steps (up to 150ms, just above SQLite's longest busy-handler sleep) so waiting writers get the lock. * fix(scanner): ignore Synology @eaDir metadata folders Synology creates an @eaDir folder next to media files, holding one subfolder per file with generated thumbnails. The scanner and watcher treated them as regular folders, which on one reported library added tens of thousands of extra folders to every scan. * fix(db): analyze tables with only partial indexes as a whole A partial index does not record the table's row count, so a table whose only indexes are partial needs a table-level ANALYZE to get the sqlite_stat1 row a full ANALYZE would write. Navidrome's schema has no such table today, but the stepped analysis should match a full ANALYZE for any schema a future migration creates. * fix(scanner): retry busy folder saves and stop phase 1 on a fatal error On slow storage, a single SQLITE_BUSY while saving a folder aborted the whole scan, even when another writer held the lock only briefly. The folder save now runs as a retryable unit: on a busy error it waits (5s, 10s, 15s) and reruns the transaction, up to three times, before failing. Side effects that do not survive a rollback (the album ID map consumed by persistAlbum, the artwork queue items, the image-change record) are rebuilt per attempt or recorded only after a successful commit. When a folder save does fail, phase 1 used to keep walking the library and reading tags for every remaining folder, discarding the results, before reporting the error; a reporter saw 40 silent minutes. The walk now stops as soon as the save fails, and the walker honors cancellation instead of blocking on its channel. Because an early stop leaves folders unvisited, phase 1 no longer marks unvisited folders missing when the phase failed; the resumed scan handles them. * refactor(persistence): move busy retry into DataStore.WithTxRetry The scanner retried its folder save itself, which meant it had to know SQLite error codes. WithTxRetry now owns that policy: it reruns the block in a fresh transaction on SQLITE_BUSY, up to three times with growing delays, and runs it only once when already inside a transaction, since the outer transaction would still hold the lock. The block receives the context to use, and attempts that will be retried carry a marker so a busy statement in them is logged as a warning; only the final attempt logs errors. The scanner's inner error logs are folded into wrapped errors, so a recovered retry no longer prints error-level lines, and the folder path travels in the log context. * fix(persistence): join the enclosing transaction in a nested WithTxRetry Called on a store that is already inside a transaction, WithTxRetry went through WithTx, which opens a second, independent transaction on another connection. That transaction waits on the lock the outer one holds and fails with SQLITE_BUSY, and if it does succeed the outer transaction cannot roll it back. It now runs the block on the enclosing transaction, which owns the lock, the commit and the rollback. Found by a Codex (gpt-6-sol) review. * fix(scanner): retry the remaining scan writes on a busy database Every write step after phase 1 still aborted the whole scan on a single SQLITE_BUSY: phase 1 finalize, phase 2 moves and purge, phase 3 album saves and play count refreshes, the deferred playlist import flag, library ScanBegin, GC, the missing-artwork enqueue, tag counts, and the final library update. They now go through WithTxRetry. The phase 2 move had to be made rerun-safe first: it changed the target track's ID inside the transaction, so a rerun would have deleted the moved track itself, and it marked album annotations as handled even when the transaction rolled back. It now works on a copy per attempt and records the annotation reassignment only after a commit. Artist.RefreshStats is left alone: it updates artists in batches outside a transaction, and one transaction around all of them would hold the write lock for the whole refresh on slow storage. Phase 4 playlist imports go through the playlist service and are left for a follow-up. * fix(scanner): claim the album before moving its annotations The rerun-safe moveMatched checked processedAlbumAnnotations before its transaction and marked the album only after the commit. Phase 2 runs same-library and cross-library moves in separate pipeline stages, so two moves into one album could both pass the check; the second would reassign annotations again and overwrite the album's created_at. The album is now claimed under the lock before the transaction, as the old code effectively did, and the claim is released if the move fails so a later move can still reassign. Found by a Codex (gpt-6-sol) review. * fix(artwork): keep artwork housekeeping from writing during scans The artwork worker already pauses while a scan runs, but its housekeeping jobs did not: the hourly missing-artwork recheck (a bulk INSERT ... SELECT over albums and artists), the startup run of the same recheck, and the daily prune all kept competing with the scanner for the write lock. They now run through LockForMaintenance, like the scheduled DB analysis: they skip while a scan is running and keep a scan from starting until they finish. Skipping the recheck loses nothing, since each scan with changes queues missing artwork at its end. * refactor(scanner): log retried step errors once, from the caller Blocks passed to WithTxRetry still logged their own errors at error level on every attempt, so a busy error that a retry absorbed printed several error lines (GC printed three). They now return wrapped errors and the callers, which already log them, report the final outcome once. Also: drop a leftover variable in phase 1 finalize, check the walk context once, stop repeating the folder field that is already in the log context, stop shadowing finalize's err in phase 3, and format the WithTxRetry scope the same way as WithTx. * test(scanner): make the scanner suite's temp DB cleanup best effort Which DB file the process-wide DB handle opens depends on which spec touches it first. When the Scanner container wins the random order, its temp DB stays open until db.Close after RunSpecs, and on Windows removing the temp dir fails with 'being used by another process'. Ginkgo pins that on the container's last spec, which is now one of the busy-database specs. The sibling suites skip Windows for the same reason; this one now removes its temp dir on a best-effort basis instead, so it keeps running there.
215 lines
5.6 KiB
Go
215 lines
5.6 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"embed"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/mattn/go-sqlite3"
|
|
"github.com/navidrome/navidrome/conf"
|
|
_ "github.com/navidrome/navidrome/db/migrations"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/utils/hasher"
|
|
"github.com/navidrome/navidrome/utils/natural"
|
|
"github.com/navidrome/navidrome/utils/singleton"
|
|
"github.com/pressly/goose/v3"
|
|
)
|
|
|
|
// NaturalCollation sorts embedded numbers by value. It is registered on every
|
|
// connection, but only referenced when conf.Server.EnableNaturalSorting is on.
|
|
const NaturalCollation = "NATSORT"
|
|
|
|
var (
|
|
Dialect = "sqlite3"
|
|
Driver = Dialect + "_custom"
|
|
Path string
|
|
)
|
|
|
|
//go:embed migrations/*.sql
|
|
var embedMigrations embed.FS
|
|
|
|
const migrationsFolder = "migrations"
|
|
|
|
// sql.Register panics if called twice, so guard it: the singleton instance can be reset
|
|
// (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once.
|
|
var registerDriverOnce sync.Once
|
|
|
|
func Db() *sql.DB {
|
|
return singleton.GetInstance(func() *sql.DB {
|
|
registerDriverOnce.Do(func() {
|
|
sql.Register(Driver, &sqlite3.SQLiteDriver{
|
|
ConnectHook: func(conn *sqlite3.SQLiteConn) error {
|
|
if err := conn.RegisterFunc("SEEDEDRAND", hasher.HashFunc(), false); err != nil {
|
|
return err
|
|
}
|
|
return conn.RegisterCollation(NaturalCollation, natural.CompareFold)
|
|
},
|
|
})
|
|
})
|
|
Path = conf.Server.DbPath
|
|
if Path == ":memory:" {
|
|
Path = "file::memory:?cache=shared&_foreign_keys=on"
|
|
conf.Server.DbPath = Path
|
|
} else {
|
|
conf.Server.DataFolder.MustPath()
|
|
}
|
|
log.Debug("Opening DataBase", "dbPath", Path, "driver", Driver)
|
|
db, err := sql.Open(Driver, Path)
|
|
db.SetMaxOpenConns(conf.MaxOpenConns())
|
|
if err != nil {
|
|
log.Fatal("Error opening database", err)
|
|
}
|
|
return db
|
|
})
|
|
}
|
|
|
|
func Close(ctx context.Context) {
|
|
// Ignore cancellations when closing the DB
|
|
ctx = context.WithoutCancel(ctx)
|
|
|
|
log.Info(ctx, "Closing Database")
|
|
err := Db().Close()
|
|
if err != nil {
|
|
log.Error(ctx, "Error closing Database", err)
|
|
}
|
|
}
|
|
|
|
func Init(ctx context.Context) func() {
|
|
db := Db()
|
|
|
|
// Disable foreign_keys to allow re-creating tables in migrations
|
|
_, err := db.ExecContext(ctx, "PRAGMA foreign_keys=off")
|
|
defer func() {
|
|
_, err := db.ExecContext(ctx, "PRAGMA foreign_keys=on")
|
|
if err != nil {
|
|
log.Error(ctx, "Error re-enabling foreign_keys", err)
|
|
}
|
|
}()
|
|
if err != nil {
|
|
log.Error(ctx, "Error disabling foreign_keys", err)
|
|
}
|
|
|
|
goose.SetBaseFS(embedMigrations)
|
|
err = goose.SetDialect(Dialect)
|
|
if err != nil {
|
|
log.Fatal(ctx, "Invalid DB driver", "driver", Driver, err)
|
|
}
|
|
schemaEmpty := isSchemaEmpty(ctx, db)
|
|
hasSchemaChanges := hasPendingMigrations(ctx, db, migrationsFolder)
|
|
if !schemaEmpty && hasSchemaChanges {
|
|
log.Info(ctx, "Upgrading DB Schema to latest version")
|
|
}
|
|
goose.SetLogger(&logAdapter{ctx: ctx, silent: schemaEmpty})
|
|
err = goose.UpContext(ctx, db, migrationsFolder)
|
|
if err != nil {
|
|
log.Fatal(ctx, "Failed to apply new migrations", err)
|
|
}
|
|
|
|
if hasSchemaChanges {
|
|
log.Debug(ctx, "Running ANALYZE after schema changes")
|
|
err = optimizeAt(ctx, db, time.Now())
|
|
if err != nil {
|
|
log.Error(ctx, "Error running ANALYZE", err)
|
|
}
|
|
}
|
|
|
|
return func() {
|
|
Close(ctx)
|
|
}
|
|
}
|
|
|
|
// ErrorCodes reports the SQLite result code and extended result code carried by err.
|
|
// The extended code is what distinguishes errors that share a message: "database is locked"
|
|
// is both SQLITE_BUSY, which busy_timeout retries, and SQLITE_BUSY_SNAPSHOT, which it never can.
|
|
func ErrorCodes(err error) (code, extended int, ok bool) {
|
|
var se sqlite3.Error
|
|
if !errors.As(err, &se) {
|
|
return 0, 0, false
|
|
}
|
|
return int(se.Code), int(se.ExtendedCode), true
|
|
}
|
|
|
|
// IsBusy reports whether err is SQLITE_BUSY, including BUSY_SNAPSHOT, which only a new transaction clears.
|
|
func IsBusy(err error) bool {
|
|
code, _, ok := ErrorCodes(err)
|
|
return ok && code == int(sqlite3.ErrBusy)
|
|
}
|
|
|
|
type statusLogger struct{ numPending int }
|
|
|
|
func (*statusLogger) Fatalf(format string, v ...any) { log.Fatal(fmt.Sprintf(format, v...)) }
|
|
func (l *statusLogger) Printf(format string, v ...any) {
|
|
if len(v) < 1 {
|
|
return
|
|
}
|
|
if v0, ok := v[0].(string); !ok {
|
|
return
|
|
} else if v0 == "Pending" {
|
|
l.numPending++
|
|
}
|
|
}
|
|
|
|
func hasPendingMigrations(ctx context.Context, db *sql.DB, folder string) bool {
|
|
l := &statusLogger{}
|
|
goose.SetLogger(l)
|
|
err := goose.StatusContext(ctx, db, folder)
|
|
if err != nil {
|
|
log.Fatal(ctx, "Failed to check for pending migrations", err)
|
|
}
|
|
return l.numPending > 0
|
|
}
|
|
|
|
// hasGooseTable reports whether goose's bookkeeping table exists, i.e. whether the
|
|
// database has ever been migrated.
|
|
func hasGooseTable(ctx context.Context, db *sql.DB) (bool, error) {
|
|
var name string
|
|
err := db.QueryRowContext(ctx,
|
|
"SELECT name FROM sqlite_master WHERE type='table' AND name='goose_db_version'").Scan(&name)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
return err == nil, err
|
|
}
|
|
|
|
func isSchemaEmpty(ctx context.Context, db *sql.DB) bool {
|
|
found, err := hasGooseTable(ctx, db)
|
|
if err != nil {
|
|
log.Fatal(ctx, "Database could not be opened!", err)
|
|
}
|
|
return !found
|
|
}
|
|
|
|
type logAdapter struct {
|
|
ctx context.Context
|
|
silent bool
|
|
}
|
|
|
|
func (l *logAdapter) Fatal(v ...any) {
|
|
log.Fatal(l.ctx, fmt.Sprint(v...))
|
|
}
|
|
|
|
func (l *logAdapter) Fatalf(format string, v ...any) {
|
|
log.Fatal(l.ctx, fmt.Sprintf(format, v...))
|
|
}
|
|
|
|
func (l *logAdapter) Print(v ...any) {
|
|
if !l.silent {
|
|
log.Info(l.ctx, fmt.Sprint(v...))
|
|
}
|
|
}
|
|
|
|
func (l *logAdapter) Println(v ...any) {
|
|
if !l.silent {
|
|
log.Info(l.ctx, fmt.Sprintln(v...))
|
|
}
|
|
}
|
|
|
|
func (l *logAdapter) Printf(format string, v ...any) {
|
|
if !l.silent {
|
|
log.Info(l.ctx, fmt.Sprintf(format, v...))
|
|
}
|
|
}
|