// 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) }