feat(jobs): add durable due-time job runner with leases
This commit is contained in:
1 parent
7e80c8ad2a
commit
008254e44a
39 files changed
+4909
-43
No files matched your search
@@ -0,0 +1,581 @@
|
||||
// Package jobrunner runs durable scheduled jobs when they fall due. Jobs are
|
||||
// claimed under a lease, so they survive restarts and crashes, and each
|
||||
// handler runs in the transaction that completes its job, so a
|
||||
// database-only effect happens once even when several workers race.
|
||||
package jobrunner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
)
|
||||
|
||||
// Job outcome label values. Every claimed job ends a pass with exactly one.
|
||||
const (
|
||||
// OutcomeDone: the handler's effect and the completion committed.
|
||||
OutcomeDone = "done"
|
||||
// OutcomeRetry: the attempt failed and the job waits for its retry.
|
||||
OutcomeRetry = "retry"
|
||||
// OutcomeDead: the job failed finally and needs an operator.
|
||||
OutcomeDead = "dead"
|
||||
// OutcomeLeaseLost: the job was canceled or reclaimed by another worker
|
||||
// before this attempt could finish; nothing of the attempt committed.
|
||||
OutcomeLeaseLost = "lease_lost"
|
||||
// OutcomeReleased: the worker gave the job back unfinished, at shutdown
|
||||
// or after a database failure outside the handler, without counting
|
||||
// the attempt.
|
||||
OutcomeReleased = "released"
|
||||
)
|
||||
|
||||
// Outcomes lists every outcome label value, for metrics that expose the
|
||||
// series at zero.
|
||||
var Outcomes = []string{OutcomeDone, OutcomeRetry, OutcomeDead, OutcomeLeaseLost, OutcomeReleased}
|
||||
|
||||
// maxReasonLength bounds the logged failure reason.
|
||||
const maxReasonLength = 256
|
||||
|
||||
// errHandlerPanic replaces the value of a handler panic, which could quote
|
||||
// the payload.
|
||||
var errHandlerPanic = errors.New("handler panicked")
|
||||
|
||||
// Metrics records job outcomes and the backlog. Labels are kinds, which the
|
||||
// code defines, and the outcome constants of this package.
|
||||
type Metrics interface {
|
||||
// PrepareScheduledJobKind exposes the series of kind at zero, so an
|
||||
// alert on the first dead job sees an increase instead of a new series.
|
||||
PrepareScheduledJobKind(kind string)
|
||||
ObserveScheduledJob(kind, outcome string)
|
||||
ObserveScheduledJobBacklog(backlog outbound.JobBacklog)
|
||||
}
|
||||
|
||||
// Settings are the named worker limits; config validates their ranges.
|
||||
type Settings struct {
|
||||
// BatchSize bounds the jobs of one claim. The jobs of a batch run one
|
||||
// after another under leases taken together, so the batch should finish
|
||||
// well within one lease.
|
||||
BatchSize int
|
||||
// PollInterval is the wait after a pass that claimed less than a batch.
|
||||
PollInterval time.Duration
|
||||
// Lease is how long a claimed job belongs to this worker. It also bounds
|
||||
// one handler attempt.
|
||||
Lease time.Duration
|
||||
// MaxAttempts bounds the attempts of jobs scheduled without their own
|
||||
// limit.
|
||||
MaxAttempts int
|
||||
// Backoff is the wait before a failed job is retried and after a pass
|
||||
// that failed in the database.
|
||||
Backoff retry.Backoff
|
||||
// ShutdownGrace is how long a job in progress may continue after Run's
|
||||
// context ends. When it expires the attempt is canceled, its
|
||||
// transaction rolls back, and the job is released.
|
||||
ShutdownGrace time.Duration
|
||||
// StoreTimeout bounds one claim, failure record, release, or backlog
|
||||
// read.
|
||||
StoreTimeout time.Duration
|
||||
// BacklogInterval is the least time between two backlog reads for the
|
||||
// metrics.
|
||||
BacklogInterval time.Duration
|
||||
}
|
||||
|
||||
func (settings Settings) validate() error {
|
||||
if settings.BatchSize < 1 || settings.MaxAttempts < 1 || settings.MaxAttempts > domain.MaxScheduledJobAttempts {
|
||||
return fmt.Errorf("jobrunner.New - batch size must be positive and max attempts between 1 and %d", domain.MaxScheduledJobAttempts)
|
||||
}
|
||||
if settings.PollInterval <= 0 || settings.Lease <= 0 || settings.ShutdownGrace <= 0 ||
|
||||
settings.StoreTimeout <= 0 || settings.BacklogInterval <= 0 {
|
||||
return errors.New("jobrunner.New - intervals, lease, grace, and timeouts must be positive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Worker claims due jobs of its registered kinds and runs their handlers.
|
||||
// Several workers may run against one database, in one process or many.
|
||||
type Worker struct {
|
||||
owner uuid.UUID
|
||||
handlers map[string]inbound.JobHandler
|
||||
kinds []string
|
||||
store outbound.JobStore
|
||||
metrics Metrics
|
||||
logger *slog.Logger
|
||||
settings Settings
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// New builds a worker for handlers, one per kind. clock is the application
|
||||
// clock: every due and lease decision uses it, so tests move time with a
|
||||
// fake one. Each worker gets a random lease owner ID.
|
||||
func New(
|
||||
handlers []inbound.JobHandler,
|
||||
store outbound.JobStore,
|
||||
metrics Metrics,
|
||||
logger *slog.Logger,
|
||||
settings Settings,
|
||||
clock func() time.Time,
|
||||
) (*Worker, error) {
|
||||
if len(handlers) == 0 {
|
||||
return nil, errors.New("jobrunner.New - at least one handler is required")
|
||||
}
|
||||
if err := settings.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
registry := make(map[string]inbound.JobHandler, len(handlers))
|
||||
for _, handler := range handlers {
|
||||
kind := handler.JobKind()
|
||||
if err := domain.ValidateScheduledJobKind(kind); err != nil {
|
||||
return nil, fmt.Errorf("jobrunner.New - handler kind: %w", err)
|
||||
}
|
||||
if _, exists := registry[kind]; exists {
|
||||
return nil, fmt.Errorf("jobrunner.New - kind %s is registered twice", kind)
|
||||
}
|
||||
registry[kind] = handler
|
||||
}
|
||||
kinds := slices.Sorted(maps.Keys(registry))
|
||||
for _, kind := range kinds {
|
||||
metrics.PrepareScheduledJobKind(kind)
|
||||
}
|
||||
owner := uuid.New()
|
||||
return &Worker{
|
||||
owner: owner,
|
||||
handlers: registry,
|
||||
kinds: kinds,
|
||||
store: store,
|
||||
metrics: metrics,
|
||||
logger: logger.With(slog.String("lease_owner", owner.String())),
|
||||
settings: settings,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Kinds returns the registered kinds in name order.
|
||||
func (worker *Worker) Kinds() []string {
|
||||
return slices.Clone(worker.kinds)
|
||||
}
|
||||
|
||||
// PassResult counts the claimed jobs of one pass by outcome.
|
||||
type PassResult struct {
|
||||
Claimed int
|
||||
Done int
|
||||
Retried int
|
||||
Dead int
|
||||
LeaseLost int
|
||||
Released int
|
||||
}
|
||||
|
||||
func (result *PassResult) add(outcome string) {
|
||||
switch outcome {
|
||||
case OutcomeDone:
|
||||
result.Done++
|
||||
case OutcomeRetry:
|
||||
result.Retried++
|
||||
case OutcomeDead:
|
||||
result.Dead++
|
||||
case OutcomeLeaseLost:
|
||||
result.LeaseLost++
|
||||
case OutcomeReleased:
|
||||
result.Released++
|
||||
}
|
||||
}
|
||||
|
||||
// RunDue runs one pass: it claims the jobs due at the clock's now and runs
|
||||
// them in due order. Tests and harnesses call it to run due jobs
|
||||
// deterministically; Run repeats it. An error reports a database failure
|
||||
// outside the handlers; the jobs it left unfinished are released or wait for
|
||||
// their leases to expire.
|
||||
func (worker *Worker) RunDue(ctx context.Context) (PassResult, error) {
|
||||
return worker.runPass(ctx, ctx)
|
||||
}
|
||||
|
||||
// Run claims and runs due jobs until ctx ends. A pass that claimed a full
|
||||
// batch is followed immediately by the next one; otherwise the worker waits
|
||||
// PollInterval, and after a database failure Backoff, which grows across
|
||||
// consecutive failures. Run stops claiming when ctx ends, lets the job in
|
||||
// progress continue for ShutdownGrace, releases the claimed jobs it did not
|
||||
// finish, and returns.
|
||||
func (worker *Worker) Run(ctx context.Context) {
|
||||
workCtx, stopWork := worker.workContext(ctx)
|
||||
defer stopWork()
|
||||
worker.logger.Info("scheduled job worker started",
|
||||
slog.Any("kinds", worker.kinds),
|
||||
slog.Int("batch_size", worker.settings.BatchSize),
|
||||
slog.Duration("poll_interval", worker.settings.PollInterval),
|
||||
slog.Duration("lease", worker.settings.Lease),
|
||||
)
|
||||
defer worker.logger.Info("scheduled job worker stopped")
|
||||
|
||||
backlog := backlogRefresher{worker: worker}
|
||||
failures := 0
|
||||
for ctx.Err() == nil {
|
||||
result, err := worker.runPass(ctx, workCtx)
|
||||
backlog.refresh(ctx)
|
||||
var delay time.Duration
|
||||
switch {
|
||||
case err != nil && ctx.Err() == nil:
|
||||
failures++
|
||||
delay = worker.settings.Backoff.Delay(failures)
|
||||
worker.logger.Warn("scheduled job pass failed in the database; unfinished jobs are released or wait for their leases",
|
||||
slog.Int("claimed", result.Claimed),
|
||||
slog.Int("consecutive_failures", failures),
|
||||
slog.Duration("retry_in", delay),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
case result.Claimed >= worker.settings.BatchSize:
|
||||
failures = 0
|
||||
default:
|
||||
failures = 0
|
||||
delay = worker.settings.PollInterval
|
||||
}
|
||||
if !retry.Wait(ctx, delay) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runPass claims with ctx, so no claim starts after shutdown began, and
|
||||
// runs handlers with workCtx, which outlives ctx by the shutdown grace.
|
||||
func (worker *Worker) runPass(ctx, workCtx context.Context) (PassResult, error) {
|
||||
var result PassResult
|
||||
claimCtx, cancel := context.WithTimeout(ctx, worker.settings.StoreTimeout)
|
||||
jobs, err := worker.store.Claim(claimCtx, outbound.JobClaim{
|
||||
Owner: worker.owner,
|
||||
Kinds: worker.kinds,
|
||||
Now: worker.clock(),
|
||||
Lease: worker.settings.Lease,
|
||||
Limit: worker.settings.BatchSize,
|
||||
DefaultMaxAttempts: worker.settings.MaxAttempts,
|
||||
})
|
||||
cancel()
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("Worker.runPass - claim jobs: %w", err)
|
||||
}
|
||||
result.Claimed = len(jobs)
|
||||
for index, job := range jobs {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// Jobs claimed but not started go back at once, so a deadline
|
||||
// does not wait for the lease to expire.
|
||||
worker.release(ctx, jobs[index:], &result)
|
||||
return result, nil
|
||||
default:
|
||||
}
|
||||
outcome, storeErr := worker.process(ctx, workCtx, job)
|
||||
if outcome != "" {
|
||||
result.add(outcome)
|
||||
}
|
||||
if storeErr != nil {
|
||||
worker.release(ctx, jobs[index+1:], &result)
|
||||
return result, storeErr
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// process runs one job and returns its outcome. storeErr reports a database
|
||||
// failure outside the handler, after which the pass stops.
|
||||
func (worker *Worker) process(ctx, workCtx context.Context, job outbound.ClaimedJob) (outcome string, storeErr error) {
|
||||
logger := worker.logger.With(jobAttributes(job)...)
|
||||
if job.Exhausted {
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeDead)
|
||||
logger.Error("scheduled job is dead: its last allowed attempt stopped without finishing; it needs an operator",
|
||||
slog.String("error_class", string(outbound.JobErrorLeaseExpired)))
|
||||
return OutcomeDead, nil
|
||||
}
|
||||
handler, registered := worker.handlers[job.Kind]
|
||||
if !registered {
|
||||
return worker.releaseOne(ctx, job), nil
|
||||
}
|
||||
// The jobs of a batch share the lease of their claim, so each one renews
|
||||
// it right before it starts. A job whose turn came after that lease
|
||||
// expired is not started: it goes back without using up an attempt, or
|
||||
// stays with the worker that already took it over.
|
||||
startCtx, cancelStart := context.WithTimeout(ctx, worker.settings.StoreTimeout)
|
||||
started, ok, err := worker.store.Start(startCtx, job, worker.clock(), worker.settings.Lease)
|
||||
cancelStart()
|
||||
if err != nil {
|
||||
return worker.releaseOne(ctx, job), fmt.Errorf("Worker.process - start job: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
logger.Info("scheduled job lease expired or was taken over before its turn; not started")
|
||||
return worker.releaseOne(ctx, job), nil
|
||||
}
|
||||
job = started
|
||||
|
||||
runCtx, cancel := context.WithTimeout(workCtx, job.LeaseExpiresAt.Sub(worker.clock()))
|
||||
defer cancel()
|
||||
handlerFailed := false
|
||||
err = worker.store.Run(runCtx, job, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
err := worker.callHandler(ctx, unit, handler, job, logger)
|
||||
handlerFailed = err != nil
|
||||
return err
|
||||
})
|
||||
timedOut := errors.Is(runCtx.Err(), context.DeadlineExceeded) && workCtx.Err() == nil
|
||||
switch {
|
||||
case err == nil:
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeDone)
|
||||
logger.Debug("scheduled job done")
|
||||
return OutcomeDone, nil
|
||||
case errors.Is(err, outbound.ErrJobLeaseLost):
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeLeaseLost)
|
||||
logger.Info("scheduled job was canceled or reclaimed before this attempt ran; skipped")
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
class, attributable := failureClass(err, handlerFailed, timedOut)
|
||||
switch {
|
||||
case attributable && finalClass(class):
|
||||
// A final failure is the job's own, also while stopping.
|
||||
return worker.fail(ctx, job, class, err, logger)
|
||||
case ctx.Err() != nil:
|
||||
// Any other failure while stopping may be the shutdown itself, so
|
||||
// it is not counted; the job is released and runs again later.
|
||||
return worker.releaseOne(ctx, job), nil
|
||||
case attributable:
|
||||
return worker.fail(ctx, job, class, err, logger)
|
||||
default:
|
||||
return worker.releaseOne(ctx, job), fmt.Errorf("Worker.process - run job: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// finalClass reports a class that ends the job at once: a retry cannot
|
||||
// change the outcome.
|
||||
func finalClass(class outbound.JobErrorClass) bool {
|
||||
switch class {
|
||||
case outbound.JobErrorHandlerPanic, outbound.JobErrorHandlerRejected, outbound.JobErrorCompletionConflict:
|
||||
return true
|
||||
case outbound.JobErrorHandlerFailed, outbound.JobErrorTimeout, outbound.JobErrorConflict,
|
||||
outbound.JobErrorEffectRejected, outbound.JobErrorLeaseExpired:
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// failureClass maps an attempt error to its class. attributable is false
|
||||
// for a database failure that the job did not cause.
|
||||
func failureClass(err error, handlerFailed, timedOut bool) (outbound.JobErrorClass, bool) {
|
||||
switch {
|
||||
case errors.Is(err, errHandlerPanic):
|
||||
return outbound.JobErrorHandlerPanic, true
|
||||
case errors.Is(err, inbound.ErrJobRejected):
|
||||
return outbound.JobErrorHandlerRejected, true
|
||||
case errors.Is(err, outbound.ErrJobCompletionConflict):
|
||||
return outbound.JobErrorCompletionConflict, true
|
||||
case timedOut:
|
||||
return outbound.JobErrorTimeout, true
|
||||
case errors.Is(err, outbound.ErrTransactionConflict):
|
||||
return outbound.JobErrorConflict, true
|
||||
case errors.Is(err, outbound.ErrJobEffectRejected):
|
||||
return outbound.JobErrorEffectRejected, true
|
||||
case handlerFailed:
|
||||
return outbound.JobErrorHandlerFailed, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// fail records a failed attempt: the job is retried after Backoff, or dead
|
||||
// when the class is final or the attempts ran out.
|
||||
func (worker *Worker) fail(
|
||||
ctx context.Context,
|
||||
job outbound.ClaimedJob,
|
||||
class outbound.JobErrorClass,
|
||||
cause error,
|
||||
logger *slog.Logger,
|
||||
) (string, error) {
|
||||
final := finalClass(class) || job.Attempt >= job.MaxAttempts
|
||||
delay := worker.settings.Backoff.Delay(job.Attempt)
|
||||
failure := outbound.JobFailure{Class: class, Dead: final, RetryAt: worker.clock().Add(delay)}
|
||||
// The record is written after shutdown began too, so a failure is not
|
||||
// lost to a restart.
|
||||
recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), worker.settings.StoreTimeout)
|
||||
defer cancel()
|
||||
recorded, err := worker.store.Fail(recordCtx, job, failure)
|
||||
if err != nil {
|
||||
logger.Warn("scheduled job failed and the failure could not be stored; the job runs again after its lease expires",
|
||||
slog.String("error_class", string(class)),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
return "", fmt.Errorf("Worker.fail - record failure: %w", err)
|
||||
}
|
||||
if !recorded {
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeLeaseLost)
|
||||
logger.Info("scheduled job failed after it was canceled or reclaimed; nothing recorded")
|
||||
return OutcomeLeaseLost, nil
|
||||
}
|
||||
reason := sanitizeReason(cause)
|
||||
if final {
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeDead)
|
||||
logger.Error("scheduled job is dead; it needs an operator",
|
||||
slog.String("error_class", string(class)),
|
||||
slog.String("reason", reason),
|
||||
)
|
||||
return OutcomeDead, nil
|
||||
}
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, OutcomeRetry)
|
||||
logger.Warn("scheduled job failed; retrying",
|
||||
slog.String("error_class", string(class)),
|
||||
slog.Duration("retry_in", delay),
|
||||
slog.String("reason", reason),
|
||||
)
|
||||
return OutcomeRetry, nil
|
||||
}
|
||||
|
||||
// releaseOne releases job and returns its outcome: OutcomeReleased,
|
||||
// OutcomeLeaseLost when another worker or a cancel took it over meanwhile,
|
||||
// or no outcome when the release failed and the job waits for its lease to
|
||||
// expire.
|
||||
func (worker *Worker) releaseOne(ctx context.Context, job outbound.ClaimedJob) string {
|
||||
var result PassResult
|
||||
worker.release(ctx, []outbound.ClaimedJob{job}, &result)
|
||||
switch {
|
||||
case result.Released > 0:
|
||||
return OutcomeReleased
|
||||
case result.LeaseLost > 0:
|
||||
return OutcomeLeaseLost
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// release gives unfinished jobs back and adds their outcomes to result: a
|
||||
// job the guard skipped was taken over by another worker or canceled, so it
|
||||
// counts as lost. A failed release is only logged: the leases expire and
|
||||
// another claim takes the jobs then.
|
||||
func (worker *Worker) release(ctx context.Context, jobs []outbound.ClaimedJob, result *PassResult) {
|
||||
held := make([]outbound.ClaimedJob, 0, len(jobs))
|
||||
for _, job := range jobs {
|
||||
if !job.Exhausted {
|
||||
held = append(held, job)
|
||||
}
|
||||
}
|
||||
if len(held) == 0 {
|
||||
return
|
||||
}
|
||||
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), worker.settings.StoreTimeout)
|
||||
defer cancel()
|
||||
released, err := worker.store.Release(releaseCtx, held)
|
||||
if err != nil {
|
||||
worker.logger.Warn("scheduled jobs could not be released; they run again after their leases expire",
|
||||
slog.Int("jobs", len(held)),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
return
|
||||
}
|
||||
for _, job := range held {
|
||||
outcome := OutcomeLeaseLost
|
||||
if slices.Contains(released, job.ID) {
|
||||
outcome = OutcomeReleased
|
||||
}
|
||||
worker.metrics.ObserveScheduledJob(job.Kind, outcome)
|
||||
result.add(outcome)
|
||||
}
|
||||
worker.logger.Info("scheduled jobs released unfinished",
|
||||
slog.Int("jobs", len(held)),
|
||||
slog.Int("released", len(released)),
|
||||
)
|
||||
}
|
||||
|
||||
// callHandler turns a panic into a final failure, so one job cannot crash
|
||||
// the process on every attempt. The stack is logged; the panic value is
|
||||
// not, because it could quote the payload.
|
||||
func (worker *Worker) callHandler(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
handler inbound.JobHandler,
|
||||
job outbound.ClaimedJob,
|
||||
logger *slog.Logger,
|
||||
) (err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
logger.Error("scheduled job handler panicked", slog.String("stack", string(debug.Stack())))
|
||||
err = errHandlerPanic
|
||||
}
|
||||
}()
|
||||
return handler.Handle(ctx, unit, job)
|
||||
}
|
||||
|
||||
// workContext returns a context for handler attempts that outlives ctx by at
|
||||
// most ShutdownGrace. stop releases the watcher goroutine.
|
||||
func (worker *Worker) workContext(ctx context.Context) (context.Context, func()) {
|
||||
workCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
stopWatching := context.AfterFunc(ctx, func() {
|
||||
timer := time.NewTimer(worker.settings.ShutdownGrace)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
cancel()
|
||||
case <-workCtx.Done():
|
||||
}
|
||||
})
|
||||
return workCtx, func() {
|
||||
stopWatching()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// backlogRefresher reads the job backlog for the metrics at most once per
|
||||
// BacklogInterval of real time; the due comparison uses the worker clock.
|
||||
type backlogRefresher struct {
|
||||
worker *Worker
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (refresher *backlogRefresher) refresh(ctx context.Context) {
|
||||
settings := refresher.worker.settings
|
||||
if !refresher.last.IsZero() && time.Since(refresher.last) < settings.BacklogInterval {
|
||||
return
|
||||
}
|
||||
refresher.last = time.Now()
|
||||
readCtx, cancel := context.WithTimeout(ctx, settings.StoreTimeout)
|
||||
defer cancel()
|
||||
backlog, err := refresher.worker.store.Backlog(readCtx, refresher.worker.clock())
|
||||
if err != nil {
|
||||
// A read interrupted by shutdown is not worth a warning.
|
||||
if ctx.Err() == nil {
|
||||
refresher.worker.logger.Warn("scheduled job worker could not read the backlog; its metrics are stale", slog.Any("error", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
refresher.worker.metrics.ObserveScheduledJobBacklog(backlog)
|
||||
}
|
||||
|
||||
// jobAttributes identifies a job in logs without its key or payload.
|
||||
func jobAttributes(job outbound.ClaimedJob) []any {
|
||||
return []any{
|
||||
slog.Int64("job_id", job.ID),
|
||||
slog.String("kind", job.Kind),
|
||||
slog.Int("attempt", job.Attempt),
|
||||
slog.Int("max_attempts", job.MaxAttempts),
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeReason keeps a short single-line cause. Handler errors must not
|
||||
// carry personal data already; this also bounds what a mistake can expose.
|
||||
func sanitizeReason(err error) string {
|
||||
reason := strings.Map(func(character rune) rune {
|
||||
if unicode.IsControl(character) || !unicode.IsPrint(character) {
|
||||
return ' '
|
||||
}
|
||||
return character
|
||||
}, err.Error())
|
||||
reason = strings.TrimSpace(reason)
|
||||
if runes := []rune(reason); len(runes) > maxReasonLength {
|
||||
reason = string(runes[:maxReasonLength])
|
||||
}
|
||||
if reason == "" {
|
||||
return "unspecified failure"
|
||||
}
|
||||
return reason
|
||||
}
|
||||
@@ -0,0 +1,846 @@
|
||||
package jobrunner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
"lincodex/backend/pkg/testutil"
|
||||
)
|
||||
|
||||
const (
|
||||
testKind = "test.effect"
|
||||
otherKind = "test.other"
|
||||
// testLease is real time only where a test lets a handler run out of
|
||||
// its lease; the fake clock decides every due and lease comparison.
|
||||
testLease = time.Minute
|
||||
testBackoff = time.Second
|
||||
// testWait bounds every wait for a goroutine in these tests.
|
||||
testWait = 5 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
testStart = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
|
||||
errStoreDown = errors.New("store unavailable")
|
||||
errEffectFail = errors.New("effect failed")
|
||||
)
|
||||
|
||||
// memoryJob mirrors one scheduled_jobs row.
|
||||
type memoryJob struct {
|
||||
id int64
|
||||
kind string
|
||||
key string
|
||||
dueAt time.Time
|
||||
availableAt time.Time
|
||||
status string
|
||||
attempts int
|
||||
maxAttempts int
|
||||
leaseOwner uuid.UUID
|
||||
leaseExpiresAt time.Time
|
||||
started bool
|
||||
errorClass outbound.JobErrorClass
|
||||
}
|
||||
|
||||
// memoryStore implements outbound.JobStore with the claim, guard, and
|
||||
// release rules of the PostgreSQL store, so the worker logic is tested
|
||||
// without a database.
|
||||
type memoryStore struct {
|
||||
mu sync.Mutex
|
||||
jobs map[int64]*memoryJob
|
||||
nextID int64
|
||||
effects map[int64]int
|
||||
// locked holds the jobs whose handler runs, as the row lock of the
|
||||
// handler transaction does; claims skip them.
|
||||
locked map[int64]bool
|
||||
claims int
|
||||
// claimErr and runErr fail every claim or every run outside apply.
|
||||
claimErr error
|
||||
runErr error
|
||||
// beforeRun runs inside Run before the guard check, outside the lock.
|
||||
beforeRun func(job outbound.ClaimedJob)
|
||||
}
|
||||
|
||||
func newMemoryStore() *memoryStore {
|
||||
return &memoryStore{jobs: make(map[int64]*memoryJob), effects: make(map[int64]int), locked: make(map[int64]bool)}
|
||||
}
|
||||
|
||||
func (store *memoryStore) schedule(kind string, dueAt time.Time) int64 {
|
||||
return store.scheduleWithLimit(kind, dueAt, 0)
|
||||
}
|
||||
|
||||
func (store *memoryStore) scheduleWithLimit(kind string, dueAt time.Time, maxAttempts int) int64 {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
store.nextID++
|
||||
store.jobs[store.nextID] = &memoryJob{
|
||||
id: store.nextID, kind: kind, key: fmt.Sprint(store.nextID), dueAt: dueAt, availableAt: dueAt,
|
||||
status: "pending", maxAttempts: maxAttempts,
|
||||
}
|
||||
return store.nextID
|
||||
}
|
||||
|
||||
func (store *memoryStore) job(id int64) memoryJob {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return *store.jobs[id]
|
||||
}
|
||||
|
||||
func (store *memoryStore) effectCount(id int64) int {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return store.effects[id]
|
||||
}
|
||||
|
||||
func (store *memoryStore) claimCount() int {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return store.claims
|
||||
}
|
||||
|
||||
func (store *memoryStore) Claim(_ context.Context, claim outbound.JobClaim) ([]outbound.ClaimedJob, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
store.claims++
|
||||
if store.claimErr != nil {
|
||||
return nil, store.claimErr
|
||||
}
|
||||
candidates := make([]*memoryJob, 0, len(store.jobs))
|
||||
for _, job := range store.jobs {
|
||||
waiting := (job.status == "pending" || job.status == "failed") && !job.availableAt.After(claim.Now)
|
||||
expired := job.status == "running" && !job.leaseExpiresAt.After(claim.Now)
|
||||
if slices.Contains(claim.Kinds, job.kind) && (waiting || expired) && !store.locked[job.id] {
|
||||
candidates = append(candidates, job)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(candidates, func(left, right *memoryJob) int { return left.availableAt.Compare(right.availableAt) })
|
||||
candidates = candidates[:min(len(candidates), claim.Limit)]
|
||||
claimed := make([]outbound.ClaimedJob, 0, len(candidates))
|
||||
for _, job := range candidates {
|
||||
maxAttempts := job.maxAttempts
|
||||
if maxAttempts == 0 {
|
||||
maxAttempts = claim.DefaultMaxAttempts
|
||||
}
|
||||
abandoned := job.status == "running" && job.started
|
||||
unstarted := job.status == "running" && !job.started
|
||||
exhausted := abandoned && job.attempts >= maxAttempts
|
||||
if abandoned {
|
||||
job.errorClass = outbound.JobErrorLeaseExpired
|
||||
}
|
||||
result := outbound.ClaimedJob{ID: job.id, Kind: job.kind, Key: job.key, DueAt: job.dueAt, MaxAttempts: maxAttempts, Exhausted: exhausted}
|
||||
job.started = false
|
||||
switch {
|
||||
case exhausted:
|
||||
job.status, job.leaseOwner, job.leaseExpiresAt = "dead", uuid.Nil, time.Time{}
|
||||
default:
|
||||
if !unstarted {
|
||||
job.attempts++
|
||||
}
|
||||
job.status = "running"
|
||||
job.leaseOwner, job.leaseExpiresAt = claim.Owner, claim.Now.Add(claim.Lease)
|
||||
result.LeaseOwner, result.LeaseExpiresAt = job.leaseOwner, job.leaseExpiresAt
|
||||
}
|
||||
result.Attempt = job.attempts
|
||||
claimed = append(claimed, result)
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
// holds reports whether the lease of attempt still holds; mu must be held.
|
||||
func (store *memoryStore) holds(claimed outbound.ClaimedJob) (*memoryJob, bool) {
|
||||
job := store.jobs[claimed.ID]
|
||||
return job, job.status == "running" && job.leaseOwner == claimed.LeaseOwner && job.attempts == claimed.Attempt
|
||||
}
|
||||
|
||||
func (store *memoryStore) Start(_ context.Context, claimed outbound.ClaimedJob, now time.Time, lease time.Duration) (outbound.ClaimedJob, bool, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
job, held := store.holds(claimed)
|
||||
if !held || !job.leaseExpiresAt.After(now) {
|
||||
return outbound.ClaimedJob{}, false, nil
|
||||
}
|
||||
job.started, job.leaseExpiresAt = true, now.Add(lease)
|
||||
claimed.LeaseExpiresAt = job.leaseExpiresAt
|
||||
return claimed, true, nil
|
||||
}
|
||||
|
||||
func (store *memoryStore) Run(ctx context.Context, claimed outbound.ClaimedJob, apply outbound.ApplyJob) error {
|
||||
if store.beforeRun != nil {
|
||||
store.beforeRun(claimed)
|
||||
}
|
||||
store.mu.Lock()
|
||||
runErr := store.runErr
|
||||
_, held := store.holds(claimed)
|
||||
store.mu.Unlock()
|
||||
if runErr != nil {
|
||||
return runErr
|
||||
}
|
||||
if !held {
|
||||
return fmt.Errorf("memoryStore.Run: %w", outbound.ErrJobLeaseLost)
|
||||
}
|
||||
store.mu.Lock()
|
||||
store.locked[claimed.ID] = true
|
||||
store.mu.Unlock()
|
||||
defer func() {
|
||||
store.mu.Lock()
|
||||
delete(store.locked, claimed.ID)
|
||||
store.mu.Unlock()
|
||||
}()
|
||||
if err := apply(ctx, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
// The commit of a canceled transaction fails and nothing commits.
|
||||
return err
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
job, held := store.holds(claimed)
|
||||
if !held {
|
||||
return fmt.Errorf("memoryStore.Run - complete: %w", outbound.ErrJobLeaseLost)
|
||||
}
|
||||
job.status, job.leaseOwner, job.leaseExpiresAt, job.started = "done", uuid.Nil, time.Time{}, false
|
||||
store.effects[claimed.ID]++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *memoryStore) Fail(_ context.Context, claimed outbound.ClaimedJob, failure outbound.JobFailure) (bool, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
job, held := store.holds(claimed)
|
||||
if !held {
|
||||
return false, nil
|
||||
}
|
||||
if failure.Dead {
|
||||
job.status = "dead"
|
||||
} else {
|
||||
job.status, job.availableAt = "failed", failure.RetryAt
|
||||
}
|
||||
job.errorClass, job.leaseOwner, job.leaseExpiresAt, job.started = failure.Class, uuid.Nil, time.Time{}, false
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *memoryStore) Release(_ context.Context, jobs []outbound.ClaimedJob) ([]int64, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
var released []int64
|
||||
for _, claimed := range jobs {
|
||||
job, held := store.holds(claimed)
|
||||
if !held {
|
||||
continue
|
||||
}
|
||||
job.status = "pending"
|
||||
if job.errorClass != "" {
|
||||
job.status = "failed"
|
||||
}
|
||||
job.attempts--
|
||||
job.leaseOwner, job.leaseExpiresAt, job.started = uuid.Nil, time.Time{}, false
|
||||
released = append(released, job.id)
|
||||
}
|
||||
return released, nil
|
||||
}
|
||||
|
||||
func (store *memoryStore) Backlog(_ context.Context, now time.Time) (outbound.JobBacklog, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
var backlog outbound.JobBacklog
|
||||
for _, job := range store.jobs {
|
||||
if (job.status == "pending" || job.status == "failed") && !job.availableAt.After(now) {
|
||||
backlog.Due++
|
||||
}
|
||||
if job.status == "dead" {
|
||||
backlog.Dead++
|
||||
}
|
||||
}
|
||||
return backlog, nil
|
||||
}
|
||||
|
||||
// recordingMetrics counts outcomes by kind.
|
||||
type recordingMetrics struct {
|
||||
mu sync.Mutex
|
||||
prepared []string
|
||||
outcomes map[string]int
|
||||
backlog outbound.JobBacklog
|
||||
}
|
||||
|
||||
func newRecordingMetrics() *recordingMetrics {
|
||||
return &recordingMetrics{outcomes: make(map[string]int)}
|
||||
}
|
||||
|
||||
func (metrics *recordingMetrics) PrepareScheduledJobKind(kind string) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.prepared = append(metrics.prepared, kind)
|
||||
}
|
||||
|
||||
func (metrics *recordingMetrics) ObserveScheduledJob(kind, outcome string) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.outcomes[kind+"/"+outcome]++
|
||||
}
|
||||
|
||||
func (metrics *recordingMetrics) ObserveScheduledJobBacklog(backlog outbound.JobBacklog) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.backlog = backlog
|
||||
}
|
||||
|
||||
// count returns the outcomes of testKind.
|
||||
func (metrics *recordingMetrics) count(outcome string) int {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
return metrics.outcomes[testKind+"/"+outcome]
|
||||
}
|
||||
|
||||
// funcHandler runs handle for one kind and records the order of calls.
|
||||
type funcHandler struct {
|
||||
kind string
|
||||
handle func(ctx context.Context, job outbound.ClaimedJob) error
|
||||
|
||||
mu sync.Mutex
|
||||
calls []int64
|
||||
}
|
||||
|
||||
func (handler *funcHandler) JobKind() string { return handler.kind }
|
||||
|
||||
func (handler *funcHandler) Handle(ctx context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
handler.mu.Lock()
|
||||
handler.calls = append(handler.calls, job.ID)
|
||||
handler.mu.Unlock()
|
||||
if handler.handle == nil {
|
||||
return nil
|
||||
}
|
||||
return handler.handle(ctx, job)
|
||||
}
|
||||
|
||||
func (handler *funcHandler) called() []int64 {
|
||||
handler.mu.Lock()
|
||||
defer handler.mu.Unlock()
|
||||
return slices.Clone(handler.calls)
|
||||
}
|
||||
|
||||
func testSettings() Settings {
|
||||
return Settings{
|
||||
BatchSize: 10,
|
||||
PollInterval: time.Millisecond,
|
||||
Lease: testLease,
|
||||
MaxAttempts: 3,
|
||||
Backoff: retry.Backoff{Initial: testBackoff, Max: testBackoff},
|
||||
ShutdownGrace: time.Second,
|
||||
StoreTimeout: time.Second,
|
||||
BacklogInterval: time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
type harness struct {
|
||||
clock *testutil.FakeClock
|
||||
store *memoryStore
|
||||
metrics *recordingMetrics
|
||||
logs *strings.Builder
|
||||
logsMu *sync.Mutex
|
||||
}
|
||||
|
||||
func newHarness() *harness {
|
||||
return &harness{
|
||||
clock: testutil.NewFakeClock(testStart),
|
||||
store: newMemoryStore(),
|
||||
metrics: newRecordingMetrics(),
|
||||
logs: &strings.Builder{},
|
||||
logsMu: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
type lockedWriter struct {
|
||||
mu *sync.Mutex
|
||||
builder *strings.Builder
|
||||
}
|
||||
|
||||
func (writer lockedWriter) Write(data []byte) (int, error) {
|
||||
writer.mu.Lock()
|
||||
defer writer.mu.Unlock()
|
||||
return writer.builder.Write(data)
|
||||
}
|
||||
|
||||
func (h *harness) logText() string {
|
||||
h.logsMu.Lock()
|
||||
defer h.logsMu.Unlock()
|
||||
return h.logs.String()
|
||||
}
|
||||
|
||||
func (h *harness) newWorker(t *testing.T, settings Settings, handlers ...inbound.JobHandler) *Worker {
|
||||
t.Helper()
|
||||
logger := slog.New(slog.NewJSONHandler(lockedWriter{mu: h.logsMu, builder: h.logs}, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
worker, err := New(handlers, h.store, h.metrics, logger, settings, h.clock.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
return worker
|
||||
}
|
||||
|
||||
func runDue(t *testing.T, worker *Worker) PassResult {
|
||||
t.Helper()
|
||||
result, err := worker.RunDue(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("RunDue() error = %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestNewRejectsInvalidRegistrations(t *testing.T) {
|
||||
h := newHarness()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
valid := &funcHandler{kind: testKind}
|
||||
tests := []struct {
|
||||
name string
|
||||
handlers []inbound.JobHandler
|
||||
settings func(*Settings)
|
||||
}{
|
||||
{name: "no handler"},
|
||||
{name: "invalid kind", handlers: []inbound.JobHandler{&funcHandler{kind: "Test Kind"}}},
|
||||
{name: "duplicate kind", handlers: []inbound.JobHandler{valid, &funcHandler{kind: testKind}}},
|
||||
{name: "zero batch", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.BatchSize = 0 }},
|
||||
{name: "too many attempts", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.MaxAttempts = 101 }},
|
||||
{name: "zero lease", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.Lease = 0 }},
|
||||
{name: "zero grace", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.ShutdownGrace = 0 }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
settings := testSettings()
|
||||
if test.settings != nil {
|
||||
test.settings(&settings)
|
||||
}
|
||||
if _, err := New(test.handlers, h.store, h.metrics, logger, settings, h.clock.Now); err == nil {
|
||||
t.Fatal("New() accepted an invalid registration")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueRunsOnlyDueJobsInDueOrder(t *testing.T) {
|
||||
h := newHarness()
|
||||
handler := &funcHandler{kind: testKind}
|
||||
worker := h.newWorker(t, testSettings(), handler, &funcHandler{kind: otherKind})
|
||||
if kinds := worker.Kinds(); !slices.Equal(kinds, []string{testKind, otherKind}) || !slices.Equal(h.metrics.prepared, kinds) {
|
||||
t.Fatalf("Kinds() = %v, prepared %v", kinds, h.metrics.prepared)
|
||||
}
|
||||
later := h.store.schedule(testKind, testStart.Add(48*time.Hour))
|
||||
second := h.store.schedule(testKind, testStart.Add(-time.Minute))
|
||||
first := h.store.schedule(testKind, testStart.Add(-time.Hour))
|
||||
unknown := h.store.schedule("test.unregistered", testStart.Add(-time.Hour))
|
||||
|
||||
if result := runDue(t, worker); result.Claimed != 2 || result.Done != 2 {
|
||||
t.Fatalf("first pass = %+v, want two done jobs", result)
|
||||
}
|
||||
if calls := handler.called(); !slices.Equal(calls, []int64{first, second}) {
|
||||
t.Fatalf("handler calls = %v, want %v in due order", calls, []int64{first, second})
|
||||
}
|
||||
if result := runDue(t, worker); result.Claimed != 0 {
|
||||
t.Fatalf("second pass at the same time claimed %d jobs", result.Claimed)
|
||||
}
|
||||
|
||||
h.clock.Advance(48*time.Hour - time.Nanosecond)
|
||||
if result := runDue(t, worker); result.Claimed != 0 {
|
||||
t.Fatal("a job ran before its due time")
|
||||
}
|
||||
h.clock.Advance(time.Nanosecond)
|
||||
if result := runDue(t, worker); result.Done != 1 || h.store.effectCount(later) != 1 {
|
||||
t.Fatalf("pass at the due time = %+v, effects %d", result, h.store.effectCount(later))
|
||||
}
|
||||
if job := h.store.job(unknown); job.status != "pending" || job.attempts != 0 {
|
||||
t.Fatalf("a job of an unregistered kind was touched: %+v", job)
|
||||
}
|
||||
if got := h.metrics.count(OutcomeDone); got != 3 {
|
||||
t.Fatalf("done outcomes = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueRetriesWithBackoffAndThenKillsTheJob(t *testing.T) {
|
||||
h := newHarness()
|
||||
handler := &funcHandler{kind: testKind, handle: func(context.Context, outbound.ClaimedJob) error { return errEffectFail }}
|
||||
worker := h.newWorker(t, testSettings(), handler)
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
|
||||
for attempt := 1; attempt < 3; attempt++ {
|
||||
if result := runDue(t, worker); result.Retried != 1 {
|
||||
t.Fatalf("attempt %d = %+v, want a retry", attempt, result)
|
||||
}
|
||||
job := h.store.job(id)
|
||||
// Backoff with Initial == Max waits between half and the whole of it.
|
||||
wait := job.availableAt.Sub(h.clock.Now())
|
||||
if job.status != "failed" || job.errorClass != outbound.JobErrorHandlerFailed || wait < testBackoff/2 || wait > testBackoff ||
|
||||
!job.dueAt.Equal(testStart) {
|
||||
t.Fatalf("after attempt %d job = %+v, retry in %s", attempt, job, wait)
|
||||
}
|
||||
// No hot loop: the job is not due again until the backoff passed.
|
||||
if result := runDue(t, worker); result.Claimed != 0 {
|
||||
t.Fatalf("attempt %d was retried before its backoff", attempt)
|
||||
}
|
||||
h.clock.Advance(testBackoff)
|
||||
}
|
||||
if result := runDue(t, worker); result.Dead != 1 {
|
||||
t.Fatalf("last attempt = %+v, want a dead job", result)
|
||||
}
|
||||
if job := h.store.job(id); job.status != "dead" || job.attempts != 3 || h.store.effectCount(id) != 0 {
|
||||
t.Fatalf("job after the last attempt = %+v", job)
|
||||
}
|
||||
if h.metrics.count(OutcomeRetry) != 2 || h.metrics.count(OutcomeDead) != 1 {
|
||||
t.Fatalf("outcomes = %v", h.metrics.outcomes)
|
||||
}
|
||||
logs := h.logText()
|
||||
if !strings.Contains(logs, "scheduled job is dead; it needs an operator") || !strings.Contains(logs, `"level":"ERROR"`) {
|
||||
t.Fatalf("dead job was not logged as an error:\n%s", logs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueEndsRejectedAndPanickingJobsAtOnce(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
handle func(context.Context, outbound.ClaimedJob) error
|
||||
class outbound.JobErrorClass
|
||||
}{
|
||||
{name: "rejected", class: outbound.JobErrorHandlerRejected, handle: func(context.Context, outbound.ClaimedJob) error {
|
||||
return fmt.Errorf("unsupported payload: %w", inbound.ErrJobRejected)
|
||||
}},
|
||||
{name: "panic", class: outbound.JobErrorHandlerPanic, handle: func(context.Context, outbound.ClaimedJob) error {
|
||||
panic("secret payload value")
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
h := newHarness()
|
||||
worker := h.newWorker(t, testSettings(), &funcHandler{kind: testKind, handle: test.handle})
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
if result := runDue(t, worker); result.Dead != 1 {
|
||||
t.Fatalf("RunDue() = %+v, want a dead job", result)
|
||||
}
|
||||
if job := h.store.job(id); job.status != "dead" || job.attempts != 1 || job.errorClass != test.class {
|
||||
t.Fatalf("job = %+v, want dead with class %s after one attempt", job, test.class)
|
||||
}
|
||||
if strings.Contains(h.logText(), "secret payload value") {
|
||||
t.Fatal("the panic value reached the logs")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueTimesOutAHandlerAtTheEndOfItsLease(t *testing.T) {
|
||||
h := newHarness()
|
||||
settings := testSettings()
|
||||
// The handler context ends with the lease in real time.
|
||||
settings.Lease = 50 * time.Millisecond
|
||||
handler := &funcHandler{kind: testKind, handle: func(ctx context.Context, _ outbound.ClaimedJob) error {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}}
|
||||
worker := h.newWorker(t, settings, handler)
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
if result := runDue(t, worker); result.Retried != 1 {
|
||||
t.Fatalf("RunDue() = %+v, want a retry", result)
|
||||
}
|
||||
if job := h.store.job(id); job.errorClass != outbound.JobErrorTimeout || h.store.effectCount(id) != 0 {
|
||||
t.Fatalf("job = %+v, want a timeout without effect", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueSkipsAJobWhoseLeaseWasLost(t *testing.T) {
|
||||
h := newHarness()
|
||||
handler := &funcHandler{kind: testKind}
|
||||
worker := h.newWorker(t, testSettings(), handler)
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
// Another worker reclaims the job after the lease expired, before this
|
||||
// worker starts it.
|
||||
h.store.beforeRun = func(claimed outbound.ClaimedJob) {
|
||||
h.store.mu.Lock()
|
||||
defer h.store.mu.Unlock()
|
||||
h.store.jobs[claimed.ID].leaseOwner = uuid.New()
|
||||
h.store.jobs[claimed.ID].attempts++
|
||||
}
|
||||
if result := runDue(t, worker); result.LeaseLost != 1 || len(handler.called()) != 0 {
|
||||
t.Fatalf("RunDue() = %+v, handler calls %v; want a lost lease without a call", result, handler.called())
|
||||
}
|
||||
if job := h.store.job(id); job.status != "running" || h.store.effectCount(id) != 0 {
|
||||
t.Fatalf("the other worker's job was changed: %+v", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueKillsAJobWhoseLastLeaseExpired(t *testing.T) {
|
||||
h := newHarness()
|
||||
handler := &funcHandler{kind: testKind}
|
||||
worker := h.newWorker(t, testSettings(), handler)
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
// Three earlier attempts started the handler and stopped without
|
||||
// finishing, as crashed workers would.
|
||||
for range 3 {
|
||||
claimed, err := h.store.Claim(t.Context(), outbound.JobClaim{
|
||||
Owner: uuid.New(), Kinds: []string{testKind}, Now: h.clock.Now(), Lease: testLease, Limit: 1, DefaultMaxAttempts: 3,
|
||||
})
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("Claim() = %v, %v", claimed, err)
|
||||
}
|
||||
if _, ok, err := h.store.Start(t.Context(), claimed[0], h.clock.Now(), testLease); !ok || err != nil {
|
||||
t.Fatalf("Start() = %t, %v", ok, err)
|
||||
}
|
||||
h.clock.Advance(testLease)
|
||||
}
|
||||
if result := runDue(t, worker); result.Dead != 1 || len(handler.called()) != 0 {
|
||||
t.Fatalf("RunDue() = %+v, handler calls %v; want a dead job without a call", result, handler.called())
|
||||
}
|
||||
if job := h.store.job(id); job.status != "dead" || job.errorClass != outbound.JobErrorLeaseExpired {
|
||||
t.Fatalf("job = %+v", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueReleasesJobsAfterADatabaseFailure(t *testing.T) {
|
||||
h := newHarness()
|
||||
worker := h.newWorker(t, testSettings(), &funcHandler{kind: testKind})
|
||||
first := h.store.schedule(testKind, testStart)
|
||||
second := h.store.schedule(testKind, testStart.Add(time.Second))
|
||||
h.clock.Advance(time.Second)
|
||||
h.store.runErr = errStoreDown
|
||||
|
||||
result, err := worker.RunDue(t.Context())
|
||||
if !errors.Is(err, errStoreDown) || result.Released != 2 {
|
||||
t.Fatalf("RunDue() = %+v, %v; want both jobs released and the store error", result, err)
|
||||
}
|
||||
for _, id := range []int64{first, second} {
|
||||
// The attempt is not counted: the job did not cause the failure.
|
||||
if job := h.store.job(id); job.status != "pending" || job.attempts != 0 {
|
||||
t.Fatalf("job %d after the failure = %+v", id, job)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBacksOffWhileTheDatabaseFails(t *testing.T) {
|
||||
h := newHarness()
|
||||
settings := testSettings()
|
||||
settings.Backoff = retry.Backoff{Initial: 100 * time.Millisecond, Max: 100 * time.Millisecond}
|
||||
worker := h.newWorker(t, settings, &funcHandler{kind: testKind})
|
||||
h.store.claimErr = errStoreDown
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
worker.Run(ctx)
|
||||
}()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
cancel()
|
||||
awaitClosed(t, stopped, "Run to return")
|
||||
// Waits of 50ms to 100ms allow at most seven claims in 300ms.
|
||||
if claims := h.store.claimCount(); claims < 2 || claims > 7 {
|
||||
t.Fatalf("Run claimed %d times in 300ms of failures; want a backoff, not a hot loop", claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunFinishesTheJobInProgressWithinTheGrace(t *testing.T) {
|
||||
h := newHarness()
|
||||
started := make(chan struct{})
|
||||
finish := make(chan struct{})
|
||||
handler := &funcHandler{kind: testKind, handle: func(ctx context.Context, _ outbound.ClaimedJob) error {
|
||||
close(started)
|
||||
select {
|
||||
case <-finish:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}}
|
||||
worker := h.newWorker(t, testSettings(), handler)
|
||||
inProgress := h.store.schedule(testKind, testStart.Add(-time.Minute))
|
||||
notStarted := h.store.schedule(testKind, testStart)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
worker.Run(ctx)
|
||||
}()
|
||||
awaitClosed(t, started, "the handler to start")
|
||||
cancel()
|
||||
close(finish)
|
||||
awaitClosed(t, stopped, "Run to return")
|
||||
|
||||
if job := h.store.job(inProgress); job.status != "done" || h.store.effectCount(inProgress) != 1 {
|
||||
t.Fatalf("job in progress = %+v, want done within the grace", job)
|
||||
}
|
||||
// The second job of the batch did not start; it went back at once.
|
||||
if job := h.store.job(notStarted); job.status != "pending" || job.attempts != 0 || job.leaseOwner != uuid.Nil {
|
||||
t.Fatalf("job not started = %+v, want released", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCancelsAndReleasesAJobThatOutlastsTheGrace(t *testing.T) {
|
||||
h := newHarness()
|
||||
settings := testSettings()
|
||||
settings.ShutdownGrace = 50 * time.Millisecond
|
||||
started := make(chan struct{})
|
||||
handler := &funcHandler{kind: testKind, handle: func(ctx context.Context, _ outbound.ClaimedJob) error {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}}
|
||||
worker := h.newWorker(t, settings, handler)
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
worker.Run(ctx)
|
||||
}()
|
||||
awaitClosed(t, started, "the handler to start")
|
||||
cancel()
|
||||
awaitClosed(t, stopped, "Run to return after the grace")
|
||||
|
||||
// The unfinished job is neither done nor counted as a failure, and it is
|
||||
// claimable again at once.
|
||||
job := h.store.job(id)
|
||||
if job.status != "pending" || job.attempts != 0 || job.errorClass != "" || h.store.effectCount(id) != 0 {
|
||||
t.Fatalf("job after shutdown = %+v, want released and not done", job)
|
||||
}
|
||||
if h.metrics.count(OutcomeReleased) != 1 || h.metrics.count(OutcomeRetry) != 0 {
|
||||
t.Fatalf("outcomes = %v", h.metrics.outcomes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunReportsTheBacklog(t *testing.T) {
|
||||
h := newHarness()
|
||||
worker := h.newWorker(t, testSettings(), &funcHandler{kind: otherKind})
|
||||
h.store.schedule(testKind, testStart)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
worker.Run(ctx)
|
||||
}()
|
||||
deadline := time.Now().Add(testWait)
|
||||
for {
|
||||
h.metrics.mu.Lock()
|
||||
due := h.metrics.backlog.Due
|
||||
h.metrics.mu.Unlock()
|
||||
if due == 1 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the backlog of a kind without a handler was not reported")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
awaitClosed(t, stopped, "Run to return")
|
||||
}
|
||||
|
||||
func awaitClosed(t *testing.T, signal <-chan struct{}, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-signal:
|
||||
case <-time.After(testWait):
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDueDoesNotSpendAnAttemptOnAJobWhoseTurnCameTooLate(t *testing.T) {
|
||||
h := newHarness()
|
||||
handler := &funcHandler{kind: testKind, handle: func(_ context.Context, job outbound.ClaimedJob) error {
|
||||
if job.ID == 1 {
|
||||
// The first job of the batch runs past the lease of the claim.
|
||||
h.clock.Advance(2 * testLease)
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
worker := h.newWorker(t, testSettings(), handler)
|
||||
slow := h.store.schedule(testKind, testStart.Add(-time.Minute))
|
||||
late := h.store.scheduleWithLimit(testKind, testStart, 1)
|
||||
|
||||
if result := runDue(t, worker); result.Claimed != 2 || result.Done != 1 || result.Released != 1 {
|
||||
t.Fatalf("first pass = %+v, want the slow job done and the late one released", result)
|
||||
}
|
||||
// The late job never started, so its only allowed attempt is intact.
|
||||
if job := h.store.job(late); job.status != "pending" || job.attempts != 0 {
|
||||
t.Fatalf("late job after the slow one = %+v, want pending without an attempt", job)
|
||||
}
|
||||
if result := runDue(t, worker); result.Done != 1 || h.store.effectCount(late) != 1 || h.store.effectCount(slow) != 1 {
|
||||
t.Fatalf("second pass = %+v, want the late job done once", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnotherWorkerRunsAJobThatABusyWorkerDidNotStart(t *testing.T) {
|
||||
h := newHarness()
|
||||
inSlowJob, finishSlowJob := make(chan struct{}), make(chan struct{})
|
||||
busy := h.newWorker(t, testSettings(), &funcHandler{kind: testKind, handle: func(ctx context.Context, job outbound.ClaimedJob) error {
|
||||
if job.ID != 1 {
|
||||
return nil
|
||||
}
|
||||
close(inSlowJob)
|
||||
select {
|
||||
case <-finishSlowJob:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}})
|
||||
other := h.newWorker(t, testSettings(), &funcHandler{kind: testKind})
|
||||
h.store.schedule(testKind, testStart.Add(-time.Minute))
|
||||
waiting := h.store.scheduleWithLimit(testKind, testStart, 1)
|
||||
|
||||
finished := make(chan PassResult, 1)
|
||||
go func() {
|
||||
result, _ := busy.RunDue(t.Context())
|
||||
finished <- result
|
||||
}()
|
||||
awaitClosed(t, inSlowJob, "the slow job to start")
|
||||
h.clock.Advance(2 * testLease)
|
||||
// The waiting job's attempt never started, so the other worker reuses it
|
||||
// instead of counting a second one, and its single attempt is not lost.
|
||||
if result := runDue(t, other); result.Done != 1 {
|
||||
t.Fatalf("other worker pass = %+v, want the waiting job done", result)
|
||||
}
|
||||
close(finishSlowJob)
|
||||
var result PassResult
|
||||
select {
|
||||
case result = <-finished:
|
||||
case <-time.After(testWait):
|
||||
t.Fatal("the busy worker did not finish its pass")
|
||||
}
|
||||
if result.Done != 1 || result.LeaseLost != 1 {
|
||||
t.Fatalf("busy worker pass = %+v, want its own job done and the taken one lost", result)
|
||||
}
|
||||
if job := h.store.job(waiting); job.status != "done" || job.attempts != 1 || h.store.effectCount(waiting) != 1 {
|
||||
t.Fatalf("waiting job = %+v, effects %d; want done once on its single attempt", job, h.store.effectCount(waiting))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunKillsAPanickingJobAlsoWhileStopping(t *testing.T) {
|
||||
h := newHarness()
|
||||
started, panicNow := make(chan struct{}), make(chan struct{})
|
||||
worker := h.newWorker(t, testSettings(), &funcHandler{kind: testKind, handle: func(context.Context, outbound.ClaimedJob) error {
|
||||
close(started)
|
||||
<-panicNow
|
||||
panic("broken handler")
|
||||
}})
|
||||
id := h.store.schedule(testKind, testStart)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
worker.Run(ctx)
|
||||
}()
|
||||
awaitClosed(t, started, "the handler to start")
|
||||
cancel()
|
||||
close(panicNow)
|
||||
awaitClosed(t, stopped, "Run to return")
|
||||
// A panic is the job's own fault, so shutdown does not release it.
|
||||
if job := h.store.job(id); job.status != "dead" || job.errorClass != outbound.JobErrorHandlerPanic {
|
||||
t.Fatalf("job = %+v, want dead with handler_panic", job)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user