feat(jobs): add durable due-time job runner with leases

This commit is contained in:
shira committed 2026-10-06 14:29:23 +03:00
1 parent 7e80c8ad2a
commit 008254e44a
39 files changed
+4909 -43

No files matched your search

+19 -7
View File
@@ -18,6 +18,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/outboxrelay"
)
@@ -40,6 +41,10 @@ type Application struct {
// consumers apply events from the event bus while the servers run. The
// list is empty until a handler is registered in eventHandlers.
consumers eventConsumers
// jobs runs scheduled jobs when they fall due while the servers run. It
// is nil when the worker is disabled, no job kind is registered, or the
// database is not configured.
jobs *jobrunner.Worker
}
func NewApplication(
@@ -50,6 +55,7 @@ func NewApplication(
mailSender outbound.MailSender,
relay *outboxrelay.Relay,
consumers eventConsumers,
jobs *jobrunner.Worker,
) *Application {
return &Application{
config: config,
@@ -59,6 +65,7 @@ func NewApplication(
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
}
}
@@ -174,18 +181,20 @@ func (application *Application) run(ctx context.Context) error {
)
application.logger.Info("servers stopped")
stopRun()
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT and
// each consumer its record in progress within CONSUMER_SHUTDOWN_GRACE
// plus one offset commit, so the cleanup that closes their pools,
// producer, and group members runs after all of them stopped.
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, each
// consumer its record in progress within CONSUMER_SHUTDOWN_GRACE plus
// one offset commit, and the job worker its job in progress within
// JOBS_SHUTDOWN_GRACE plus one release, so the cleanup that closes their
// pools, producer, and group members runs after all of them stopped.
<-workersStopped
application.logger.Info("workers stopped")
return err
}
// startWorkers runs the relay and every consumer until ctx ends and returns
// a channel that closes when all of them have stopped. The workers stop
// together with the servers; none of them depends on another.
// startWorkers runs the relay, every consumer, and the scheduled job worker
// until ctx ends and returns a channel that closes when all of them have
// stopped. The workers stop together with the servers; none of them
// depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
var workers sync.WaitGroup
if application.relay != nil {
@@ -194,6 +203,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
for _, consumer := range application.consumers {
workers.Go(func() { consumer.Run(ctx) })
}
if application.jobs != nil {
workers.Go(func() { application.jobs.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
+1 -1
View File
@@ -191,7 +191,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer})
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+109
View File
@@ -0,0 +1,109 @@
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,
}
}
+105
View File
@@ -0,0 +1,105 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
type kindHandler string
func (handler kindHandler) JobKind() string { return string(handler) }
func (kindHandler) Handle(context.Context, outbound.UnitOfWork, outbound.ClaimedJob) error {
return nil
}
func TestBuildJobWorkerSkipsWithoutWork(t *testing.T) {
disabled := consumerTestConfig(t)
disabled.JobsEnabled = false
noDatabase := consumerTestConfig(t)
noDatabase.DatabaseURL = ""
tests := []struct {
name string
settings config.Config
handlers []inbound.JobHandler
log string
}{
{name: "disabled", settings: disabled, handlers: []inbound.JobHandler{kindHandler("test.deadline")}, log: "scheduled job worker is disabled"},
{name: "no handler registered", settings: consumerTestConfig(t), log: "no scheduled job kind is registered"},
{name: "database not configured", settings: noDatabase, handlers: []inbound.JobHandler{kindHandler("test.deadline")}, log: "DATABASE_URL is not set"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var logs strings.Builder
logger := slog.New(slog.NewTextHandler(&logs, nil))
worker, cleanup, err := buildJobWorker(t.Context(), test.settings, logger, prometheus.New(), test.handlers)
if err != nil {
t.Fatalf("buildJobWorker() error = %v", err)
}
cleanup()
if worker != nil {
t.Fatal("buildJobWorker() built a worker without work to do")
}
if !strings.Contains(logs.String(), test.log) {
t.Fatalf("logs = %q, want %q", logs.String(), test.log)
}
})
}
}
func TestBootstrapRegistersNoJobKindYet(t *testing.T) {
if handlers := jobHandlers(); len(handlers) != 0 {
t.Fatalf("jobHandlers() = %v; update the documentation when the registered job kinds change", handlers)
}
}
func TestBuildJobWorkerRefusesADuplicateKind(t *testing.T) {
_, _, err := buildJobWorker(t.Context(), consumerTestConfig(t), slog.New(slog.DiscardHandler), prometheus.New(),
[]inbound.JobHandler{kindHandler("test.deadline"), kindHandler("test.deadline")})
if err == nil {
t.Fatal("buildJobWorker() accepted a kind registered twice")
}
}
// TestApplicationRunsAndStopsTheJobWorker starts the worker against a
// database that does not answer: it keeps retrying in the background, and
// the application still stops within its shutdown budget.
func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) {
settings := consumerTestConfig(t)
settings.HTTPAddr = "127.0.0.1:0"
settings.MetricsAddr = "127.0.0.1:0"
settings.ShutdownTimeout = time.Second
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
worker, cleanup, err := buildJobWorker(t.Context(), settings, logger, metrics, []inbound.JobHandler{kindHandler("test.deadline")})
if err != nil {
t.Fatalf("buildJobWorker() error = %v", err)
}
defer cleanup()
if worker == nil {
t.Fatal("buildJobWorker() built no worker for a registered kind")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
time.Sleep(50 * time.Millisecond)
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -49,6 +49,7 @@ func initialize(
httpadapter.NewRouter,
newOutboxRelay,
newEventConsumers,
newJobWorker,
NewApplication,
),
)
+11 -1
View File
@@ -70,8 +70,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers)
worker, cleanup6, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker)
return application, func() {
cleanup6()
cleanup5()
cleanup4()
cleanup3()