package bootstrap import ( "context" "fmt" "log/slog" "time" "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/worker/jobrunner" "lincodex/backend/internal/worker/retry" ) const ( // jobsPoolMaxConns covers the handler transaction and one statement // next to it, such as a backlog read; the worker runs one job at a time. jobsPoolMaxConns = 2 // jobsStoreTimeout bounds one claim, failure record, release, or // backlog read. Each is one indexed statement, so a healthy database // answers well below it. jobsStoreTimeout = 5 * time.Second // jobsBacklogInterval matches the usual Prometheus scrape interval. jobsBacklogInterval = 15 * time.Second ) var _ jobrunner.Metrics = (*prometheus.Metrics)(nil) // jobHandlers lists the scheduled job handlers, one per kind. A product // module adds its handler here, for example the invitation response // deadline, and the worker then claims jobs of that kind with the next // deployment. Jobs of a kind without a handler wait in the database. func jobHandlers() []inbound.JobHandler { return []inbound.JobHandler{} } func newJobWorker( ctx context.Context, settings config.Config, logger *slog.Logger, metrics *prometheus.Metrics, ) (*jobrunner.Worker, func(), error) { return buildJobWorker(ctx, settings, logger, metrics, jobHandlers()) } // buildJobWorker builds the scheduled job worker and the PostgreSQL pool it // owns. Nothing connects here, so an unavailable database never blocks // startup; the worker retries in the background. It returns no worker when // JOBS_ENABLED is false, when no handler is registered, or when // DATABASE_URL is unset. The application clock is time.Now. func buildJobWorker( ctx context.Context, settings config.Config, logger *slog.Logger, metrics jobrunner.Metrics, handlers []inbound.JobHandler, ) (*jobrunner.Worker, func(), error) { switch { case !settings.JobsEnabled: logger.Info("scheduled job worker is disabled; due jobs wait in the database") return nil, func() {}, nil case len(handlers) == 0: logger.Info("no scheduled job kind is registered") return nil, func() {}, nil case settings.DatabaseURL == "": logger.Warn("scheduled job worker skipped because DATABASE_URL is not set") return nil, func() {}, nil } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, jobsPoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.buildJobWorker - create pool: %w", err) } // The run transaction lasts at most one lease, which also bounds the // handler. store := postgres.NewScheduledJobStore(pool, settings.JobsLeaseDuration) worker, err := jobrunner.New( handlers, store, metrics, logger.With(slog.String("component", "scheduled_jobs")), jobWorkerSettings(settings), time.Now, ) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.buildJobWorker - create worker: %w", err) } // The application stops the worker before this cleanup runs, so no job // uses the pool while it closes. return worker, pool.Close, nil } func jobWorkerSettings(settings config.Config) jobrunner.Settings { return jobrunner.Settings{ BatchSize: settings.JobsBatchSize, PollInterval: settings.JobsPollInterval, Lease: settings.JobsLeaseDuration, MaxAttempts: settings.JobsMaxAttempts, Backoff: retry.Backoff{ Initial: settings.JobsBackoffInitial, Max: settings.JobsBackoffMax, }, ShutdownGrace: settings.JobsShutdownGrace, StoreTimeout: jobsStoreTimeout, BacklogInterval: jobsBacklogInterval, } }