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

+20 -2
View File
@@ -77,6 +77,18 @@ type Config struct {
// ConsumerRebalanceTimeout is the Kafka rebalance timeout of every
// consumer group member.
ConsumerRebalanceTimeout time.Duration
// JobsEnabled runs the scheduled job worker next to the HTTP servers
// when a job handler is registered.
JobsEnabled bool
JobsPollInterval time.Duration
JobsBatchSize int
JobsLeaseDuration time.Duration
// JobsMaxAttempts applies to jobs scheduled without their own limit.
JobsMaxAttempts int
JobsBackoffInitial time.Duration
JobsBackoffMax time.Duration
// JobsShutdownGrace bounds the job in progress after shutdown begins.
JobsShutdownGrace time.Duration
// EmailProvider selects the only active mail transport. Settings of the
// other transports are not loaded.
EmailProvider EmailProvider
@@ -146,6 +158,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadConsumer(lookup); err != nil {
return Config{}, err
}
if err := config.loadJobs(lookup); err != nil {
return Config{}, err
}
if err := config.loadMail(lookup); err != nil {
return Config{}, err
}
@@ -211,11 +226,14 @@ func (config Config) Validate() error {
if config.ShutdownTimeout <= 0 {
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
}
// The consumer shutdown grace is checked against SHUTDOWN_TIMEOUT, so it
// follows that check.
// The consumer and job shutdown graces are checked against
// SHUTDOWN_TIMEOUT, so they follow that check.
if err := config.ValidateConsumer(); err != nil {
return err
}
if err := config.ValidateJobs(); err != nil {
return err
}
switch config.LogLevel {
case "debug", "info", "warn", "error":
default:
+99
View File
@@ -0,0 +1,99 @@
package config
import (
"errors"
"fmt"
"time"
)
const (
// The scheduled job worker runs by default. It starts only when a job
// handler is registered and DATABASE_URL is set.
defaultJobsEnabled = true
// defaultJobsPollInterval is the wait after a pass that claimed less
// than a batch. It is also the usual lateness of a job after its due
// time.
defaultJobsPollInterval = time.Second
minJobsPollInterval = 10 * time.Millisecond
maxJobsPollInterval = 5 * time.Minute
// defaultJobsBatchSize bounds the jobs one claim leases. A worker runs
// them one after another under leases taken together, so a batch stays
// small next to the lease.
defaultJobsBatchSize = 10
maxJobsBatchSize = 100
// defaultJobsLeaseDuration is how long a claimed job belongs to one
// worker. It bounds one handler attempt, and a worker that crashed
// delays its jobs by at most this long.
defaultJobsLeaseDuration = time.Minute
minJobsLeaseDuration = time.Second
maxJobsLeaseDuration = time.Hour
// defaultJobsMaxAttempts bounds the attempts of a job scheduled without
// its own limit before it is dead.
defaultJobsMaxAttempts = 5
// maxJobsMaxAttempts matches the database bound on a per-job limit.
maxJobsMaxAttempts = 100
// A failed job is retried after a delay that starts at the initial
// value, doubles per failed attempt, and stops growing at the maximum.
defaultJobsBackoffInitial = time.Second
defaultJobsBackoffMax = 5 * time.Minute
maxJobsBackoff = 24 * time.Hour
// defaultJobsShutdownGrace is how long the job in progress may continue
// after shutdown begins.
defaultJobsShutdownGrace = 5 * time.Second
)
func (config *Config) loadJobs(lookup LookupEnv) error {
var err error
if config.JobsEnabled, err = boolOrDefault(lookup, "JOBS_ENABLED", defaultJobsEnabled); err != nil {
return err
}
if config.JobsPollInterval, err = durationOrDefault(lookup, "JOBS_POLL_INTERVAL", defaultJobsPollInterval); err != nil {
return err
}
if config.JobsBatchSize, err = intOrDefault(lookup, "JOBS_BATCH_SIZE", defaultJobsBatchSize); err != nil {
return err
}
if config.JobsLeaseDuration, err = durationOrDefault(lookup, "JOBS_LEASE_DURATION", defaultJobsLeaseDuration); err != nil {
return err
}
if config.JobsMaxAttempts, err = intOrDefault(lookup, "JOBS_MAX_ATTEMPTS", defaultJobsMaxAttempts); err != nil {
return err
}
if config.JobsBackoffInitial, err = durationOrDefault(lookup, "JOBS_BACKOFF_INITIAL", defaultJobsBackoffInitial); err != nil {
return err
}
if config.JobsBackoffMax, err = durationOrDefault(lookup, "JOBS_BACKOFF_MAX", defaultJobsBackoffMax); err != nil {
return err
}
config.JobsShutdownGrace, err = durationOrDefault(lookup, "JOBS_SHUTDOWN_GRACE", defaultJobsShutdownGrace)
return err
}
// ValidateJobs checks the scheduled job settings even when the worker is
// disabled, so enabling it later cannot surface an old mistake.
func (config Config) ValidateJobs() error {
if config.JobsPollInterval < minJobsPollInterval || config.JobsPollInterval > maxJobsPollInterval {
return fmt.Errorf("Config.ValidateJobs - JOBS_POLL_INTERVAL must be between %s and %s", minJobsPollInterval, maxJobsPollInterval)
}
if config.JobsBatchSize < 1 || config.JobsBatchSize > maxJobsBatchSize {
return fmt.Errorf("Config.ValidateJobs - JOBS_BATCH_SIZE must be between 1 and %d", maxJobsBatchSize)
}
if config.JobsLeaseDuration < minJobsLeaseDuration || config.JobsLeaseDuration > maxJobsLeaseDuration {
return fmt.Errorf("Config.ValidateJobs - JOBS_LEASE_DURATION must be between %s and %s", minJobsLeaseDuration, maxJobsLeaseDuration)
}
if config.JobsMaxAttempts < 1 || config.JobsMaxAttempts > maxJobsMaxAttempts {
return fmt.Errorf("Config.ValidateJobs - JOBS_MAX_ATTEMPTS must be between 1 and %d", maxJobsMaxAttempts)
}
if config.JobsBackoffInitial <= 0 {
return errors.New("Config.ValidateJobs - JOBS_BACKOFF_INITIAL must be positive")
}
if config.JobsBackoffMax < config.JobsBackoffInitial || config.JobsBackoffMax > maxJobsBackoff {
return fmt.Errorf("Config.ValidateJobs - JOBS_BACKOFF_MAX must be between JOBS_BACKOFF_INITIAL and %s", maxJobsBackoff)
}
// The grace runs while the HTTP servers drain, so it must fit in the
// shutdown budget of the process.
if config.JobsShutdownGrace <= 0 || config.JobsShutdownGrace > config.ShutdownTimeout {
return errors.New("Config.ValidateJobs - JOBS_SHUTDOWN_GRACE must be positive and at most SHUTDOWN_TIMEOUT")
}
return nil
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvJobsDefaults(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(nil))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if !settings.JobsEnabled || settings.JobsPollInterval != time.Second || settings.JobsBatchSize != 10 ||
settings.JobsLeaseDuration != time.Minute || settings.JobsMaxAttempts != 5 ||
settings.JobsBackoffInitial != time.Second || settings.JobsBackoffMax != 5*time.Minute ||
settings.JobsShutdownGrace != 5*time.Second {
t.Fatalf("unexpected job defaults: %+v", jobSettings(settings))
}
}
func TestLoadFromEnvReadsJobSettings(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"JOBS_ENABLED": " FALSE ",
"JOBS_POLL_INTERVAL": "10ms",
"JOBS_BATCH_SIZE": " 100 ",
"JOBS_LEASE_DURATION": "1h",
"JOBS_MAX_ATTEMPTS": "100",
"JOBS_BACKOFF_INITIAL": "2s",
"JOBS_BACKOFF_MAX": "24h",
"JOBS_SHUTDOWN_GRACE": "20s",
"SHUTDOWN_TIMEOUT": "20s",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.JobsEnabled || settings.JobsPollInterval != 10*time.Millisecond || settings.JobsBatchSize != 100 ||
settings.JobsLeaseDuration != time.Hour || settings.JobsMaxAttempts != 100 ||
settings.JobsBackoffInitial != 2*time.Second || settings.JobsBackoffMax != 24*time.Hour ||
settings.JobsShutdownGrace != 20*time.Second {
t.Fatalf("job settings were not loaded: %+v", jobSettings(settings))
}
}
func TestLoadFromEnvRejectsJobSettings(t *testing.T) {
tests := []struct {
key, value, want string
}{
{key: "JOBS_ENABLED", value: "yes", want: "config.boolOrDefault - JOBS_ENABLED"},
{key: "JOBS_POLL_INTERVAL", value: "soon", want: "config.durationOrDefault - parse JOBS_POLL_INTERVAL"},
{key: "JOBS_POLL_INTERVAL", value: "9ms", want: "Config.ValidateJobs - JOBS_POLL_INTERVAL"},
{key: "JOBS_POLL_INTERVAL", value: "6m", want: "Config.ValidateJobs - JOBS_POLL_INTERVAL"},
{key: "JOBS_BATCH_SIZE", value: "", want: "config.intOrDefault - JOBS_BATCH_SIZE"},
{key: "JOBS_BATCH_SIZE", value: "0", want: "Config.ValidateJobs - JOBS_BATCH_SIZE"},
{key: "JOBS_BATCH_SIZE", value: "101", want: "Config.ValidateJobs - JOBS_BATCH_SIZE"},
{key: "JOBS_LEASE_DURATION", value: "999ms", want: "Config.ValidateJobs - JOBS_LEASE_DURATION"},
{key: "JOBS_LEASE_DURATION", value: "61m", want: "Config.ValidateJobs - JOBS_LEASE_DURATION"},
{key: "JOBS_MAX_ATTEMPTS", value: "many", want: "config.intOrDefault - JOBS_MAX_ATTEMPTS"},
{key: "JOBS_MAX_ATTEMPTS", value: "0", want: "Config.ValidateJobs - JOBS_MAX_ATTEMPTS"},
{key: "JOBS_MAX_ATTEMPTS", value: "101", want: "Config.ValidateJobs - JOBS_MAX_ATTEMPTS"},
{key: "JOBS_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateJobs - JOBS_BACKOFF_INITIAL"},
{key: "JOBS_BACKOFF_INITIAL", value: "6m", want: "Config.ValidateJobs - JOBS_BACKOFF_MAX"},
{key: "JOBS_BACKOFF_MAX", value: "25h", want: "Config.ValidateJobs - JOBS_BACKOFF_MAX"},
{key: "JOBS_SHUTDOWN_GRACE", value: "0s", want: "Config.ValidateJobs - JOBS_SHUTDOWN_GRACE"},
// Longer than the default SHUTDOWN_TIMEOUT of 10s.
{key: "JOBS_SHUTDOWN_GRACE", value: "11s", want: "Config.ValidateJobs - JOBS_SHUTDOWN_GRACE"},
}
for _, test := range tests {
t.Run(test.key+"/"+test.value, func(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want)
}
})
}
}
func TestValidateJobsChecksSettingsEvenWhenDisabled(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"JOBS_ENABLED": "false"}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
settings.JobsBatchSize = 0
if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateJobs - JOBS_BATCH_SIZE") {
t.Fatalf("Validate() error = %v, want the job batch size error", err)
}
}
// jobSettings collects the job fields for failure messages.
func jobSettings(settings Config) map[string]any {
return map[string]any{
"enabled": settings.JobsEnabled,
"poll_interval": settings.JobsPollInterval,
"batch_size": settings.JobsBatchSize,
"lease": settings.JobsLeaseDuration,
"max_attempts": settings.JobsMaxAttempts,
"backoff_initial": settings.JobsBackoffInitial,
"backoff_max": settings.JobsBackoffMax,
"shutdown_grace": settings.JobsShutdownGrace,
}
}