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
+4 -4
View File
@@ -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})
}
+4 -4
View File
@@ -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
+4 -12
View File
@@ -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.
+5 -14
View File
@@ -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
+2 -11
View File
@@ -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.
+3 -13
View File
@@ -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
+6 -19
View File
@@ -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 {
+3 -18
View File
@@ -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)
+7 -3
View File
@@ -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
}
+3 -18
View File
@@ -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)
+3 -2
View File
@@ -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
}
+4 -11
View File
@@ -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
+4 -11
View File
@@ -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
+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/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(
+5 -11
View File
@@ -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
+5 -11
View File
@@ -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
+2 -11
View File
@@ -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;
+3 -11
View File
@@ -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