fix(server): a background job that panics no longer stops the server (#8002)
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m18s
release / android (push) Successful in 4m19s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 30s
release / Verify release artifacts (tag releases only) (push) Skipped

Background jobs run in their own goroutines, outside the router's panic
recovery, and only five of them recovered. A panic in the scrobble,
similarity, co-play, gc, tags, compactor, notification, backup or
safety-net loop, or in a scan or rebuild started off a request, ended
the process and every stream in it.

internal/periodic now runs each job: a pass at start (or after one
interval, Delayed), then one per interval and on any WakeOn channel,
each pass under recover with the stack logged. Detached one-shot work
(scans, the lazy system-playlist build, bulk cover refetch, leveled
prerender, the backup run, the playlist catch-up) runs under
periodic.Safe. The duplicate resolver keeps its own loop for its
retry-soon timer, and its pass already recovers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:38:56 -05:00
co-authored by Claude Opus 5.5
parent 9b36effbaf
commit 125099ede2
21 changed files with 281 additions and 206 deletions
+9 -15
View File
@@ -30,6 +30,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/lookups" "git.fabledsword.com/bvandeusen/minstrel/internal/lookups"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications" "git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings" "git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
"git.fabledsword.com/bvandeusen/minstrel/internal/scrobble" "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble"
@@ -102,13 +103,7 @@ const safetyNetScanInterval = 12 * time.Hour
func runSafetyNetScans(ctx context.Context, pool *pgxpool.Pool, scanner *library.Scanner, func runSafetyNetScans(ctx context.Context, pool *pgxpool.Pool, scanner *library.Scanner,
enricher *coverart.Enricher, logger *slog.Logger, scanCfg library.RunScanConfig, enricher *coverart.Enricher, logger *slog.Logger, scanCfg library.RunScanConfig,
) { ) {
ticker := time.NewTicker(safetyNetScanInterval) periodic.Run(ctx, logger, "safety-net scan", safetyNetScanInterval, func(ctx context.Context) {
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
started, existing, err := library.TryStartScan(ctx, pool, scanner, enricher, logger, scanCfg) started, existing, err := library.TryStartScan(ctx, pool, scanner, enricher, logger, scanCfg)
if err != nil { if err != nil {
logger.Error("safety-net scan: try start failed", "err", err) logger.Error("safety-net scan: try start failed", "err", err)
@@ -116,8 +111,7 @@ func runSafetyNetScans(ctx context.Context, pool *pgxpool.Pool, scanner *library
logger.Info("safety-net scan skipped — prior still in flight", logger.Info("safety-net scan skipped — prior still in flight",
"in_flight_id", existing.ID) "in_flight_id", existing.ID)
} }
} }, periodic.Delayed())
}
} }
func run() error { func run() error {
@@ -257,7 +251,7 @@ func run() error {
// closed first, so it doesn't read as a scan still going. // closed first, so it doesn't read as a scan still going.
library.RecoverScanRuns(ctx, pool, logger.With("component", "scan_run")) library.RecoverScanRuns(ctx, pool, logger.With("component", "scan_run"))
if cfg.Library.ScanOnStartup && len(roots) > 0 { if cfg.Library.ScanOnStartup && len(roots) > 0 {
go func() { go periodic.Safe(ctx, logger, "startup scan", func(ctx context.Context) {
if _, err := library.RunScan(ctx, pool, scanner, coverEnricher, if _, err := library.RunScan(ctx, pool, scanner, coverEnricher,
logger.With("component", "scan_run"), logger.With("component", "scan_run"),
library.RunScanConfig{ library.RunScanConfig{
@@ -269,11 +263,11 @@ func run() error {
); err != nil { ); err != nil {
logger.Warn("startup scan run failed", "err", err) logger.Warn("startup scan run failed", "err", err)
} }
}() })
} else { } else {
// No startup file walk, but still run backfill + enrich so cover // No startup file walk, but still run backfill + enrich so cover
// art keeps arriving with scan-on-startup off. // art keeps arriving with scan-on-startup off.
go func() { go periodic.Safe(ctx, logger, "boot scan", func(ctx context.Context) {
if _, err := library.RunScan(ctx, pool, nil, coverEnricher, if _, err := library.RunScan(ctx, pool, nil, coverEnricher,
logger.With("component", "scan_run"), logger.With("component", "scan_run"),
library.RunScanConfig{ library.RunScanConfig{
@@ -285,7 +279,7 @@ func run() error {
); err != nil { ); err != nil {
logger.Warn("boot-only scan run failed", "err", err) logger.Warn("boot-only scan run failed", "err", err)
} }
}() })
} }
// ListenBrainz scrobble worker: every 30s, drains up to 50 pending rows. // ListenBrainz scrobble worker: every 30s, drains up to 50 pending rows.
@@ -447,11 +441,11 @@ func run() error {
// fsnotify, scanning just the affected paths + enriching their albums // fsnotify, scanning just the affected paths + enriching their albums
// inline. Replaces the removed configurable scan scheduler. // inline. Replaces the removed configurable scan scheduler.
watcher := library.NewWatcher(scanner, coverEnricher, logger.With("component", "watcher")) watcher := library.NewWatcher(scanner, coverEnricher, logger.With("component", "watcher"))
go func() { go periodic.Safe(ctx, logger, "library watcher", func(ctx context.Context) {
if werr := watcher.Run(ctx); werr != nil { if werr := watcher.Run(ctx); werr != nil {
logger.Warn("library watcher exited", "err", werr) logger.Warn("library watcher exited", "err", werr)
} }
}() })
// Safety-net delta walk backstops the watcher (inotify limits / dropped // Safety-net delta walk backstops the watcher (inotify limits / dropped
// events) at a fixed low frequency. No operator config. // events) at a fixed low frequency. No operator config.
go runSafetyNetScans(ctx, pool, scanner, coverEnricher, go runSafetyNetScans(ctx, pool, scanner, coverEnricher,
+4 -4
View File
@@ -11,6 +11,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
type adminCoverRefetchResp struct { type adminCoverRefetchResp struct {
@@ -58,11 +59,10 @@ type adminBulkRefetchResp struct {
// sources run at disk speed). The count is unknowable synchronously, so the // sources run at disk speed). The count is unknowable synchronously, so the
// response just acknowledges the drain started. // response just acknowledges the drain started.
func (h *handlers) handleAdminBulkRefetchCovers(w http.ResponseWriter, _ *http.Request) { func (h *handlers) handleAdminBulkRefetchCovers(w http.ResponseWriter, _ *http.Request) {
go func() { go periodic.Safe(context.Background(), h.logger, "bulk cover refetch", func(ctx context.Context) {
bgCtx := context.Background() if _, err := h.coverart.EnrichRetryMissing(ctx, -1); err != nil {
if _, err := h.coverart.EnrichRetryMissing(bgCtx, -1); err != nil {
h.logger.Warn("admin: bulk cover refetch failed", "err", err) h.logger.Warn("admin: bulk cover refetch failed", "err", err)
} }
}() })
writeJSON(w, http.StatusOK, adminBulkRefetchResp{Started: true}) writeJSON(w, http.StatusOK, adminBulkRefetchResp{Started: true})
} }
+4 -4
View File
@@ -16,6 +16,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists" "git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
) )
@@ -174,13 +175,12 @@ func (h *handlers) maybeKickBackgroundBuild(ctx context.Context, userID pgtype.U
if !stale || run.InFlight { if !stale || run.InFlight {
return return
} }
go func() { go periodic.Safe(context.Background(), h.logger, "lazy system playlist build", func(ctx context.Context) {
bgCtx := context.Background() if err := playlists.BuildSystemPlaylists(ctx, h.pool, h.logger, userID, time.Now(), h.dataDir); err != nil {
if err := playlists.BuildSystemPlaylists(bgCtx, h.pool, h.logger, userID, time.Now(), h.dataDir); err != nil {
h.logger.Warn("lazy system playlist build failed", h.logger.Warn("lazy system playlist build failed",
"user_id", "redacted", "err", err) "user_id", "redacted", "err", err)
} }
}() })
} }
// createPlaylistBody's ID is optional: a client that makes a playlist // createPlaylistBody's ID is optional: a client that makes a playlist
+4 -12
View File
@@ -20,6 +20,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret" "git.fabledsword.com/bvandeusen/minstrel/internal/secret"
) )
@@ -556,7 +557,7 @@ func (s *Service) Start(ctx context.Context, trigger string) error {
s.runningSince = time.Time{} s.runningSince = time.Time{}
s.mu.Unlock() s.mu.Unlock()
}() }()
s.run(trigger, st) periodic.Safe(context.Background(), s.logger, "backup run", func(context.Context) { s.run(trigger, st) })
}() }()
return nil return nil
} }
@@ -732,17 +733,8 @@ func (s *Service) Recover(ctx context.Context) {
// Loop recovers, then ticks until ctx ends. The first tick waits a full // Loop recovers, then ticks until ctx ends. The first tick waits a full
// interval, so a restart isn't followed straight away by a backup. // interval, so a restart isn't followed straight away by a backup.
func (s *Service) Loop(ctx context.Context) { func (s *Service) Loop(ctx context.Context) {
s.Recover(ctx) periodic.Safe(ctx, s.logger, "backup recover", s.Recover)
t := time.NewTicker(tickEvery) periodic.Run(ctx, s.logger, "backup", tickEvery, s.Tick, periodic.Delayed())
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
s.Tick(ctx)
}
}
} }
// Close stops a running backup and waits for it to record how it ended. // Close stops a running backup and waits for it to record how it ended.
+3 -12
View File
@@ -16,6 +16,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// minJaccard is the co-play edge floor: prune weak pairs and self-limit hub // minJaccard is the co-play edge floor: prune weak pairs and self-limit hub
@@ -44,21 +45,11 @@ func NewWorker(pool *pgxpool.Pool, logger *slog.Logger) *Worker {
// then every w.tick until ctx is cancelled. Runs in its own goroutine, so a // then every w.tick until ctx is cancelled. Runs in its own goroutine, so a
// slow initial rebuild never blocks boot. // slow initial rebuild never blocks boot.
func (w *Worker) Run(ctx context.Context) { func (w *Worker) Run(ctx context.Context) {
if err := w.rebuild(ctx); err != nil { periodic.Run(ctx, w.logger, "coplay", w.tick, func(ctx context.Context) {
w.logger.Error("coplay: initial rebuild failed", "err", err)
}
t := time.NewTicker(w.tick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := w.rebuild(ctx); err != nil { if err := w.rebuild(ctx); err != nil {
w.logger.Error("coplay: rebuild failed", "err", err) w.logger.Error("coplay: rebuild failed", "err", err)
} }
} })
}
} }
// rebuild atomic-replaces the user_cooccurrence edge set inside one // rebuild atomic-replaces the user_cooccurrence edge set inside one
+2 -11
View File
@@ -26,6 +26,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// defaultTick is the production sweep cadence. 1 hour is generous // defaultTick is the production sweep cadence. 1 hour is generous
@@ -59,17 +60,7 @@ func (w *Worker) Run(ctx context.Context) {
// Fire once at start so a freshly-deployed server doesn't wait a // Fire once at start so a freshly-deployed server doesn't wait a
// full tick before doing the initial sweep. Matches the scrobble // full tick before doing the initial sweep. Matches the scrobble
// + similarity workers' "sweep then tick" pattern. // + similarity workers' "sweep then tick" pattern.
w.tickOnce(ctx) periodic.Run(ctx, w.logger, "gc", w.tick, w.tickOnce)
t := time.NewTicker(w.tick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
w.tickOnce(ctx)
}
}
} }
// tickOnce runs each sweep once, logging the affected-row count. // tickOnce runs each sweep once, logging the affected-row count.
+3 -13
View File
@@ -16,6 +16,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/acoustid" "git.fabledsword.com/bvandeusen/minstrel/internal/acoustid"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// AcoustID lookup worker. // AcoustID lookup worker.
@@ -171,19 +172,8 @@ func (w *AcoustIDLookupWorker) Status() AcoustIDLookupStatus {
// Run blocks until ctx is cancelled: one pass at start, then one per tick, on // Run blocks until ctx is cancelled: one pass at start, then one per tick, on
// a kick, and after every settings save. // a kick, and after every settings save.
func (w *AcoustIDLookupWorker) Run(ctx context.Context) { func (w *AcoustIDLookupWorker) Run(ctx context.Context) {
w.runOnce(ctx) periodic.Run(ctx, w.logger, "acoustid lookup", w.tick, w.runOnce,
t := time.NewTicker(w.tick) periodic.WakeOn(w.kick, w.settings.Changed()))
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
case <-w.kick:
case <-w.settings.Changed():
}
w.runOnce(ctx)
}
} }
// runOnce contains a pass so that nothing it does (an error, a panic) can stop // runOnce contains a pass so that nothing it does (an error, a panic) can stop
+6 -19
View File
@@ -14,6 +14,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
) )
@@ -299,11 +300,11 @@ func TryStartDuplicateSweep(
return false, fmt.Errorf("duplicate sweep in-flight check: %w", err) return false, fmt.Errorf("duplicate sweep in-flight check: %w", err)
} }
go func() { go periodic.Safe(ctx, logger, "duplicate sweep", func(ctx context.Context) {
if _, err := RunDuplicateSweep(ctx, pool, logger, cfg); err != nil { if _, err := RunDuplicateSweep(ctx, pool, logger, cfg); err != nil {
logger.Warn("duplicate sweep failed", "err", err) logger.Warn("duplicate sweep failed", "err", err)
} }
}() })
return true, nil return true, nil
} }
@@ -326,26 +327,12 @@ func NewDuplicateSweepWorker(
// Run blocks until ctx is cancelled, checking once at start and then each tick. // Run blocks until ctx is cancelled, checking once at start and then each tick.
func (w *DuplicateSweepWorker) Run(ctx context.Context) { func (w *DuplicateSweepWorker) Run(ctx context.Context) {
w.tickOnce(ctx) periodic.Run(ctx, w.logger, "duplicate sweep", w.tick, w.tickOnce)
t := time.NewTicker(w.tick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
w.tickOnce(ctx)
}
}
} }
// tickOnce contains one check so nothing it does can stop the next tick. // tickOnce checks whether a sweep is due and runs it. periodic.Run contains a
// panic.
func (w *DuplicateSweepWorker) tickOnce(ctx context.Context) { func (w *DuplicateSweepWorker) tickOnce(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
w.logger.Error("duplicate sweep: tick panicked", "panic", r)
}
}()
cfg := w.settings.Get() cfg := w.settings.Get()
due, err := duplicateSweepDue(ctx, dbq.New(w.pool), cfg, time.Now()) due, err := duplicateSweepDue(ctx, dbq.New(w.pool), cfg, time.Now())
if err != nil { if err != nil {
+3 -18
View File
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// Fingerprint backfill. // Fingerprint backfill.
@@ -101,27 +102,11 @@ func NewFingerprintBackfillWorker(
// Run blocks until ctx is cancelled: one pass at start, so a fresh deploy does // Run blocks until ctx is cancelled: one pass at start, so a fresh deploy does
// not sit idle for an hour, then one per tick. // not sit idle for an hour, then one per tick.
func (w *FingerprintBackfillWorker) Run(ctx context.Context) { func (w *FingerprintBackfillWorker) Run(ctx context.Context) {
w.runOnce(ctx) periodic.Run(ctx, w.logger, "fingerprint backfill", w.tick, w.runOnce)
t := time.NewTicker(w.tick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
w.runOnce(ctx)
}
}
} }
// runOnce contains a pass so that nothing it does — an error, a panic — can // runOnce runs one pass and logs what it did. periodic.Run contains a panic.
// stop the next tick from firing.
func (w *FingerprintBackfillWorker) runOnce(ctx context.Context) { func (w *FingerprintBackfillWorker) runOnce(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
w.logger.Error("fingerprint backfill: pass panicked", "panic", r)
}
}()
res, err := w.pass(ctx) res, err := w.pass(ctx)
if err != nil && ctx.Err() == nil { if err != nil && ctx.Err() == nil {
w.logger.Warn("fingerprint backfill: pass failed", "err", err, "processed", res.Processed) w.logger.Warn("fingerprint backfill: pass failed", "err", err, "processed", res.Processed)
+4
View File
@@ -19,6 +19,8 @@ import (
"time" "time"
"golang.org/x/sync/singleflight" "golang.org/x/sync/singleflight"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// Leveled streams. // Leveled streams.
@@ -242,9 +244,11 @@ func (r *LeveledRenderer) Prerender(src LeveledSource, g LeveledGain) bool {
defer func() { <-r.prerenders }() defer func() { <-r.prerenders }()
ctx, cancel := context.WithTimeout(context.Background(), loudnessTimeout(src.DurationMs)) ctx, cancel := context.WithTimeout(context.Background(), loudnessTimeout(src.DurationMs))
defer cancel() defer cancel()
periodic.Safe(ctx, r.logger, "leveled prerender", func(ctx context.Context) {
if _, err := r.Path(ctx, src, g); err != nil { if _, err := r.Path(ctx, src, g); err != nil {
r.logger.Warn("leveled: prerender failed", "track", src.TrackID, "err", err) r.logger.Warn("leveled: prerender failed", "track", src.TrackID, "err", err)
} }
})
}() }()
return true return true
} }
+3 -18
View File
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// Loudness backfill. // Loudness backfill.
@@ -92,27 +93,11 @@ func NewLoudnessBackfillWorker(
// Run blocks until ctx is cancelled: one pass at start, then one per tick. // Run blocks until ctx is cancelled: one pass at start, then one per tick.
func (w *LoudnessBackfillWorker) Run(ctx context.Context) { func (w *LoudnessBackfillWorker) Run(ctx context.Context) {
w.runOnce(ctx) periodic.Run(ctx, w.logger, "loudness backfill", w.tick, w.runOnce)
t := time.NewTicker(w.tick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
w.runOnce(ctx)
}
}
} }
// runOnce contains a pass so that nothing it does (an error, a panic) can stop // runOnce runs one pass and logs what it did. periodic.Run contains a panic.
// the next tick from firing.
func (w *LoudnessBackfillWorker) runOnce(ctx context.Context) { func (w *LoudnessBackfillWorker) runOnce(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
w.logger.Error("loudness backfill: pass panicked", "panic", r)
}
}()
res, err := w.pass(ctx) res, err := w.pass(ctx)
if err != nil && ctx.Err() == nil { if err != nil && ctx.Err() == nil {
w.logger.Warn("loudness backfill: pass failed", "err", err, "processed", res.Processed) w.logger.Warn("loudness backfill: pass failed", "err", err, "processed", res.Processed)
+3 -2
View File
@@ -12,6 +12,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// StuckScanThreshold is the age past which an in-flight scan_runs row is // StuckScanThreshold is the age past which an in-flight scan_runs row is
@@ -83,10 +84,10 @@ func TryStartScan(ctx context.Context, pool *pgxpool.Pool,
} }
// No in-flight (or just reaped). Start RunScan detached. // No in-flight (or just reaped). Start RunScan detached.
go func() { go periodic.Safe(ctx, logger, "scan run", func(ctx context.Context) {
if _, runErr := RunScan(ctx, pool, scanner, enricher, logger, cfg); runErr != nil { if _, runErr := RunScan(ctx, pool, scanner, enricher, logger, cfg); runErr != nil {
logger.Warn("scan run failed", "err", runErr) logger.Warn("scan run failed", "err", runErr)
} }
}() })
return true, nil, nil return true, nil, nil
} }
+3 -10
View File
@@ -13,6 +13,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// The email digest. Nothing is emailed per event: a steady stream of new // The email digest. Nothing is emailed per event: a steady stream of new
@@ -159,17 +160,9 @@ func NewDigest(pool *pgxpool.Pool, sender mailer.Sender, logger *slog.Logger) *D
// that has been down past a batch or a summary hour catches up, then every // that has been down past a batch or a summary hour catches up, then every
// few minutes. // few minutes.
func (d *Digest) Run(ctx context.Context) { func (d *Digest) Run(ctx context.Context) {
periodic.Run(ctx, d.logger, "notification digest", digestInterval, func(ctx context.Context) {
d.Tick(ctx, time.Now()) d.Tick(ctx, time.Now())
t := time.NewTicker(digestInterval) })
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
d.Tick(ctx, now)
}
}
} }
// Tick sends every group that is due as of now. Failures are logged and // Tick sends every group that is due as of now. Failures are logged and
+3 -10
View File
@@ -8,6 +8,7 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
const ( const (
@@ -35,17 +36,9 @@ func NewRetention(db dbq.DBTX, logger *slog.Logger) *Retention {
// Run blocks until ctx is cancelled. It trims once at startup, so a process // Run blocks until ctx is cancelled. It trims once at startup, so a process
// that has been down a while catches up, then daily. // that has been down a while catches up, then daily.
func (r *Retention) Run(ctx context.Context) { func (r *Retention) Run(ctx context.Context) {
periodic.Run(ctx, r.logger, "notification retention", retentionInterval, func(ctx context.Context) {
r.TrimOnce(ctx, time.Now()) r.TrimOnce(ctx, time.Now())
t := time.NewTicker(retentionInterval) })
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
r.TrimOnce(ctx, now)
}
}
} }
// TrimOnce deletes what has outlived its retention as of now. Errors are // TrimOnce deletes what has outlived its retention as of now. Errors are
+86
View File
@@ -0,0 +1,86 @@
// Package periodic runs the server's background jobs: a pass now, then one
// per interval until the server shuts down.
//
// Every pass runs under recover. These jobs run in their own goroutines,
// outside the HTTP router's panic recovery, so without it one bad row that
// panics a pass would stop the whole server, streams in progress included.
// A pass that panics is logged and the next one starts on schedule.
package periodic
import (
"context"
"log/slog"
"runtime/debug"
"time"
)
type config struct {
delayed bool
wake []<-chan struct{}
}
// Option changes when a job's passes run.
type Option func(*config)
// Delayed skips the pass at start: the first one runs after one interval.
// For jobs that would otherwise all hit the network or the database in the
// same second as the server comes up.
func Delayed() Option { return func(c *config) { c.delayed = true } }
// WakeOn also runs a pass whenever one of chs receives, such as an admin's
// "run now" or a settings change. A nil channel never wakes the job.
func WakeOn(chs ...<-chan struct{}) Option {
return func(c *config) { c.wake = append(c.wake, chs...) }
}
// Run calls pass now (unless Delayed) and then once every interval, until
// ctx ends. It blocks, so start it with `go`. name labels the job in the log.
func Run(ctx context.Context, logger *slog.Logger, name string, every time.Duration,
pass func(context.Context), opts ...Option,
) {
var c config
for _, o := range opts {
o(&c)
}
// Up to two wake channels, as a select needs them by name. More than
// that is a sign the job wants its own loop.
var wake1, wake2 <-chan struct{}
if len(c.wake) > 0 {
wake1 = c.wake[0]
}
if len(c.wake) > 1 {
wake2 = c.wake[1]
}
if len(c.wake) > 2 {
panic("periodic.Run: at most two wake channels")
}
if !c.delayed {
Safe(ctx, logger, name, pass)
}
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
case <-wake1:
case <-wake2:
}
if ctx.Err() != nil {
return
}
Safe(ctx, logger, name, pass)
}
}
// Safe calls pass once and turns a panic into an error in the log, with the
// stack, so the caller carries on.
func Safe(ctx context.Context, logger *slog.Logger, name string, pass func(context.Context)) {
defer func() {
if r := recover(); r != nil {
logger.Error(name+": pass panicked", "panic", r, "stack", string(debug.Stack()))
}
}()
pass(ctx)
}
+109
View File
@@ -0,0 +1,109 @@
package periodic
import (
"bytes"
"context"
"log/slog"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// syncBuffer lets the job's goroutine log while the test reads.
type syncBuffer struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuffer) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuffer) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.String()
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(time.Millisecond)
}
}
func TestRun_APanickingPassDoesNotStopTheNext(t *testing.T) {
var logs syncBuffer
logger := slog.New(slog.NewTextHandler(&logs, nil))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var passes atomic.Int32
done := make(chan struct{})
go func() {
Run(ctx, logger, "test job", 5*time.Millisecond, func(context.Context) {
if passes.Add(1) == 1 {
panic("boom")
}
})
close(done)
}()
waitFor(t, "a second pass after the panic", func() bool { return passes.Load() >= 2 })
if !strings.Contains(logs.String(), "test job: pass panicked") {
t.Fatalf("the panic was not logged; log: %s", logs.String())
}
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("Run did not return after cancel")
}
}
func TestRun_FirstPassTiming(t *testing.T) {
logger := slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil))
for _, tc := range []struct {
name string
opts []Option
atStart bool
}{
{"runs at start by default", nil, true},
{"waits an interval when delayed", []Option{Delayed()}, false},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var passes atomic.Int32
go Run(ctx, logger, "test job", time.Hour, func(context.Context) { passes.Add(1) }, tc.opts...)
if tc.atStart {
waitFor(t, "the first pass", func() bool { return passes.Load() == 1 })
return
}
time.Sleep(50 * time.Millisecond)
if n := passes.Load(); n != 0 {
t.Fatalf("a delayed job ran %d passes before its first interval", n)
}
})
}
}
func TestRun_WakeOnRunsAPassBeforeTheInterval(t *testing.T) {
logger := slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
kick := make(chan struct{}, 1)
var passes atomic.Int32
go Run(ctx, logger, "test job", time.Hour, func(context.Context) { passes.Add(1) },
Delayed(), WakeOn(kick, nil))
kick <- struct{}{}
waitFor(t, "a pass on the kick", func() bool { return passes.Load() == 1 })
}
+4 -1
View File
@@ -28,6 +28,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
"git.fabledsword.com/bvandeusen/minstrel/internal/taste" "git.fabledsword.com/bvandeusen/minstrel/internal/taste"
) )
@@ -109,7 +110,9 @@ func (s *Scheduler) Start(ctx context.Context) error {
// now, regardless of their scheduled time. Mirrors the existing // now, regardless of their scheduled time. Mirrors the existing
// system_cron.go startup runOnce so users who missed yesterday's // system_cron.go startup runOnce so users who missed yesterday's
// schedule (process down) get caught up. // schedule (process down) get caught up.
go s.runStartupCatchUp(ctx, users) go periodic.Safe(ctx, s.logger, "playlist startup catch-up", func(ctx context.Context) {
s.runStartupCatchUp(ctx, users)
})
// Hourly reconciliation pass. // Hourly reconciliation pass.
if _, err := s.gocron.NewJob( if _, err := s.gocron.NewJob(
+3 -9
View File
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
"git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz" "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret" "git.fabledsword.com/bvandeusen/minstrel/internal/secret"
) )
@@ -55,18 +56,11 @@ func NewWorker(pool *pgxpool.Pool, client *listenbrainz.Client, logger *slog.Log
// Run blocks until ctx is cancelled, ticking every w.tick. // Run blocks until ctx is cancelled, ticking every w.tick.
func (w *Worker) Run(ctx context.Context) { func (w *Worker) Run(ctx context.Context) {
t := time.NewTicker(w.tick) periodic.Run(ctx, w.logger, "scrobble", w.tick, func(ctx context.Context) {
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := w.tickOnce(ctx); err != nil { if err := w.tickOnce(ctx); err != nil {
w.logger.Error("scrobble: tick failed", "err", err) w.logger.Error("scrobble: tick failed", "err", err)
} }
} }, periodic.Delayed())
}
} }
// tickOnce drains up to w.batch pending rows. Returns the first error // tickOnce drains up to w.batch pending rows. Returns the first error
+3 -9
View File
@@ -28,6 +28,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
"git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz" "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz"
) )
@@ -64,18 +65,11 @@ func NewWorker(pool *pgxpool.Pool, client *listenbrainz.Client, logger *slog.Log
// Run blocks until ctx is cancelled, ticking every w.tick. // Run blocks until ctx is cancelled, ticking every w.tick.
func (w *Worker) Run(ctx context.Context) { func (w *Worker) Run(ctx context.Context) {
t := time.NewTicker(w.tick) periodic.Run(ctx, w.logger, "similarity", w.tick, func(ctx context.Context) {
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := w.tickOnce(ctx); err != nil { if err := w.tickOnce(ctx); err != nil {
w.logger.Error("similarity: tick failed", "err", err) w.logger.Error("similarity: tick failed", "err", err)
} }
} }, periodic.Delayed())
}
} }
// tickOnce drains one batch of tracks and one batch of artists, unless an // tickOnce drains one batch of tracks and one batch of artists, unless an
+2 -11
View File
@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// CompactorRetention is how long a delete stays in the log. An app that // CompactorRetention is how long a delete stays in the log. An app that
@@ -57,17 +58,7 @@ func NewCompactor(pool *pgxpool.Pool, logger *slog.Logger) *Compactor {
// Fires one tick immediately on startup so a long-running process // Fires one tick immediately on startup so a long-running process
// that hasn't been compacted in a while catches up. // that hasn't been compacted in a while catches up.
func (c *Compactor) Run(ctx context.Context) { func (c *Compactor) Run(ctx context.Context) {
c.tickOnce(ctx) periodic.Run(ctx, c.logger, "library changes compactor", c.interval, c.tickOnce)
t := time.NewTicker(c.interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
c.tickOnce(ctx)
}
}
} }
// tickOnce trims the log once and logs what went. Errors are logged at WARN; // tickOnce trims the log once and logs what went. Errors are logged at WARN;
+3 -11
View File
@@ -4,6 +4,8 @@ import (
"context" "context"
"log/slog" "log/slog"
"time" "time"
"git.fabledsword.com/bvandeusen/minstrel/internal/periodic"
) )
// Worker periodically drains tracks needing tag enrichment. Unlike cover // Worker periodically drains tracks needing tag enrichment. Unlike cover
@@ -35,17 +37,7 @@ func NewWorker(enricher *Enricher, logger *slog.Logger) *Worker {
// Run blocks until ctx is cancelled: an initial drain, then every w.tick. // Run blocks until ctx is cancelled: an initial drain, then every w.tick.
func (w *Worker) Run(ctx context.Context) { func (w *Worker) Run(ctx context.Context) {
w.tickOnce(ctx) periodic.Run(ctx, w.logger, "tags", w.tick, w.tickOnce)
t := time.NewTicker(w.tick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
w.tickOnce(ctx)
}
}
} }
// tickOnce drains one bounded batch. EnrichTrackBatch already logs a // tickOnce drains one bounded batch. EnrichTrackBatch already logs a