The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
7 changed files with 123 additions and 10 deletions
Showing only changes of commit 785b15ab5f - Show all commits
+3 -1
View File
@@ -244,7 +244,9 @@ func run() error {
// One unified scan chain: library walk → MBID backfill → cover enrich.
// Boot-time scan and manual-trigger scans share this path; results land
// in scan_runs for the admin overview.
// in scan_runs for the admin overview. A run the last shutdown cut off is
// closed first, so it doesn't read as a scan still going.
library.RecoverScanRuns(ctx, pool, logger.With("component", "scan_run"))
if cfg.Library.ScanOnStartup && len(roots) > 0 {
go func() {
if _, err := library.RunScan(ctx, pool, scanner, coverEnricher,
+18
View File
@@ -11,6 +11,24 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const failUnfinishedScanRuns = `-- name: FailUnfinishedScanRuns :execrows
UPDATE scan_runs
SET finished_at = now(),
error_message = 'The server stopped while the scan was running.'
WHERE finished_at IS NULL
`
// At startup no scan can be running yet, so a row still unfinished was cut
// off when the server last stopped. Closing it keeps it from reading as a
// scan in progress, which would block saving library folders.
func (q *Queries) FailUnfinishedScanRuns(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, failUnfinishedScanRuns)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const finishScanRun = `-- name: FinishScanRun :exec
UPDATE scan_runs
SET finished_at = now(),
+9
View File
@@ -38,6 +38,15 @@ UPDATE scan_runs
SET artist_art_enrich = $2
WHERE id = $1;
-- name: FailUnfinishedScanRuns :execrows
-- At startup no scan can be running yet, so a row still unfinished was cut
-- off when the server last stopped. Closing it keeps it from reading as a
-- scan in progress, which would block saving library folders.
UPDATE scan_runs
SET finished_at = now(),
error_message = 'The server stopped while the scan was running.'
WHERE finished_at IS NULL;
-- name: GetInFlightScanRun :one
-- Used by POST /api/admin/scan/run to 409 when a scan is already running.
-- "In flight" = finished_at IS NULL.
+4 -4
View File
@@ -598,15 +598,15 @@ func (w *DuplicateResolveWorker) tickOnce(ctx context.Context) (waitForScan bool
// A scan in flight has listed the files it will reconcile: a copy removed
// now is marked present again when it does. A run past StuckScanThreshold
// is a dead one.
run, err := q.GetInFlightScanRun(ctx)
running, err := scanRunning(ctx, q)
switch {
case err == nil && time.Since(run.StartedAt.Time) <= StuckScanThreshold:
return true
case err != nil && !errors.Is(err, pgx.ErrNoRows):
case err != nil:
if ctx.Err() == nil {
w.logger.Warn("duplicate resolve: scan check failed", "err", err)
}
return false
case running:
return true
}
res, err := ResolveDuplicatesWith(ctx, w.pool, w.logger, w.dataDir, w.settings.Get().AutoResolve, w.src)
if err != nil && ctx.Err() == nil {
+5 -5
View File
@@ -80,13 +80,13 @@ func (s *Scanner) SetRoots(ctx context.Context, changes []RootChange) (RerootRes
q := dbq.New(s.pool)
// A scan walking the old folders would put their paths back, or mark the
// moved rows missing when it reconciles.
_, err = q.GetInFlightScanRun(ctx)
if err == nil {
return RerootResult{}, badRoots("A library scan is running; save again once it finishes.")
}
if !errors.Is(err, pgx.ErrNoRows) {
running, err := scanRunning(ctx, q)
if err != nil {
return RerootResult{}, fmt.Errorf("in-flight scan check: %w", err)
}
if running {
return RerootResult{}, badRoots("A library scan is running; save again once it finishes.")
}
for _, m := range moves {
if err := checkMove(ctx, q, m); err != nil {
return RerootResult{}, err
+57
View File
@@ -0,0 +1,57 @@
package library
import (
"context"
"errors"
"testing"
"github.com/jackc/pgx/v5/pgtype"
)
// A scan the last shutdown cut off is closed at startup with the reason, so
// it no longer reads as a scan in progress.
func TestRecoverScanRuns_ClosesARunTheLastShutdownCutOff_Integration(t *testing.T) {
pool := triggerTestPool(t)
ctx := context.Background()
var id pgtype.UUID
if err := pool.QueryRow(ctx,
`INSERT INTO scan_runs (started_at) VALUES (now() - interval '5 minutes') RETURNING id`).Scan(&id); err != nil {
t.Fatal(err)
}
RecoverScanRuns(ctx, pool, quietLogger())
var finished bool
var reason *string
if err := pool.QueryRow(ctx,
`SELECT finished_at IS NOT NULL, error_message FROM scan_runs WHERE id = $1`, id).Scan(&finished, &reason); err != nil {
t.Fatal(err)
}
if !finished || reason == nil || *reason == "" {
t.Errorf("finished %v, reason %v; want the run closed with why", finished, reason)
}
}
// Saving library folders waits for a scan that is running, but not for an
// unfinished run older than StuckScanThreshold: that one is dead.
func TestSetRoots_OnlyALiveScanHoldsUpSavingFolders_Integration(t *testing.T) {
pool := triggerTestPool(t)
clearSavedRoots(t, pool)
ctx := context.Background()
s := New(pool, quietLogger(), nil, nil)
if _, err := pool.Exec(ctx, `INSERT INTO scan_runs (started_at) VALUES (now() - interval '2 hours')`); err != nil {
t.Fatal(err)
}
if _, err := s.SetRoots(ctx, []RootChange{{Path: t.TempDir()}}); err != nil {
t.Errorf("a dead scan blocked saving folders: %v", err)
}
if _, err := pool.Exec(ctx, `INSERT INTO scan_runs (started_at) VALUES (now())`); err != nil {
t.Fatal(err)
}
var re *RootsError
if _, err := s.SetRoots(ctx, []RootChange{{Path: t.TempDir()}}); !errors.As(err, &re) {
t.Errorf("err %v; want a refusal while a scan is running", err)
}
}
+27
View File
@@ -20,6 +20,33 @@ import (
// duration so a normally-running scan is never reaped accidentally.
const StuckScanThreshold = 1 * time.Hour
// RecoverScanRuns closes the scan runs a stopped server left unfinished. It
// runs once at startup, before the first scan: none can be running yet.
func RecoverScanRuns(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) {
n, err := dbq.New(pool).FailUnfinishedScanRuns(ctx)
if err != nil {
logger.Warn("scan: recover unfinished runs", "err", err)
return
}
if n > 0 {
logger.Warn("scan: a run was cut off by the last shutdown", "runs", n)
}
}
// scanRunning reports whether a library scan is running now: an unfinished
// run that started within StuckScanThreshold. An older unfinished run is a
// dead one, and doesn't hold anything up.
func scanRunning(ctx context.Context, q *dbq.Queries) (bool, error) {
run, err := q.GetInFlightScanRun(ctx)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
return time.Since(run.StartedAt.Time) <= StuckScanThreshold, nil
}
// TryStartScan attempts to start a new scan, with built-in handling for
// stuck/stale in-flight rows.
//