From 125099ede27614f1bdbef873fc87563f8cf6631b Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 26 Nov 2026 12:38:56 -0500 Subject: [PATCH] fix(server): a background job that panics no longer stops the server (#8002) 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 --- cmd/minstrel/main.go | 36 ++++---- internal/api/admin_covers.go | 8 +- internal/api/playlists.go | 8 +- internal/backup/service.go | 16 +--- internal/coplay/worker.go | 19 ++-- internal/gc/worker.go | 13 +-- internal/library/acoustid_lookup.go | 16 +--- internal/library/duplicate_sweep.go | 25 ++---- internal/library/fingerprint_backfill.go | 21 +---- internal/library/leveled.go | 10 ++- internal/library/loudness_backfill.go | 21 +---- internal/library/trigger.go | 5 +- internal/notifications/digest.go | 15 +--- internal/notifications/retention.go | 15 +--- internal/periodic/periodic.go | 86 ++++++++++++++++++ internal/periodic/periodic_test.go | 109 +++++++++++++++++++++++ internal/playlists/scheduler.go | 5 +- internal/scrobble/worker.go | 16 ++-- internal/similarity/worker.go | 16 ++-- internal/sync/compactor.go | 13 +-- internal/tags/worker.go | 14 +-- 21 files changed, 281 insertions(+), 206 deletions(-) create mode 100644 internal/periodic/periodic.go create mode 100644 internal/periodic/periodic_test.go diff --git a/cmd/minstrel/main.go b/cmd/minstrel/main.go index e38ffd76..51a06877 100644 --- a/cmd/minstrel/main.go +++ b/cmd/minstrel/main.go @@ -30,6 +30,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/lookups" "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" "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/recsettings" "git.fabledsword.com/bvandeusen/minstrel/internal/scrobble" @@ -102,22 +103,15 @@ const safetyNetScanInterval = 12 * time.Hour func runSafetyNetScans(ctx context.Context, pool *pgxpool.Pool, scanner *library.Scanner, enricher *coverart.Enricher, logger *slog.Logger, scanCfg library.RunScanConfig, ) { - ticker := time.NewTicker(safetyNetScanInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - started, existing, err := library.TryStartScan(ctx, pool, scanner, enricher, logger, scanCfg) - if err != nil { - logger.Error("safety-net scan: try start failed", "err", err) - } else if !started && existing != nil { - logger.Info("safety-net scan skipped — prior still in flight", - "in_flight_id", existing.ID) - } + periodic.Run(ctx, logger, "safety-net scan", safetyNetScanInterval, func(ctx context.Context) { + started, existing, err := library.TryStartScan(ctx, pool, scanner, enricher, logger, scanCfg) + if err != nil { + logger.Error("safety-net scan: try start failed", "err", err) + } else if !started && existing != nil { + logger.Info("safety-net scan skipped — prior still in flight", + "in_flight_id", existing.ID) } - } + }, periodic.Delayed()) } func run() error { @@ -257,7 +251,7 @@ func run() error { // 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() { + go periodic.Safe(ctx, logger, "startup scan", func(ctx context.Context) { if _, err := library.RunScan(ctx, pool, scanner, coverEnricher, logger.With("component", "scan_run"), library.RunScanConfig{ @@ -269,11 +263,11 @@ func run() error { ); err != nil { logger.Warn("startup scan run failed", "err", err) } - }() + }) } else { // No startup file walk, but still run backfill + enrich so cover // 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, logger.With("component", "scan_run"), library.RunScanConfig{ @@ -285,7 +279,7 @@ func run() error { ); err != nil { logger.Warn("boot-only scan run failed", "err", err) } - }() + }) } // 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 // inline. Replaces the removed configurable scan scheduler. 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 { logger.Warn("library watcher exited", "err", werr) } - }() + }) // Safety-net delta walk backstops the watcher (inotify limits / dropped // events) at a fixed low frequency. No operator config. go runSafetyNetScans(ctx, pool, scanner, coverEnricher, diff --git a/internal/api/admin_covers.go b/internal/api/admin_covers.go index b9856f23..6e9a52c9 100644 --- a/internal/api/admin_covers.go +++ b/internal/api/admin_covers.go @@ -11,6 +11,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) type adminCoverRefetchResp struct { @@ -58,11 +59,10 @@ type adminBulkRefetchResp struct { // sources run at disk speed). The count is unknowable synchronously, so the // response just acknowledges the drain started. func (h *handlers) handleAdminBulkRefetchCovers(w http.ResponseWriter, _ *http.Request) { - go func() { - bgCtx := context.Background() - if _, err := h.coverart.EnrichRetryMissing(bgCtx, -1); err != nil { + go periodic.Safe(context.Background(), h.logger, "bulk cover refetch", func(ctx context.Context) { + if _, err := h.coverart.EnrichRetryMissing(ctx, -1); err != nil { h.logger.Warn("admin: bulk cover refetch failed", "err", err) } - }() + }) writeJSON(w, http.StatusOK, adminBulkRefetchResp{Started: true}) } diff --git a/internal/api/playlists.go b/internal/api/playlists.go index d4c9eabb..9225b33f 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -16,6 +16,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/apierror" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" "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 { return } - go func() { - bgCtx := context.Background() - if err := playlists.BuildSystemPlaylists(bgCtx, h.pool, h.logger, userID, time.Now(), h.dataDir); err != nil { + go periodic.Safe(context.Background(), h.logger, "lazy system playlist build", func(ctx context.Context) { + if err := playlists.BuildSystemPlaylists(ctx, h.pool, h.logger, userID, time.Now(), h.dataDir); err != nil { h.logger.Warn("lazy system playlist build failed", "user_id", "redacted", "err", err) } - }() + }) } // createPlaylistBody's ID is optional: a client that makes a playlist diff --git a/internal/backup/service.go b/internal/backup/service.go index 776a1cb9..50ca3c31 100644 --- a/internal/backup/service.go +++ b/internal/backup/service.go @@ -20,6 +20,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" "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.mu.Unlock() }() - s.run(trigger, st) + periodic.Safe(context.Background(), s.logger, "backup run", func(context.Context) { s.run(trigger, st) }) }() 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 // interval, so a restart isn't followed straight away by a backup. func (s *Service) Loop(ctx context.Context) { - s.Recover(ctx) - t := time.NewTicker(tickEvery) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - s.Tick(ctx) - } - } + periodic.Safe(ctx, s.logger, "backup recover", s.Recover) + periodic.Run(ctx, s.logger, "backup", tickEvery, s.Tick, periodic.Delayed()) } // Close stops a running backup and waits for it to record how it ended. diff --git a/internal/coplay/worker.go b/internal/coplay/worker.go index 732508e9..19bfd0c3 100644 --- a/internal/coplay/worker.go +++ b/internal/coplay/worker.go @@ -16,6 +16,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "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 @@ -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 // slow initial rebuild never blocks boot. func (w *Worker) Run(ctx context.Context) { - if err := w.rebuild(ctx); err != nil { - 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 { - w.logger.Error("coplay: rebuild failed", "err", err) - } + periodic.Run(ctx, w.logger, "coplay", w.tick, func(ctx context.Context) { + if err := w.rebuild(ctx); err != nil { + w.logger.Error("coplay: rebuild failed", "err", err) } - } + }) } // rebuild atomic-replaces the user_cooccurrence edge set inside one diff --git a/internal/gc/worker.go b/internal/gc/worker.go index 5a0ea9d8..f0a85f8e 100644 --- a/internal/gc/worker.go +++ b/internal/gc/worker.go @@ -26,6 +26,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "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 @@ -59,17 +60,7 @@ func (w *Worker) Run(ctx context.Context) { // Fire once at start so a freshly-deployed server doesn't wait a // full tick before doing the initial sweep. Matches the scrobble // + similarity workers' "sweep then tick" pattern. - w.tickOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.tickOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "gc", w.tick, w.tickOnce) } // tickOnce runs each sweep once, logging the affected-row count. diff --git a/internal/library/acoustid_lookup.go b/internal/library/acoustid_lookup.go index 2f896ff0..68b445d6 100644 --- a/internal/library/acoustid_lookup.go +++ b/internal/library/acoustid_lookup.go @@ -16,6 +16,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/acoustid" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) // 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 // a kick, and after every settings save. func (w *AcoustIDLookupWorker) Run(ctx context.Context) { - w.runOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - case <-w.kick: - case <-w.settings.Changed(): - } - w.runOnce(ctx) - } + periodic.Run(ctx, w.logger, "acoustid lookup", w.tick, w.runOnce, + periodic.WakeOn(w.kick, w.settings.Changed())) } // runOnce contains a pass so that nothing it does (an error, a panic) can stop diff --git a/internal/library/duplicate_sweep.go b/internal/library/duplicate_sweep.go index df54351e..acd11c6f 100644 --- a/internal/library/duplicate_sweep.go +++ b/internal/library/duplicate_sweep.go @@ -14,6 +14,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" 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) } - go func() { + go periodic.Safe(ctx, logger, "duplicate sweep", func(ctx context.Context) { if _, err := RunDuplicateSweep(ctx, pool, logger, cfg); err != nil { logger.Warn("duplicate sweep failed", "err", err) } - }() + }) return true, nil } @@ -326,26 +327,12 @@ func NewDuplicateSweepWorker( // Run blocks until ctx is cancelled, checking once at start and then each tick. func (w *DuplicateSweepWorker) Run(ctx context.Context) { - w.tickOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.tickOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "duplicate sweep", w.tick, w.tickOnce) } -// 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) { - defer func() { - if r := recover(); r != nil { - w.logger.Error("duplicate sweep: tick panicked", "panic", r) - } - }() cfg := w.settings.Get() due, err := duplicateSweepDue(ctx, dbq.New(w.pool), cfg, time.Now()) if err != nil { diff --git a/internal/library/fingerprint_backfill.go b/internal/library/fingerprint_backfill.go index 7f25ab9c..76c076e0 100644 --- a/internal/library/fingerprint_backfill.go +++ b/internal/library/fingerprint_backfill.go @@ -11,6 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) // Fingerprint backfill. @@ -101,27 +102,11 @@ func NewFingerprintBackfillWorker( // 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. func (w *FingerprintBackfillWorker) Run(ctx context.Context) { - w.runOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.runOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "fingerprint backfill", w.tick, w.runOnce) } -// runOnce contains a pass so that nothing it does — an error, a panic — can -// stop the next tick from firing. +// runOnce runs one pass and logs what it did. periodic.Run contains a panic. 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) if err != nil && ctx.Err() == nil { w.logger.Warn("fingerprint backfill: pass failed", "err", err, "processed", res.Processed) diff --git a/internal/library/leveled.go b/internal/library/leveled.go index d13360f7..7776d4a9 100644 --- a/internal/library/leveled.go +++ b/internal/library/leveled.go @@ -19,6 +19,8 @@ import ( "time" "golang.org/x/sync/singleflight" + + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) // Leveled streams. @@ -242,9 +244,11 @@ func (r *LeveledRenderer) Prerender(src LeveledSource, g LeveledGain) bool { defer func() { <-r.prerenders }() ctx, cancel := context.WithTimeout(context.Background(), loudnessTimeout(src.DurationMs)) defer cancel() - if _, err := r.Path(ctx, src, g); err != nil { - r.logger.Warn("leveled: prerender failed", "track", src.TrackID, "err", err) - } + periodic.Safe(ctx, r.logger, "leveled prerender", func(ctx context.Context) { + if _, err := r.Path(ctx, src, g); err != nil { + r.logger.Warn("leveled: prerender failed", "track", src.TrackID, "err", err) + } + }) }() return true } diff --git a/internal/library/loudness_backfill.go b/internal/library/loudness_backfill.go index afcae46f..7b78958e 100644 --- a/internal/library/loudness_backfill.go +++ b/internal/library/loudness_backfill.go @@ -11,6 +11,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) // Loudness backfill. @@ -92,27 +93,11 @@ func NewLoudnessBackfillWorker( // Run blocks until ctx is cancelled: one pass at start, then one per tick. func (w *LoudnessBackfillWorker) Run(ctx context.Context) { - w.runOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.runOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "loudness backfill", w.tick, w.runOnce) } -// runOnce contains a pass so that nothing it does (an error, a panic) can stop -// the next tick from firing. +// runOnce runs one pass and logs what it did. periodic.Run contains a panic. 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) if err != nil && ctx.Err() == nil { w.logger.Warn("loudness backfill: pass failed", "err", err, "processed", res.Processed) diff --git a/internal/library/trigger.go b/internal/library/trigger.go index a2e71e59..f228e17c 100644 --- a/internal/library/trigger.go +++ b/internal/library/trigger.go @@ -12,6 +12,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/coverart" "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 @@ -83,10 +84,10 @@ func TryStartScan(ctx context.Context, pool *pgxpool.Pool, } // 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 { logger.Warn("scan run failed", "err", runErr) } - }() + }) return true, nil, nil } diff --git a/internal/notifications/digest.go b/internal/notifications/digest.go index 94b44211..caf88624 100644 --- a/internal/notifications/digest.go +++ b/internal/notifications/digest.go @@ -13,6 +13,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "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 @@ -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 // few minutes. func (d *Digest) Run(ctx context.Context) { - 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) - } - } + periodic.Run(ctx, d.logger, "notification digest", digestInterval, func(ctx context.Context) { + d.Tick(ctx, time.Now()) + }) } // Tick sends every group that is due as of now. Failures are logged and diff --git a/internal/notifications/retention.go b/internal/notifications/retention.go index a329cbc1..38b38cec 100644 --- a/internal/notifications/retention.go +++ b/internal/notifications/retention.go @@ -8,6 +8,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) 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 // that has been down a while catches up, then daily. func (r *Retention) Run(ctx context.Context) { - 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) - } - } + periodic.Run(ctx, r.logger, "notification retention", retentionInterval, func(ctx context.Context) { + r.TrimOnce(ctx, time.Now()) + }) } // TrimOnce deletes what has outlived its retention as of now. Errors are diff --git a/internal/periodic/periodic.go b/internal/periodic/periodic.go new file mode 100644 index 00000000..a4ceb0f8 --- /dev/null +++ b/internal/periodic/periodic.go @@ -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) +} diff --git a/internal/periodic/periodic_test.go b/internal/periodic/periodic_test.go new file mode 100644 index 00000000..05f5b550 --- /dev/null +++ b/internal/periodic/periodic_test.go @@ -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 }) +} diff --git a/internal/playlists/scheduler.go b/internal/playlists/scheduler.go index ee23f7e1..70b1057c 100644 --- a/internal/playlists/scheduler.go +++ b/internal/playlists/scheduler.go @@ -28,6 +28,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" "git.fabledsword.com/bvandeusen/minstrel/internal/eventbus" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" "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 // system_cron.go startup runOnce so users who missed yesterday's // 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. if _, err := s.gocron.NewJob( diff --git a/internal/scrobble/worker.go b/internal/scrobble/worker.go index 53fcfe8b..82e69f10 100644 --- a/internal/scrobble/worker.go +++ b/internal/scrobble/worker.go @@ -10,6 +10,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "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/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. func (w *Worker) Run(ctx context.Context) { - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - if err := w.tickOnce(ctx); err != nil { - w.logger.Error("scrobble: tick failed", "err", err) - } + periodic.Run(ctx, w.logger, "scrobble", w.tick, func(ctx context.Context) { + if err := w.tickOnce(ctx); err != nil { + w.logger.Error("scrobble: tick failed", "err", err) } - } + }, periodic.Delayed()) } // tickOnce drains up to w.batch pending rows. Returns the first error diff --git a/internal/similarity/worker.go b/internal/similarity/worker.go index 2075cd61..15367115 100644 --- a/internal/similarity/worker.go +++ b/internal/similarity/worker.go @@ -28,6 +28,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" "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. func (w *Worker) Run(ctx context.Context) { - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - if err := w.tickOnce(ctx); err != nil { - w.logger.Error("similarity: tick failed", "err", err) - } + periodic.Run(ctx, w.logger, "similarity", w.tick, func(ctx context.Context) { + if err := w.tickOnce(ctx); err != nil { + w.logger.Error("similarity: tick failed", "err", err) } - } + }, periodic.Delayed()) } // tickOnce drains one batch of tracks and one batch of artists, unless an diff --git a/internal/sync/compactor.go b/internal/sync/compactor.go index b975540f..3fc99dd0 100644 --- a/internal/sync/compactor.go +++ b/internal/sync/compactor.go @@ -24,6 +24,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "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 @@ -57,17 +58,7 @@ func NewCompactor(pool *pgxpool.Pool, logger *slog.Logger) *Compactor { // Fires one tick immediately on startup so a long-running process // that hasn't been compacted in a while catches up. func (c *Compactor) Run(ctx context.Context) { - c.tickOnce(ctx) - t := time.NewTicker(c.interval) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - c.tickOnce(ctx) - } - } + periodic.Run(ctx, c.logger, "library changes compactor", c.interval, c.tickOnce) } // tickOnce trims the log once and logs what went. Errors are logged at WARN; diff --git a/internal/tags/worker.go b/internal/tags/worker.go index 701a08f3..e8c23048 100644 --- a/internal/tags/worker.go +++ b/internal/tags/worker.go @@ -4,6 +4,8 @@ import ( "context" "log/slog" "time" + + "git.fabledsword.com/bvandeusen/minstrel/internal/periodic" ) // 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. func (w *Worker) Run(ctx context.Context) { - w.tickOnce(ctx) - t := time.NewTicker(w.tick) - defer t.Stop() - for { - select { - case <-ctx.Done(): - return - case <-t.C: - w.tickOnce(ctx) - } - } + periodic.Run(ctx, w.logger, "tags", w.tick, w.tickOnce) } // tickOnce drains one bounded batch. EnrichTrackBatch already logs a