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
@@ -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:
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
-- +goose Up
|
||||
-- Durable jobs that run when they fall due, such as a response deadline. A
|
||||
-- usecase schedules a job in its own business transaction, so the job exists
|
||||
-- exactly when the business change committed. The scheduled job worker
|
||||
-- claims due jobs under a lease and runs each handler in one transaction
|
||||
-- with the completion of its job, so a database-only effect happens once.
|
||||
--
|
||||
-- Every due and lease time comes from the application clock, never from the
|
||||
-- database clock, so tests can move time without waiting. created_at and
|
||||
-- updated_at are informational database times for operators.
|
||||
--
|
||||
-- The payload holds identifiers only. Rows are kept after they finish: the
|
||||
-- (kind, dedup_key) pair stays reserved, so a repeated schedule of a job
|
||||
-- that already ran or was canceled does nothing. Retention of finished rows
|
||||
-- is not implemented yet.
|
||||
CREATE TABLE scheduled_jobs (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY,
|
||||
-- Handler name from the code, for example "invitation.response_deadline".
|
||||
kind text NOT NULL,
|
||||
-- Caller key of the logical job within its kind, for example an
|
||||
-- aggregate ID. It must not contain personal data.
|
||||
dedup_key text NOT NULL,
|
||||
-- Small JSON object of identifiers for the handler.
|
||||
payload jsonb NOT NULL,
|
||||
-- When the job falls due: the deadline it stands for. It never changes,
|
||||
-- so a handler that runs late or on a retry still sees the deadline.
|
||||
due_at timestamptz NOT NULL,
|
||||
-- When a worker may claim the job next: due_at at first, then the
|
||||
-- retry time after a failed attempt.
|
||||
available_at timestamptz NOT NULL,
|
||||
-- pending: waits for available_at and no attempt failed yet;
|
||||
-- failed: an attempt failed and the job waits for its retry at
|
||||
-- available_at;
|
||||
-- running: claimed under a lease; done, dead, cancelled: final.
|
||||
status text NOT NULL,
|
||||
-- Attempts counted so far, including a running one. A claim counts its
|
||||
-- attempt before the handler runs, so a job that crashes the process
|
||||
-- cannot loop forever; a claim whose attempt never started is reused
|
||||
-- by the next claim instead of counted twice.
|
||||
attempts integer NOT NULL,
|
||||
-- NULL means the worker default, JOBS_MAX_ATTEMPTS.
|
||||
max_attempts integer,
|
||||
-- Random ID of the worker instance that holds the lease.
|
||||
lease_owner uuid,
|
||||
lease_expires_at timestamptz,
|
||||
-- When the worker started the handler of the running attempt and
|
||||
-- renewed its lease, by the application clock. NULL while the job is
|
||||
-- claimed but not started, and whenever it is not running.
|
||||
started_at timestamptz,
|
||||
-- Bounded cause of the last failed or abandoned attempt; never text
|
||||
-- from the handler.
|
||||
last_error_class text,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT scheduled_jobs_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT scheduled_jobs_kind_dedup_key_key UNIQUE (kind, dedup_key),
|
||||
CONSTRAINT scheduled_jobs_kind_format CHECK (
|
||||
char_length(kind) <= 64
|
||||
AND kind ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$'
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_dedup_key_format CHECK (
|
||||
char_length(dedup_key) <= 128
|
||||
AND dedup_key ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$'
|
||||
),
|
||||
-- The application allows 2 KiB of compact JSON; the jsonb text form
|
||||
-- adds spaces, so this backstop is wider.
|
||||
CONSTRAINT scheduled_jobs_payload_object CHECK (
|
||||
jsonb_typeof(payload) = 'object'
|
||||
AND octet_length(payload::text) <= 4096
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_status_known CHECK (
|
||||
status IN ('pending', 'failed', 'running', 'done', 'dead', 'cancelled')
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_attempts_bounded CHECK (
|
||||
attempts >= 0
|
||||
AND (max_attempts IS NULL OR max_attempts BETWEEN 1 AND 100)
|
||||
),
|
||||
-- Only a running job holds a lease, and a running job always does.
|
||||
CONSTRAINT scheduled_jobs_lease_when_running CHECK (
|
||||
(status = 'running')
|
||||
= (lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL)
|
||||
AND (lease_owner IS NULL) = (lease_expires_at IS NULL)
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_running_counted CHECK (
|
||||
status <> 'running' OR attempts > 0
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_started_when_running CHECK (
|
||||
status = 'running' OR started_at IS NULL
|
||||
),
|
||||
-- failed differs from pending only by the recorded cause, so an
|
||||
-- operator can tell a first wait from a retry.
|
||||
CONSTRAINT scheduled_jobs_failed_has_cause CHECK (
|
||||
(status <> 'pending' OR last_error_class IS NULL)
|
||||
AND (status <> 'failed' OR last_error_class IS NOT NULL)
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_error_class_known CHECK (
|
||||
last_error_class IN (
|
||||
'handler_failed',
|
||||
'handler_rejected',
|
||||
'handler_panic',
|
||||
'timeout',
|
||||
'conflict',
|
||||
'effect_rejected',
|
||||
'lease_expired',
|
||||
'completion_conflict'
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the claim of due jobs. It covers only waiting rows, so it stays
|
||||
-- small while finished rows accumulate.
|
||||
CREATE INDEX scheduled_jobs_available_idx
|
||||
ON scheduled_jobs (available_at, id)
|
||||
WHERE status IN ('pending', 'failed');
|
||||
|
||||
-- Serves the claim of running jobs whose lease expired.
|
||||
CREATE INDEX scheduled_jobs_lease_idx
|
||||
ON scheduled_jobs (lease_expires_at)
|
||||
WHERE status = 'running';
|
||||
|
||||
-- Serves the dead job gauge and operator queries; dead jobs are rare.
|
||||
CREATE INDEX scheduled_jobs_dead_idx
|
||||
ON scheduled_jobs (kind, updated_at)
|
||||
WHERE status = 'dead';
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE scheduled_jobs;
|
||||
@@ -0,0 +1,288 @@
|
||||
-- Lock order. A job handler runs while its transaction holds the row lock
|
||||
-- of the job, and may then lock product rows. A business transaction that
|
||||
-- cancels a job should cancel it before it locks the product rows the
|
||||
-- handler touches, so both take the locks in the same order.
|
||||
|
||||
-- Schedules a job in the caller's transaction. The first schedule of a
|
||||
-- (kind, dedup_key) wins: a repeat, also after the job finished or was
|
||||
-- canceled, inserts nothing and reports 0 rows, so a repeated command never
|
||||
-- moves a deadline. A concurrent insert of the same key waits for the first
|
||||
-- transaction and then inserts nothing, or inserts after its rollback.
|
||||
-- name: InsertScheduledJob :execrows
|
||||
INSERT INTO scheduled_jobs (
|
||||
kind,
|
||||
dedup_key,
|
||||
payload,
|
||||
due_at,
|
||||
available_at,
|
||||
status,
|
||||
attempts,
|
||||
max_attempts
|
||||
) VALUES (
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(dedup_key),
|
||||
sqlc.arg(payload),
|
||||
sqlc.arg(due_at),
|
||||
sqlc.arg(due_at),
|
||||
'pending',
|
||||
0,
|
||||
sqlc.narg(max_attempts)
|
||||
)
|
||||
ON CONFLICT (kind, dedup_key) DO NOTHING;
|
||||
|
||||
-- Cancels a job that has not finished. A job whose handler transaction is
|
||||
-- in progress holds its row lock, so the statement waits for it: after the
|
||||
-- handler committed the job is done and nothing is canceled; otherwise the
|
||||
-- worker finds its lease gone and does not run or complete the job.
|
||||
-- name: CancelScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
status = 'cancelled',
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
kind = sqlc.arg(kind)
|
||||
AND dedup_key = sqlc.arg(dedup_key)
|
||||
AND status IN ('pending', 'failed', 'running');
|
||||
|
||||
-- Claims up to batch_limit jobs of the listed kinds in one statement: jobs
|
||||
-- whose available_at has passed, and running jobs whose lease expired
|
||||
-- because their worker stopped without finishing them. Rows that another
|
||||
-- worker locks are skipped without waiting. Each claimed job gets the lease
|
||||
-- of lease_owner and one more attempt, except a job whose expired attempt
|
||||
-- never started its handler: that attempt is reused, so a worker that was
|
||||
-- busy with other jobs of its batch costs the job nothing. A job whose
|
||||
-- started attempt was abandoned on its last allowed attempt becomes dead
|
||||
-- with lease_expired instead, so a job that keeps crashing its worker
|
||||
-- stops. now is the application clock.
|
||||
--
|
||||
-- The kind filter applies after the index on available_at; when many waiting
|
||||
-- jobs belong to kinds without a handler in the claiming process, an index
|
||||
-- on (kind, available_at, id) is the next step.
|
||||
-- name: ClaimScheduledJobs :many
|
||||
WITH candidates AS (
|
||||
SELECT
|
||||
candidate.id,
|
||||
(
|
||||
candidate.status = 'running'
|
||||
AND candidate.started_at IS NULL
|
||||
) AS unstarted,
|
||||
(
|
||||
candidate.status = 'running'
|
||||
AND candidate.started_at IS NOT NULL
|
||||
AND candidate.attempts >= coalesce(
|
||||
candidate.max_attempts,
|
||||
sqlc.arg(default_max_attempts)::integer
|
||||
)
|
||||
) AS exhausted
|
||||
FROM scheduled_jobs AS candidate
|
||||
WHERE
|
||||
candidate.kind = any(sqlc.arg(kinds)::text [])
|
||||
AND (
|
||||
(
|
||||
candidate.status IN ('pending', 'failed')
|
||||
AND candidate.available_at <= sqlc.arg(now)::timestamptz
|
||||
)
|
||||
OR (
|
||||
candidate.status = 'running'
|
||||
AND candidate.lease_expires_at <= sqlc.arg(now)::timestamptz
|
||||
)
|
||||
)
|
||||
ORDER BY candidate.available_at, candidate.id
|
||||
LIMIT sqlc.arg(batch_limit)
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
|
||||
UPDATE scheduled_jobs AS job
|
||||
SET
|
||||
status = CASE WHEN candidates.exhausted THEN 'dead' ELSE 'running' END,
|
||||
attempts = CASE
|
||||
WHEN candidates.exhausted OR candidates.unstarted THEN job.attempts
|
||||
ELSE job.attempts + 1
|
||||
END,
|
||||
lease_owner = CASE
|
||||
WHEN candidates.exhausted THEN NULL ELSE sqlc.arg(lease_owner)::uuid
|
||||
END,
|
||||
lease_expires_at = CASE
|
||||
WHEN
|
||||
candidates.exhausted
|
||||
THEN NULL
|
||||
ELSE sqlc.arg(lease_expires_at)::timestamptz
|
||||
END,
|
||||
started_at = NULL,
|
||||
last_error_class = CASE
|
||||
WHEN
|
||||
job.status = 'running' AND NOT candidates.unstarted
|
||||
THEN 'lease_expired'
|
||||
ELSE job.last_error_class
|
||||
END,
|
||||
updated_at = clock_timestamp()
|
||||
FROM candidates
|
||||
WHERE job.id = candidates.id
|
||||
RETURNING
|
||||
job.id,
|
||||
job.kind,
|
||||
job.dedup_key,
|
||||
job.payload,
|
||||
job.due_at,
|
||||
job.attempts,
|
||||
coalesce(
|
||||
job.max_attempts, sqlc.arg(default_max_attempts)::integer
|
||||
)::integer AS max_attempts,
|
||||
candidates.exhausted;
|
||||
|
||||
-- Starts a claimed attempt right before its handler transaction: it renews
|
||||
-- the lease from now and records the start, committed on its own. It
|
||||
-- changes nothing when the lease already expired by now or no longer
|
||||
-- belongs to this attempt, so a job whose turn in the batch came too late is
|
||||
-- never started on a lease that another worker may take over. now is the
|
||||
-- application clock.
|
||||
-- name: StartScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
lease_expires_at = sqlc.arg(lease_expires_at),
|
||||
started_at = sqlc.arg(now),
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND status = 'running'
|
||||
AND lease_owner = sqlc.arg(lease_owner)
|
||||
AND attempts = sqlc.arg(attempt)
|
||||
AND lease_expires_at > sqlc.arg(now);
|
||||
|
||||
-- Locks a claimed job for its handler transaction and checks that the lease
|
||||
-- still belongs to this attempt. It returns no row when the job was
|
||||
-- canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
-- other workers skip the row, so the handler never runs twice at once.
|
||||
-- name: LockClaimedScheduledJob :one
|
||||
SELECT job.id
|
||||
FROM scheduled_jobs AS job
|
||||
WHERE
|
||||
job.id = sqlc.arg(id)
|
||||
AND job.status = 'running'
|
||||
AND job.lease_owner = sqlc.arg(lease_owner)
|
||||
AND job.attempts = sqlc.arg(attempt)
|
||||
FOR UPDATE;
|
||||
|
||||
-- Completes a job in the transaction of its handler effect. The guard is
|
||||
-- the lease owner and the attempt, so a worker that lost its lease cannot
|
||||
-- complete the job.
|
||||
-- name: CompleteScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
status = 'done',
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND status = 'running'
|
||||
AND lease_owner = sqlc.arg(lease_owner)
|
||||
AND attempts = sqlc.arg(attempt);
|
||||
|
||||
-- Records a failed attempt after its handler transaction rolled back: the
|
||||
-- job waits for its retry at retry_at (status failed) or is dead, with a
|
||||
-- NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
-- completion applies.
|
||||
-- name: FailScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
status = sqlc.arg(status),
|
||||
available_at = coalesce(sqlc.narg(retry_at), available_at),
|
||||
last_error_class = sqlc.arg(error_class),
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND status = 'running'
|
||||
AND lease_owner = sqlc.arg(lease_owner)
|
||||
AND attempts = sqlc.arg(attempt);
|
||||
|
||||
-- Returns claimed jobs that did not finish, at shutdown or after a database
|
||||
-- failure outside the handler, so another worker can run them at once
|
||||
-- instead of after the lease expires. The attempt is not counted, because
|
||||
-- the job did not cause the failure. The same guard as the completion
|
||||
-- applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
-- name: ReleaseScheduledJobs :many
|
||||
UPDATE scheduled_jobs AS job
|
||||
SET
|
||||
status = CASE
|
||||
WHEN job.last_error_class IS NULL THEN 'pending' ELSE 'failed'
|
||||
END,
|
||||
attempts = job.attempts - 1,
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
FROM (
|
||||
-- Set-returning functions in one select list advance together, so the
|
||||
-- arrays pair up by position. The two-argument unnest(ids, attempts)
|
||||
-- would say the same, but the sqlc analyzer cannot type it, and
|
||||
-- sqlfluff cannot parse ROWS FROM.
|
||||
SELECT
|
||||
unnest(sqlc.arg(ids)::bigint []) AS id,
|
||||
unnest(sqlc.arg(attempts)::integer []) AS attempt
|
||||
) AS released
|
||||
WHERE
|
||||
job.id = released.id
|
||||
AND job.attempts = released.attempt
|
||||
AND job.status = 'running'
|
||||
AND job.lease_owner = sqlc.arg(lease_owner)
|
||||
RETURNING job.id;
|
||||
|
||||
-- Reads the status of a job whose completion found it changed, inside
|
||||
-- the handler transaction that holds its row lock: only that transaction
|
||||
-- can have changed it, for example by canceling its own job.
|
||||
-- name: GetScheduledJobStatus :one
|
||||
SELECT job.status
|
||||
FROM scheduled_jobs AS job
|
||||
WHERE job.id = sqlc.arg(id);
|
||||
|
||||
-- Reads the backlog for metrics without locking: jobs that a worker may
|
||||
-- claim at now, how long the earliest of them has waited, and the dead
|
||||
-- jobs. The
|
||||
-- partial indexes keep the cost proportional to those rows. now is the
|
||||
-- application clock.
|
||||
-- name: GetScheduledJobBacklog :one
|
||||
SELECT
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM scheduled_jobs AS due
|
||||
WHERE
|
||||
due.status IN ('pending', 'failed')
|
||||
AND due.available_at <= sqlc.arg(now)::timestamptz
|
||||
)::bigint AS due_jobs,
|
||||
coalesce((
|
||||
SELECT
|
||||
extract(EPOCH FROM sqlc.arg(now)::timestamptz - oldest.available_at)
|
||||
FROM scheduled_jobs AS oldest
|
||||
WHERE
|
||||
oldest.status IN ('pending', 'failed')
|
||||
AND oldest.available_at <= sqlc.arg(now)::timestamptz
|
||||
ORDER BY oldest.available_at
|
||||
LIMIT 1
|
||||
), 0)::float8 AS oldest_due_age_seconds,
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM scheduled_jobs AS dead
|
||||
WHERE dead.status = 'dead'
|
||||
)::bigint AS dead_jobs;
|
||||
|
||||
-- Bounds a handler transaction on the server, local to the transaction.
|
||||
-- statement_timeout stops a slow statement; idle_in_transaction_session_timeout
|
||||
-- ends the session of a worker that froze or lost the network inside the
|
||||
-- handler, which releases the job row lock so the job can be reclaimed once
|
||||
-- its lease expires.
|
||||
-- name: SetScheduledJobTransactionTimeouts :exec
|
||||
SELECT
|
||||
set_config('statement_timeout', sqlc.arg(statement_timeout_ms)::text, true),
|
||||
set_config(
|
||||
'idle_in_transaction_session_timeout',
|
||||
sqlc.arg(idle_timeout_ms)::text,
|
||||
true
|
||||
);
|
||||
@@ -31,16 +31,19 @@ const (
|
||||
deliveryMigrationVersion = 6
|
||||
// mailQuotaMigrationVersion creates mailQuotaTableNames.
|
||||
mailQuotaMigrationVersion = 7
|
||||
// scheduledJobMigrationVersion creates scheduledJobTableNames.
|
||||
scheduledJobMigrationVersion = 8
|
||||
)
|
||||
|
||||
var (
|
||||
// Tables created by 00001, 00002, 00003, 00005, 00006, and 00007.
|
||||
outboxTables = []string{"outbox_events"}
|
||||
identityTableNames = []string{"users", "email_tokens", "sessions"}
|
||||
policyTableNames = []string{"policy_versions"}
|
||||
consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"}
|
||||
deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"}
|
||||
mailQuotaTableNames = []string{"mail_quota_usage", "mail_quota_reservations"}
|
||||
// Tables created by 00001, 00002, 00003, 00005, 00006, 00007, and 00008.
|
||||
outboxTables = []string{"outbox_events"}
|
||||
identityTableNames = []string{"users", "email_tokens", "sessions"}
|
||||
policyTableNames = []string{"policy_versions"}
|
||||
consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"}
|
||||
deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"}
|
||||
mailQuotaTableNames = []string{"mail_quota_usage", "mail_quota_reservations"}
|
||||
scheduledJobTableNames = []string{"scheduled_jobs"}
|
||||
// Trigger functions created by 00003 and 00006.
|
||||
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
|
||||
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
|
||||
@@ -76,8 +79,10 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
assertTablesExist(ctx, t, pool, true, deliveryTableNames...)
|
||||
assertFunctionsExist(ctx, t, pool, true, deliveryFunctionNames...)
|
||||
assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, scheduledJobTableNames...)
|
||||
|
||||
identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack, mailQuotaRolledBack := false, false, false, false, false
|
||||
scheduledJobRolledBack := false
|
||||
for rolledBack := 0; ; rolledBack++ {
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
|
||||
@@ -89,6 +94,12 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
|
||||
}
|
||||
if result.Version == scheduledJobMigrationVersion {
|
||||
// The scheduled job migration removes only its own table.
|
||||
assertTablesExist(ctx, t, pool, false, scheduledJobTableNames...)
|
||||
assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...)
|
||||
scheduledJobRolledBack = true
|
||||
}
|
||||
if result.Version == mailQuotaMigrationVersion {
|
||||
// The quota migration removes only its counter table; the
|
||||
// deliveries it does not reference stay.
|
||||
@@ -126,9 +137,10 @@ func TestPostgresMigrations(t *testing.T) {
|
||||
identityRolledBack = true
|
||||
}
|
||||
}
|
||||
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack {
|
||||
t.Fatalf("migrations %d, %d, %d, %d, and %d were not all rolled back",
|
||||
identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion)
|
||||
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack || !scheduledJobRolledBack {
|
||||
t.Fatalf("migrations %d, %d, %d, %d, %d, and %d were not all rolled back",
|
||||
identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion,
|
||||
scheduledJobMigrationVersion)
|
||||
}
|
||||
assertTablesExist(ctx, t, pool, false, outboxTables...)
|
||||
assertTablesExist(ctx, t, pool, false, identityTableNames...)
|
||||
|
||||
@@ -0,0 +1,758 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/worker/jobrunner"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
"lincodex/backend/pkg/testutil"
|
||||
)
|
||||
|
||||
const (
|
||||
jobTestTimeout = 3 * time.Minute
|
||||
// jobTestKind is registered only by the test handler.
|
||||
jobTestKind = "test.effect"
|
||||
// jobTestLease is long in real time: the fake clock alone decides when
|
||||
// a lease expired, and a handler never runs out of it by accident.
|
||||
jobTestLease = time.Minute
|
||||
jobTestBackoff = time.Second
|
||||
jobTestGrace = 2 * time.Second
|
||||
jobTestShortGrace = 200 * time.Millisecond
|
||||
jobTestMaxAttempts = 3
|
||||
// jobTestConcurrentJobs is enough jobs for two workers to overlap.
|
||||
jobTestConcurrentJobs = 40
|
||||
jobEffectsSchema = "job_test"
|
||||
jobEffectsTable = "effects"
|
||||
jobCancelApplication = "job_cancel"
|
||||
)
|
||||
|
||||
var (
|
||||
jobTestStart = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
|
||||
jobEffects = pgx.Identifier{jobEffectsSchema, jobEffectsTable}
|
||||
createJobEffectsTable = fmt.Sprintf(`
|
||||
CREATE SCHEMA %[1]s;
|
||||
-- No unique key: a second effect of a job must stay visible. seq
|
||||
-- records the commit order of the effects.
|
||||
CREATE TABLE %[2]s (
|
||||
seq bigint GENERATED ALWAYS AS IDENTITY,
|
||||
job_id bigint NOT NULL,
|
||||
job_key text NOT NULL,
|
||||
worker text NOT NULL
|
||||
)`, pgx.Identifier{jobEffectsSchema}.Sanitize(), jobEffects.Sanitize())
|
||||
errJobEffectFailed = errors.New("job effect failed")
|
||||
)
|
||||
|
||||
// jobEffectHandler is the test-only handler: it writes one effect row in
|
||||
// the transaction that completes the job, then runs hook in it.
|
||||
type jobEffectHandler struct {
|
||||
worker string
|
||||
hook func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error
|
||||
}
|
||||
|
||||
func (*jobEffectHandler) JobKind() string { return jobTestKind }
|
||||
|
||||
func (handler *jobEffectHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
|
||||
if !ok {
|
||||
return errors.New("unit of work is not a PostgreSQL transaction")
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "INSERT INTO "+jobEffects.Sanitize()+" (job_id, job_key, worker) VALUES ($1, $2, $3)", job.ID, job.Key, handler.worker); err != nil {
|
||||
return err
|
||||
}
|
||||
if handler.hook == nil {
|
||||
return nil
|
||||
}
|
||||
return handler.hook(ctx, unit, job)
|
||||
}
|
||||
|
||||
// jobHarness schedules jobs through the scheduler port and builds workers
|
||||
// the way the application does, each with its own pool, against one
|
||||
// database and one fake clock.
|
||||
type jobHarness struct {
|
||||
env *testEnvironment
|
||||
pool *pgxpool.Pool
|
||||
clock *testutil.FakeClock
|
||||
}
|
||||
|
||||
// jobInstance is one simulated backend process: its own pool, store, and
|
||||
// worker. Dropping it and building another one is a restart.
|
||||
type jobInstance struct {
|
||||
pool *pgxpool.Pool
|
||||
store *postgresadapter.ScheduledJobStore
|
||||
worker *jobrunner.Worker
|
||||
metrics *prometheus.Metrics
|
||||
}
|
||||
|
||||
func jobTestSettings(grace time.Duration) jobrunner.Settings {
|
||||
return jobrunner.Settings{
|
||||
BatchSize: 5,
|
||||
PollInterval: 10 * time.Millisecond,
|
||||
Lease: jobTestLease,
|
||||
MaxAttempts: jobTestMaxAttempts,
|
||||
Backoff: retry.Backoff{Initial: jobTestBackoff, Max: jobTestBackoff},
|
||||
ShutdownGrace: grace,
|
||||
StoreTimeout: 5 * time.Second,
|
||||
BacklogInterval: time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func (harness *jobHarness) start(ctx context.Context, t *testing.T, handler *jobEffectHandler, settings jobrunner.Settings) *jobInstance {
|
||||
t.Helper()
|
||||
pool := harness.env.newPool(ctx, t)
|
||||
store := postgresadapter.NewScheduledJobStore(pool, settings.Lease)
|
||||
metrics := prometheus.New()
|
||||
worker, err := jobrunner.New([]inbound.JobHandler{handler}, store, metrics, slog.New(slog.DiscardHandler), settings, harness.clock.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("jobrunner.New() error = %v", err)
|
||||
}
|
||||
return &jobInstance{pool: pool, store: store, worker: worker, metrics: metrics}
|
||||
}
|
||||
|
||||
// schedule schedules a job of the test kind in its own transaction and
|
||||
// reports whether it was new.
|
||||
func (harness *jobHarness) schedule(ctx context.Context, t *testing.T, key string, dueAt time.Time, maxAttempts int) bool {
|
||||
t.Helper()
|
||||
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{
|
||||
Kind: jobTestKind, Key: key, DueAt: dueAt, MaxAttempts: maxAttempts,
|
||||
Payload: []byte(`{"subject_id":"` + key + `"}`),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewScheduledJob() error = %v", err)
|
||||
}
|
||||
var scheduled bool
|
||||
err = postgresadapter.NewTransactor(harness.pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
scheduled, err = unit.ScheduledJobs().Schedule(ctx, job)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Schedule() error = %v", err)
|
||||
}
|
||||
return scheduled
|
||||
}
|
||||
|
||||
func (harness *jobHarness) cancel(ctx context.Context, t *testing.T, key string) bool {
|
||||
t.Helper()
|
||||
cancelled, err := cancelJob(ctx, harness.pool, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Cancel() error = %v", err)
|
||||
}
|
||||
return cancelled
|
||||
}
|
||||
|
||||
// cancelJob cancels a job of the test kind in its own transaction on pool.
|
||||
func cancelJob(ctx context.Context, pool *pgxpool.Pool, key string) (bool, error) {
|
||||
var cancelled bool
|
||||
err := postgresadapter.NewTransactor(pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
cancelled, err = unit.ScheduledJobs().Cancel(ctx, jobTestKind, key)
|
||||
return err
|
||||
})
|
||||
return cancelled, err
|
||||
}
|
||||
|
||||
// stall claims the one due job with a lease owner of its own, as a worker
|
||||
// that then stops would, and with started also records that its handler
|
||||
// began. It returns the stale claim.
|
||||
func (harness *jobHarness) stall(ctx context.Context, t *testing.T, instance *jobInstance, started bool) outbound.ClaimedJob {
|
||||
t.Helper()
|
||||
claimed, err := instance.store.Claim(ctx, outbound.JobClaim{
|
||||
Owner: uuid.New(), Kinds: []string{jobTestKind}, Now: harness.clock.Now(),
|
||||
Lease: jobTestLease, Limit: 1, DefaultMaxAttempts: jobTestMaxAttempts,
|
||||
})
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("Claim() = %v, %v; want one job", claimed, err)
|
||||
}
|
||||
if !started {
|
||||
return claimed[0]
|
||||
}
|
||||
job, ok, err := instance.store.Start(ctx, claimed[0], harness.clock.Now(), jobTestLease)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("Start() = %t, %v; want started", ok, err)
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
type jobRow struct {
|
||||
id int64
|
||||
status string
|
||||
attempts int
|
||||
dueAt time.Time
|
||||
availableAt time.Time
|
||||
errorClass *string
|
||||
leaseOwner *uuid.UUID
|
||||
}
|
||||
|
||||
func (harness *jobHarness) job(ctx context.Context, t *testing.T, key string) jobRow {
|
||||
t.Helper()
|
||||
var row jobRow
|
||||
err := harness.pool.QueryRow(ctx, `
|
||||
SELECT id, status, attempts, due_at, available_at, last_error_class, lease_owner
|
||||
FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`, jobTestKind, key).
|
||||
Scan(&row.id, &row.status, &row.attempts, &row.dueAt, &row.availableAt, &row.errorClass, &row.leaseOwner)
|
||||
if err != nil {
|
||||
t.Fatalf("read job %s: %v", key, err)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
// effectKeys returns the job keys of the committed effects in commit order.
|
||||
func (harness *jobHarness) effectKeys(ctx context.Context, t *testing.T) []string {
|
||||
t.Helper()
|
||||
rows, err := harness.pool.Query(ctx, "SELECT job_key FROM "+jobEffects.Sanitize()+" ORDER BY seq")
|
||||
if err != nil {
|
||||
t.Fatalf("read effects: %v", err)
|
||||
}
|
||||
keys, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
t.Fatalf("scan effects: %v", err)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func runDueJobs(ctx context.Context, t *testing.T, instance *jobInstance) jobrunner.PassResult {
|
||||
t.Helper()
|
||||
result, err := instance.worker.RunDue(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("RunDue() error = %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// runWorker runs the worker loop until the returned stop is called, which
|
||||
// waits for Run to return.
|
||||
func runWorker(ctx context.Context, t *testing.T, instance *jobInstance) (stop func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
instance.worker.Run(ctx)
|
||||
}()
|
||||
var once sync.Once
|
||||
stop = func() {
|
||||
once.Do(func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-stopped:
|
||||
case <-time.After(consumerStopTimeout):
|
||||
t.Fatal("the job worker did not stop")
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Cleanup(stop)
|
||||
return stop
|
||||
}
|
||||
|
||||
func TestScheduledJobs(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), jobTestTimeout)
|
||||
defer cancel()
|
||||
pool := env.newPool(ctx, t)
|
||||
if _, err := pool.Exec(ctx, createJobEffectsTable); err != nil {
|
||||
t.Fatalf("create test-only tables: %v", err)
|
||||
}
|
||||
// Subtests share the tables and run sequentially; each starts empty
|
||||
// with a fresh clock.
|
||||
reset := func(t *testing.T) *jobHarness {
|
||||
t.Helper()
|
||||
truncateTables(ctx, t, pool, jobEffects, pgx.Identifier{"scheduled_jobs"})
|
||||
return &jobHarness{env: env, pool: pool, clock: testutil.NewFakeClock(jobTestStart)}
|
||||
}
|
||||
|
||||
t.Run("jobs on different dates survive restarts and each runs once in due order", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
inThreeDays, tomorrow := jobTestStart.AddDate(0, 0, 3), jobTestStart.AddDate(0, 0, 1)
|
||||
if !harness.schedule(ctx, t, "later", inThreeDays, 0) || !harness.schedule(ctx, t, "sooner", tomorrow, 0) {
|
||||
t.Fatal("Schedule() did not create the jobs")
|
||||
}
|
||||
// A repeated schedule keeps the first due time.
|
||||
if harness.schedule(ctx, t, "sooner", jobTestStart, 0) {
|
||||
t.Fatal("a repeated Schedule() created a second job")
|
||||
}
|
||||
|
||||
first := harness.start(ctx, t, &jobEffectHandler{worker: "first"}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, first); result.Claimed != 0 {
|
||||
t.Fatalf("a job ran before it was due: %+v", result)
|
||||
}
|
||||
// Restart: the first process is gone with its pool; a new one
|
||||
// finds the jobs in the database.
|
||||
first.pool.Close()
|
||||
second := harness.start(ctx, t, &jobEffectHandler{worker: "second"}, jobTestSettings(jobTestGrace))
|
||||
harness.clock.Advance(24 * time.Hour)
|
||||
if result := runDueJobs(ctx, t, second); result.Done != 1 {
|
||||
t.Fatalf("pass after one day = %+v, want one done job", result)
|
||||
}
|
||||
if result := runDueJobs(ctx, t, second); result.Claimed != 0 {
|
||||
t.Fatalf("a done job ran again: %+v", result)
|
||||
}
|
||||
|
||||
second.pool.Close()
|
||||
third := harness.start(ctx, t, &jobEffectHandler{worker: "third"}, jobTestSettings(jobTestGrace))
|
||||
harness.clock.Advance(48*time.Hour - time.Microsecond)
|
||||
if result := runDueJobs(ctx, t, third); result.Claimed != 0 {
|
||||
t.Fatalf("the later job ran a microsecond early: %+v", result)
|
||||
}
|
||||
harness.clock.Advance(time.Microsecond)
|
||||
if result := runDueJobs(ctx, t, third); result.Done != 1 {
|
||||
t.Fatalf("pass after three days = %+v, want one done job", result)
|
||||
}
|
||||
harness.clock.Advance(30 * 24 * time.Hour)
|
||||
if result := runDueJobs(ctx, t, third); result.Claimed != 0 {
|
||||
t.Fatalf("a done job ran again a month later: %+v", result)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "sooner" || keys[1] != "later" {
|
||||
t.Fatalf("effects = %v, want sooner then later, once each", keys)
|
||||
}
|
||||
for _, key := range []string{"sooner", "later"} {
|
||||
if row := harness.job(ctx, t, key); row.status != "done" || row.attempts != 1 || row.leaseOwner != nil {
|
||||
t.Fatalf("job %s = %+v, want done after one attempt", key, row)
|
||||
}
|
||||
}
|
||||
if !harness.job(ctx, t, "sooner").dueAt.Equal(tomorrow) {
|
||||
t.Fatal("the repeated Schedule() moved the due time")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("two concurrent workers produce exactly one effect per job", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
for index := range jobTestConcurrentJobs {
|
||||
harness.schedule(ctx, t, "job-"+strconv.Itoa(index), jobTestStart.Add(-time.Duration(index)*time.Second), 0)
|
||||
}
|
||||
slow := func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
|
||||
// Keeps the two workers' transactions overlapping.
|
||||
select {
|
||||
case <-time.After(5 * time.Millisecond):
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
left := harness.start(ctx, t, &jobEffectHandler{worker: "left", hook: slow}, jobTestSettings(jobTestGrace))
|
||||
right := harness.start(ctx, t, &jobEffectHandler{worker: "right", hook: slow}, jobTestSettings(jobTestGrace))
|
||||
stopLeft, stopRight := runWorker(ctx, t, left), runWorker(ctx, t, right)
|
||||
waitFor(ctx, t, "every job to be done", func() bool {
|
||||
var done int
|
||||
err := pool.QueryRow(ctx, "SELECT count(*) FROM scheduled_jobs WHERE status = 'done'").Scan(&done)
|
||||
return err == nil && done == jobTestConcurrentJobs
|
||||
})
|
||||
stopLeft()
|
||||
stopRight()
|
||||
|
||||
var total, distinct int
|
||||
var workers []string
|
||||
err := pool.QueryRow(ctx, "SELECT count(*), count(DISTINCT job_id), array_agg(DISTINCT worker) FROM "+jobEffects.Sanitize()).
|
||||
Scan(&total, &distinct, &workers)
|
||||
if err != nil {
|
||||
t.Fatalf("count effects: %v", err)
|
||||
}
|
||||
if total != jobTestConcurrentJobs || distinct != jobTestConcurrentJobs {
|
||||
t.Fatalf("%d effects for %d distinct jobs, want exactly one for each of %d jobs", total, distinct, jobTestConcurrentJobs)
|
||||
}
|
||||
t.Logf("effects were written by workers %v", workers)
|
||||
})
|
||||
|
||||
t.Run("a handler that outlives its lease keeps the job locked and another worker skips it", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "slow", jobTestStart, 0)
|
||||
inEffect, release := make(chan struct{}), make(chan struct{})
|
||||
holder := harness.start(ctx, t, &jobEffectHandler{worker: "holder", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
|
||||
close(inEffect)
|
||||
return awaitOrCancel(ctx, release, nil)
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
other := harness.start(ctx, t, &jobEffectHandler{worker: "other"}, jobTestSettings(jobTestGrace))
|
||||
|
||||
finished := make(chan jobrunner.PassResult, 1)
|
||||
go func() {
|
||||
result, _ := holder.worker.RunDue(ctx)
|
||||
finished <- result
|
||||
}()
|
||||
awaitSignal(ctx, t, inEffect, "the first handler to start")
|
||||
// By the clock the lease expired, but the row is locked by the
|
||||
// running handler, so the claim skips it instead of running the
|
||||
// job a second time.
|
||||
harness.clock.Advance(2 * jobTestLease)
|
||||
if result := runDueJobs(ctx, t, other); result.Claimed != 0 {
|
||||
t.Fatalf("another worker claimed a job whose handler is running: %+v", result)
|
||||
}
|
||||
close(release)
|
||||
if result := <-finished; result.Done != 1 {
|
||||
t.Fatalf("holder pass = %+v, want one done job", result)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 1 {
|
||||
t.Fatalf("effects = %v, want one", keys)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an expired lease is reclaimed by another worker and the late completion is refused", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "abandoned", jobTestStart, 0)
|
||||
stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace))
|
||||
// Worker A starts the job and stops inside it, like a process that
|
||||
// froze or crashed while its handler ran.
|
||||
claimed := harness.stall(ctx, t, stalled, true)
|
||||
reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer"}, jobTestSettings(jobTestGrace))
|
||||
harness.clock.Advance(jobTestLease - time.Microsecond)
|
||||
if result := runDueJobs(ctx, t, reclaimer); result.Claimed != 0 {
|
||||
t.Fatalf("a job was reclaimed before its lease expired: %+v", result)
|
||||
}
|
||||
harness.clock.Advance(time.Microsecond)
|
||||
if result := runDueJobs(ctx, t, reclaimer); result.Done != 1 {
|
||||
t.Fatalf("pass after the lease expired = %+v, want one done job", result)
|
||||
}
|
||||
row := harness.job(ctx, t, "abandoned")
|
||||
if row.status != "done" || row.attempts != 2 || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorLeaseExpired) {
|
||||
t.Fatalf("job = %+v, want done on the second attempt after lease_expired", row)
|
||||
}
|
||||
|
||||
// Worker A wakes up: its start, completion, failure record, and
|
||||
// release are all refused, and its handler never runs.
|
||||
if _, ok, err := stalled.store.Start(ctx, claimed, harness.clock.Now(), jobTestLease); err != nil || ok {
|
||||
t.Fatalf("late Start() = %t, %v; want refused", ok, err)
|
||||
}
|
||||
ran := false
|
||||
err := stalled.store.Run(ctx, claimed, func(context.Context, outbound.UnitOfWork) error {
|
||||
ran = true
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrJobLeaseLost) || ran {
|
||||
t.Fatalf("late Run() = %v, ran %t; want ErrJobLeaseLost without running", err, ran)
|
||||
}
|
||||
if recorded, err := stalled.store.Fail(ctx, claimed, outbound.JobFailure{Class: outbound.JobErrorHandlerFailed, RetryAt: harness.clock.Now()}); err != nil || recorded {
|
||||
t.Fatalf("late Fail() = %t, %v; want refused", recorded, err)
|
||||
}
|
||||
if released, err := stalled.store.Release(ctx, []outbound.ClaimedJob{claimed}); err != nil || len(released) != 0 {
|
||||
t.Fatalf("late Release() = %v, %v; want refused", released, err)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 1 || harness.job(ctx, t, "abandoned").status != "done" {
|
||||
t.Fatalf("effects = %v, want one and the job still done", keys)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a started last attempt whose lease expired makes the job dead without running it", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "crashing", jobTestStart, 1)
|
||||
stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace))
|
||||
harness.stall(ctx, t, stalled, true)
|
||||
calls := 0
|
||||
reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer", hook: func(context.Context, outbound.UnitOfWork, outbound.ClaimedJob) error {
|
||||
calls++
|
||||
return nil
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
harness.clock.Advance(jobTestLease)
|
||||
if result := runDueJobs(ctx, t, reclaimer); result.Dead != 1 || calls != 0 {
|
||||
t.Fatalf("pass = %+v, handler calls %d; want a dead job without a call", result, calls)
|
||||
}
|
||||
row := harness.job(ctx, t, "crashing")
|
||||
if row.status != "dead" || row.attempts != 1 || row.leaseOwner != nil || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorLeaseExpired) {
|
||||
t.Fatalf("job = %+v, want dead after one attempt with lease_expired", row)
|
||||
}
|
||||
assertJobMetric(t, reclaimer.metrics, "dead", 1)
|
||||
})
|
||||
|
||||
t.Run("a claim that never started is reused, so a single allowed attempt is not lost", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "unstarted", jobTestStart, 1)
|
||||
stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace))
|
||||
// Worker A claims the job and stops before it started the handler.
|
||||
harness.stall(ctx, t, stalled, false)
|
||||
reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer"}, jobTestSettings(jobTestGrace))
|
||||
harness.clock.Advance(jobTestLease)
|
||||
if result := runDueJobs(ctx, t, reclaimer); result.Done != 1 {
|
||||
t.Fatalf("pass = %+v, want the job done", result)
|
||||
}
|
||||
if row := harness.job(ctx, t, "unstarted"); row.status != "done" || row.attempts != 1 || row.errorClass != nil {
|
||||
t.Fatalf("job = %+v, want done on its first counted attempt without an error class", row)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a slow job neither starves nor kills the next job of its batch", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "slow", jobTestStart.Add(-time.Minute), 0)
|
||||
harness.schedule(ctx, t, "next", jobTestStart, 1)
|
||||
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(_ context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
if job.Key == "slow" {
|
||||
// The first job runs past the lease the batch was claimed with.
|
||||
harness.clock.Advance(2 * jobTestLease)
|
||||
}
|
||||
return nil
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, worker); result.Claimed != 2 || result.Done != 1 || result.Released != 1 {
|
||||
t.Fatalf("first pass = %+v, want the slow job done and the next one released", result)
|
||||
}
|
||||
if row := harness.job(ctx, t, "next"); row.status != "pending" || row.attempts != 0 || row.leaseOwner != nil {
|
||||
t.Fatalf("next job = %+v, want pending with its attempt intact", row)
|
||||
}
|
||||
if result := runDueJobs(ctx, t, worker); result.Done != 1 {
|
||||
t.Fatalf("second pass = %+v, want the next job done", result)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "slow" || keys[1] != "next" {
|
||||
t.Fatalf("effects = %v, want slow then next", keys)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("another worker runs a job that a busy worker claimed but did not start", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "slow", jobTestStart.Add(-time.Minute), 0)
|
||||
harness.schedule(ctx, t, "waiting", jobTestStart, 1)
|
||||
inSlow, finishSlow := make(chan struct{}), make(chan struct{})
|
||||
busy := harness.start(ctx, t, &jobEffectHandler{worker: "busy", hook: func(ctx context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
if job.Key != "slow" {
|
||||
return nil
|
||||
}
|
||||
close(inSlow)
|
||||
return awaitOrCancel(ctx, finishSlow, nil)
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
other := harness.start(ctx, t, &jobEffectHandler{worker: "other"}, jobTestSettings(jobTestGrace))
|
||||
finished := make(chan jobrunner.PassResult, 1)
|
||||
go func() {
|
||||
result, _ := busy.worker.RunDue(ctx)
|
||||
finished <- result
|
||||
}()
|
||||
awaitSignal(ctx, t, inSlow, "the slow job to start")
|
||||
harness.clock.Advance(2 * jobTestLease)
|
||||
// The slow job is locked by its handler; the waiting job's attempt
|
||||
// never started, so the other worker runs it on that same attempt.
|
||||
if result := runDueJobs(ctx, t, other); result.Claimed != 1 || result.Done != 1 {
|
||||
t.Fatalf("other worker pass = %+v, want only the waiting job, done", result)
|
||||
}
|
||||
close(finishSlow)
|
||||
if result := <-finished; result.Done != 1 || result.LeaseLost != 1 {
|
||||
t.Fatalf("busy worker pass = %+v, want its slow job done and the waiting one lost", result)
|
||||
}
|
||||
if row := harness.job(ctx, t, "waiting"); row.status != "done" || row.attempts != 1 {
|
||||
t.Fatalf("waiting job = %+v, want done on its single attempt", row)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 2 {
|
||||
t.Fatalf("effects = %v, want one per job", keys)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a job that cancels itself is finished and the queue moves on", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "self", jobTestStart.Add(-time.Minute), 0)
|
||||
harness.schedule(ctx, t, "after", jobTestStart, 0)
|
||||
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
if job.Key != "self" {
|
||||
return nil
|
||||
}
|
||||
// An expiry that also cancels the deadline job it stands for.
|
||||
cancelled, err := unit.ScheduledJobs().Cancel(ctx, jobTestKind, job.Key)
|
||||
if err == nil && !cancelled {
|
||||
err = errors.New("the running job was not canceled")
|
||||
}
|
||||
return err
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, worker); result.Done != 2 {
|
||||
t.Fatalf("pass = %+v, want both jobs done", result)
|
||||
}
|
||||
if row := harness.job(ctx, t, "self"); row.status != "cancelled" || row.leaseOwner != nil || row.attempts != 1 {
|
||||
t.Fatalf("self-canceled job = %+v, want cancelled after one attempt", row)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "self" {
|
||||
t.Fatalf("effects = %v, want the self-canceled job's effect committed and the next job run", keys)
|
||||
}
|
||||
if result := runDueJobs(ctx, t, worker); result.Claimed != 0 {
|
||||
t.Fatalf("a self-canceled job was claimed again: %+v", result)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a handler that changes its own job otherwise makes it dead", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "meddling", jobTestStart, 0)
|
||||
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
|
||||
if !ok {
|
||||
return errors.New("unit of work is not a PostgreSQL transaction")
|
||||
}
|
||||
_, err := tx.Exec(ctx, `UPDATE scheduled_jobs
|
||||
SET status = 'done', lease_owner = NULL, lease_expires_at = NULL, started_at = NULL
|
||||
WHERE id = $1`, job.ID)
|
||||
return err
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, worker); result.Dead != 1 {
|
||||
t.Fatalf("pass = %+v, want a dead job", result)
|
||||
}
|
||||
row := harness.job(ctx, t, "meddling")
|
||||
if row.status != "dead" || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorCompletionConflict) {
|
||||
t.Fatalf("job = %+v, want dead with completion_conflict", row)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 0 {
|
||||
t.Fatalf("effects = %v, want the rolled back attempt to leave none", keys)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("graceful shutdown leaves the job not done and reclaimable", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "interrupted", jobTestStart, 0)
|
||||
inEffect := make(chan struct{})
|
||||
stopping := harness.start(ctx, t, &jobEffectHandler{worker: "stopping", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
|
||||
close(inEffect)
|
||||
// Outlasts the shutdown grace.
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}}, jobTestSettings(jobTestShortGrace))
|
||||
stop := runWorker(ctx, t, stopping)
|
||||
awaitSignal(ctx, t, inEffect, "the handler to start")
|
||||
stop()
|
||||
|
||||
// The effect rolled back, the job is not done, and the release
|
||||
// returned it without counting the attempt.
|
||||
row := harness.job(ctx, t, "interrupted")
|
||||
if row.status != "pending" || row.attempts != 0 || row.leaseOwner != nil || row.errorClass != nil {
|
||||
t.Fatalf("job after shutdown = %+v, want pending without an attempt", row)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 0 {
|
||||
t.Fatalf("effects after shutdown = %v, want none", keys)
|
||||
}
|
||||
next := harness.start(ctx, t, &jobEffectHandler{worker: "next"}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, next); result.Done != 1 {
|
||||
t.Fatalf("pass after the restart = %+v, want the job done without waiting for a lease", result)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 1 {
|
||||
t.Fatalf("effects = %v, want one", keys)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a failing job is retried after the backoff and then dead", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "failing", jobTestStart, 2)
|
||||
var seenDueAt []time.Time
|
||||
failing := harness.start(ctx, t, &jobEffectHandler{worker: "failing", hook: func(_ context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
|
||||
seenDueAt = append(seenDueAt, job.DueAt)
|
||||
return errJobEffectFailed
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, failing); result.Retried != 1 {
|
||||
t.Fatalf("first attempt = %+v, want a retry", result)
|
||||
}
|
||||
row := harness.job(ctx, t, "failing")
|
||||
// The retry moves only the claim time; the deadline stays.
|
||||
wait := row.availableAt.Sub(harness.clock.Now())
|
||||
if row.status != "failed" || row.attempts != 1 || wait < jobTestBackoff/2 || wait > jobTestBackoff ||
|
||||
*row.errorClass != string(outbound.JobErrorHandlerFailed) || !row.dueAt.Equal(jobTestStart) {
|
||||
t.Fatalf("job after the first attempt = %+v, retry in %s", row, wait)
|
||||
}
|
||||
if result := runDueJobs(ctx, t, failing); result.Claimed != 0 {
|
||||
t.Fatal("the job was retried before its backoff passed")
|
||||
}
|
||||
harness.clock.Advance(jobTestBackoff)
|
||||
// The per-job limit of two attempts overrides the default of three.
|
||||
if result := runDueJobs(ctx, t, failing); result.Dead != 1 {
|
||||
t.Fatalf("second attempt = %+v, want a dead job", result)
|
||||
}
|
||||
if row := harness.job(ctx, t, "failing"); row.status != "dead" || row.attempts != 2 {
|
||||
t.Fatalf("job = %+v, want dead after two attempts", row)
|
||||
}
|
||||
// The handler saw the deadline on the retry too, not the retry time.
|
||||
if len(seenDueAt) != 2 || !seenDueAt[0].Equal(jobTestStart) || !seenDueAt[1].Equal(jobTestStart) {
|
||||
t.Fatalf("handler saw due times %v, want %s twice", seenDueAt, jobTestStart)
|
||||
}
|
||||
if keys := harness.effectKeys(ctx, t); len(keys) != 0 {
|
||||
t.Fatalf("failed attempts left effects %v", keys)
|
||||
}
|
||||
backlog, err := failing.store.Backlog(ctx, harness.clock.Now())
|
||||
if err != nil || backlog.Dead != 1 || backlog.Due != 0 {
|
||||
t.Fatalf("Backlog() = %+v, %v; want one dead job", backlog, err)
|
||||
}
|
||||
assertJobMetric(t, failing.metrics, "dead", 1)
|
||||
assertJobMetric(t, failing.metrics, "retry", 1)
|
||||
})
|
||||
|
||||
t.Run("a canceled job never runs and its key stays reserved", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "withdrawn", jobTestStart, 0)
|
||||
if !harness.cancel(ctx, t, "withdrawn") {
|
||||
t.Fatal("Cancel() did not cancel a pending job")
|
||||
}
|
||||
if harness.cancel(ctx, t, "withdrawn") || harness.schedule(ctx, t, "withdrawn", jobTestStart, 0) {
|
||||
t.Fatal("a canceled job was canceled or scheduled again")
|
||||
}
|
||||
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker"}, jobTestSettings(jobTestGrace))
|
||||
if result := runDueJobs(ctx, t, worker); result.Claimed != 0 {
|
||||
t.Fatalf("a canceled job was claimed: %+v", result)
|
||||
}
|
||||
backlog, err := worker.store.Backlog(ctx, harness.clock.Now())
|
||||
if err != nil || backlog.Due != 0 {
|
||||
t.Fatalf("Backlog() = %+v, %v; want nothing due", backlog, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a cancel waits for a running handler and then finds the job done", func(t *testing.T) {
|
||||
harness := reset(t)
|
||||
harness.schedule(ctx, t, "racing", jobTestStart, 0)
|
||||
inEffect, release := make(chan struct{}), make(chan struct{})
|
||||
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
|
||||
close(inEffect)
|
||||
return awaitOrCancel(ctx, release, nil)
|
||||
}}, jobTestSettings(jobTestGrace))
|
||||
finished := make(chan jobrunner.PassResult, 1)
|
||||
go func() {
|
||||
result, _ := worker.worker.RunDue(ctx)
|
||||
finished <- result
|
||||
}()
|
||||
awaitSignal(ctx, t, inEffect, "the handler to start")
|
||||
|
||||
cancelPool := env.newPoolWithApplicationName(ctx, t, jobCancelApplication)
|
||||
type cancelResult struct {
|
||||
cancelled bool
|
||||
err error
|
||||
}
|
||||
cancelled := make(chan cancelResult, 1)
|
||||
go func() {
|
||||
result, err := cancelJob(ctx, cancelPool, "racing")
|
||||
cancelled <- cancelResult{cancelled: result, err: err}
|
||||
}()
|
||||
if waitEvent, waiting := waitForLockWait(ctx, pool, jobCancelApplication); !waiting {
|
||||
t.Fatalf("the cancel did not wait for the running handler; last wait event %q", waitEvent)
|
||||
}
|
||||
close(release)
|
||||
if result := <-finished; result.Done != 1 {
|
||||
t.Fatalf("pass = %+v, want the job done", result)
|
||||
}
|
||||
if result := <-cancelled; result.err != nil || result.cancelled {
|
||||
t.Fatalf("Cancel() = %t, %v; want false for a job its handler completed", result.cancelled, result.err)
|
||||
}
|
||||
if row := harness.job(ctx, t, "racing"); row.status != "done" {
|
||||
t.Fatalf("job = %+v, want done", row)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// assertJobMetric reads lincodex_scheduled_jobs_total for the test kind and
|
||||
// one outcome from the scrape output.
|
||||
func assertJobMetric(t *testing.T, metrics *prometheus.Metrics, outcome string, want int) {
|
||||
t.Helper()
|
||||
prefix := fmt.Sprintf(`lincodex_scheduled_jobs_total{kind=%q,outcome=%q} `, jobTestKind, outcome)
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
||||
for line := range strings.SplitSeq(response.Body.String(), "\n") {
|
||||
if value, found := strings.CutPrefix(line, prefix); found {
|
||||
if value != strconv.Itoa(want) {
|
||||
t.Fatalf("%s%s, want %d", prefix, value, want)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("metrics output has no series %s", prefix)
|
||||
}
|
||||
@@ -103,17 +103,24 @@ func (store *EventConsumerStore) ApplyOnce(ctx context.Context, consumer string,
|
||||
//
|
||||
// Connection and network errors pass through as store failures.
|
||||
func classifyCommitError(err error) error {
|
||||
return classifyCommitRefusal(err, outbound.ErrEventEffectRejected)
|
||||
}
|
||||
|
||||
// classifyCommitRefusal is classifyCommitError with the sentinel that a
|
||||
// refused commit matches, so the scheduled job store applies the same rules
|
||||
// with its own port error.
|
||||
func classifyCommitRefusal(err, rejected error) error {
|
||||
if errors.Is(err, pgx.ErrTxCommitRollback) {
|
||||
return fmt.Errorf("postgres.classifyCommitError - transaction was aborted by a failed statement: %w", outbound.ErrEventEffectRejected)
|
||||
return fmt.Errorf("postgres.classifyCommitRefusal - transaction was aborted by a failed statement: %w", rejected)
|
||||
}
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) && len(pgError.Code) == len(deadlockDetectedCode) {
|
||||
safe := &databaseError{code: pgError.Code, constraint: pgError.ConstraintName}
|
||||
switch pgError.Code[:sqlStateClassLength] {
|
||||
case integrityConstraintClass:
|
||||
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrEventEffectRejected, safe)
|
||||
return fmt.Errorf("postgres.classifyCommitRefusal - %w: %w", rejected, safe)
|
||||
case transactionRollbackClass:
|
||||
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrTransactionConflict, safe)
|
||||
return fmt.Errorf("postgres.classifyCommitRefusal - %w: %w", outbound.ErrTransactionConflict, safe)
|
||||
}
|
||||
}
|
||||
return sanitizedDatabaseError(err)
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Job status values that the worker side of the store writes or reads.
|
||||
const (
|
||||
jobStatusFailed = "failed"
|
||||
jobStatusDead = "dead"
|
||||
jobStatusCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// ScheduledJobStore implements outbound.JobStore with a pgx pool owned by
|
||||
// the caller. A claim, a failure, and a release are single statements; each
|
||||
// Run holds one connection and one transaction for the duration of the
|
||||
// handler.
|
||||
type ScheduledJobStore struct {
|
||||
pool *pgxpool.Pool
|
||||
// runTimeout is set as statement_timeout and
|
||||
// idle_in_transaction_session_timeout of every Run transaction.
|
||||
runTimeout time.Duration
|
||||
}
|
||||
|
||||
var _ outbound.JobStore = (*ScheduledJobStore)(nil)
|
||||
|
||||
// NewScheduledJobStore bounds each handler transaction on the server by
|
||||
// runTimeout, the lease duration. The worker's context already ends a live
|
||||
// handler with its lease; the server-side limits also end the transaction of
|
||||
// a worker that froze or lost the network, so the job row lock it holds is
|
||||
// released and the job can be claimed again once the lease expired.
|
||||
func NewScheduledJobStore(pool *pgxpool.Pool, runTimeout time.Duration) *ScheduledJobStore {
|
||||
return &ScheduledJobStore{pool: pool, runTimeout: runTimeout}
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) Claim(ctx context.Context, claim outbound.JobClaim) ([]outbound.ClaimedJob, error) {
|
||||
if claim.Limit <= 0 || claim.Limit > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("ScheduledJobStore.Claim - limit must be between 1 and %d", math.MaxInt32)
|
||||
}
|
||||
if claim.DefaultMaxAttempts <= 0 || claim.DefaultMaxAttempts > domain.MaxScheduledJobAttempts {
|
||||
return nil, fmt.Errorf("ScheduledJobStore.Claim - default max attempts must be between 1 and %d", domain.MaxScheduledJobAttempts)
|
||||
}
|
||||
if len(claim.Kinds) == 0 || claim.Owner == uuid.Nil || claim.Lease <= 0 || claim.Now.IsZero() {
|
||||
return nil, errors.New("ScheduledJobStore.Claim - kinds, owner, lease, and now must be set")
|
||||
}
|
||||
expiresAt := claim.Now.Add(claim.Lease)
|
||||
rows, err := sqlc.New(store.pool).ClaimScheduledJobs(ctx, sqlc.ClaimScheduledJobsParams{
|
||||
LeaseOwner: pgtype.UUID{Bytes: claim.Owner, Valid: true},
|
||||
LeaseExpiresAt: timestamp(expiresAt),
|
||||
DefaultMaxAttempts: int32(claim.DefaultMaxAttempts),
|
||||
Kinds: claim.Kinds,
|
||||
Now: timestamp(claim.Now),
|
||||
BatchLimit: int32(claim.Limit),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ScheduledJobStore.Claim - claim due jobs: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
jobs := make([]outbound.ClaimedJob, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
exhausted := row.Exhausted.Valid && row.Exhausted.Bool
|
||||
job := outbound.ClaimedJob{
|
||||
ID: row.ID,
|
||||
Kind: row.Kind,
|
||||
Key: row.DedupKey,
|
||||
Payload: row.Payload,
|
||||
DueAt: row.DueAt.Time,
|
||||
Attempt: int(row.Attempts),
|
||||
MaxAttempts: int(row.MaxAttempts),
|
||||
Exhausted: exhausted,
|
||||
}
|
||||
if !exhausted {
|
||||
job.LeaseOwner = claim.Owner
|
||||
job.LeaseExpiresAt = expiresAt
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
// UPDATE ... RETURNING does not keep the order of the locking scan.
|
||||
slices.SortFunc(jobs, func(left, right outbound.ClaimedJob) int {
|
||||
return cmp.Or(left.DueAt.Compare(right.DueAt), cmp.Compare(left.ID, right.ID))
|
||||
})
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) Start(ctx context.Context, job outbound.ClaimedJob, now time.Time, lease time.Duration) (outbound.ClaimedJob, bool, error) {
|
||||
guard, err := leaseGuard(job)
|
||||
if err != nil {
|
||||
return outbound.ClaimedJob{}, false, err
|
||||
}
|
||||
if now.IsZero() || lease <= 0 {
|
||||
return outbound.ClaimedJob{}, false, errors.New("ScheduledJobStore.Start - now and lease must be set")
|
||||
}
|
||||
expiresAt := now.Add(lease)
|
||||
started, err := sqlc.New(store.pool).StartScheduledJob(ctx, sqlc.StartScheduledJobParams{
|
||||
LeaseExpiresAt: timestamp(expiresAt),
|
||||
Now: timestamp(now),
|
||||
ID: guard.ID,
|
||||
LeaseOwner: guard.LeaseOwner,
|
||||
Attempt: guard.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.ClaimedJob{}, false, fmt.Errorf("ScheduledJobStore.Start - renew lease: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
if started != 1 {
|
||||
return outbound.ClaimedJob{}, false, nil
|
||||
}
|
||||
job.LeaseExpiresAt = expiresAt
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) Run(ctx context.Context, job outbound.ClaimedJob, apply outbound.ApplyJob) error {
|
||||
// PostgreSQL reads 0 as no limit, so a value below one millisecond would
|
||||
// silently remove the bound.
|
||||
if store.runTimeout < time.Millisecond {
|
||||
return errors.New("ScheduledJobStore.Run - transaction timeout must be at least 1ms")
|
||||
}
|
||||
guard, err := leaseGuard(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ctx.Value(transactionContextKey{}) != nil {
|
||||
return fmt.Errorf("ScheduledJobStore.Run - begin transaction: %w", outbound.ErrNestedTransaction)
|
||||
}
|
||||
tx, err := store.pool.BeginTx(ctx, transactionOptions)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ScheduledJobStore.Run - begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
// Runs only when apply panics; the panic keeps its stack and the
|
||||
// rollback error cannot change that outcome.
|
||||
if !finished {
|
||||
_ = rollback(ctx, tx)
|
||||
}
|
||||
}()
|
||||
|
||||
runErr := store.runInTransaction(ctx, tx, guard, apply)
|
||||
finished = true
|
||||
if runErr != nil {
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return errors.Join(runErr, fmt.Errorf("ScheduledJobStore.Run - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
return runErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("ScheduledJobStore.Run - commit transaction: %w", classifyCommitRefusal(err, outbound.ErrJobEffectRejected))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) runInTransaction(ctx context.Context, tx pgx.Tx, guard jobLeaseGuard, apply outbound.ApplyJob) error {
|
||||
queries := sqlc.New(tx)
|
||||
timeout := milliseconds(store.runTimeout)
|
||||
err := queries.SetScheduledJobTransactionTimeouts(ctx, sqlc.SetScheduledJobTransactionTimeoutsParams{
|
||||
StatementTimeoutMs: timeout,
|
||||
IdleTimeoutMs: timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.runInTransaction - set transaction timeouts: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
_, err = queries.LockClaimedScheduledJob(ctx, sqlc.LockClaimedScheduledJobParams(guard))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("postgres.runInTransaction - lock job: %w", outbound.ErrJobLeaseLost)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.runInTransaction - lock job: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
unit := &UnitOfWork{tx: tx, queries: queries}
|
||||
// The error of apply is returned without a store location, so the
|
||||
// caller keeps its identity; only PostgreSQL text inside it is replaced.
|
||||
if err := apply(context.WithValue(ctx, transactionContextKey{}, true), unit); err != nil {
|
||||
return sanitizeApplyError(markTransactionConflict(err))
|
||||
}
|
||||
completed, err := queries.CompleteScheduledJob(ctx, sqlc.CompleteScheduledJobParams(guard))
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.runInTransaction - complete job: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
if completed == 1 {
|
||||
return nil
|
||||
}
|
||||
return completeChangedJob(ctx, queries, guard.ID)
|
||||
}
|
||||
|
||||
// completeChangedJob decides a completion whose guard no longer matched.
|
||||
// The transaction holds the row lock, so only apply can have changed the
|
||||
// job. A handler that canceled its own job, for example an expiry that
|
||||
// also cancels the deadline it stands for, has finished it: its effect
|
||||
// commits. Any other change is a handler bug that would repeat on every
|
||||
// attempt, so it is a final failure rather than a database failure, which
|
||||
// would release the job and claim it first again on every pass.
|
||||
func completeChangedJob(ctx context.Context, queries *sqlc.Queries, id int64) error {
|
||||
status, err := queries.GetScheduledJobStatus(ctx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("postgres.completeChangedJob - read job status: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
if status == jobStatusCancelled {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("postgres.completeChangedJob - job is %s: %w", status, outbound.ErrJobCompletionConflict)
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) Fail(ctx context.Context, job outbound.ClaimedJob, failure outbound.JobFailure) (bool, error) {
|
||||
guard, err := leaseGuard(job)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if failure.Class == "" {
|
||||
return false, errors.New("ScheduledJobStore.Fail - failure class must be set")
|
||||
}
|
||||
status, retryAt := jobStatusFailed, timestamp(failure.RetryAt)
|
||||
if failure.Dead {
|
||||
// A dead job keeps the time it was last available.
|
||||
status, retryAt = jobStatusDead, pgtype.Timestamptz{}
|
||||
} else if failure.RetryAt.IsZero() {
|
||||
return false, errors.New("ScheduledJobStore.Fail - retry time must be set")
|
||||
}
|
||||
recorded, err := sqlc.New(store.pool).FailScheduledJob(ctx, sqlc.FailScheduledJobParams{
|
||||
Status: status,
|
||||
RetryAt: retryAt,
|
||||
ErrorClass: pgtype.Text{String: string(failure.Class), Valid: true},
|
||||
ID: guard.ID,
|
||||
LeaseOwner: guard.LeaseOwner,
|
||||
Attempt: guard.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("ScheduledJobStore.Fail - record failure: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return recorded == 1, nil
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) Release(ctx context.Context, jobs []outbound.ClaimedJob) ([]int64, error) {
|
||||
if len(jobs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
owner := jobs[0].LeaseOwner
|
||||
ids := make([]int64, 0, len(jobs))
|
||||
attempts := make([]int32, 0, len(jobs))
|
||||
for _, job := range jobs {
|
||||
guard, err := leaseGuard(job)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if job.LeaseOwner != owner {
|
||||
return nil, errors.New("ScheduledJobStore.Release - jobs must share one lease owner")
|
||||
}
|
||||
ids = append(ids, guard.ID)
|
||||
attempts = append(attempts, guard.Attempt)
|
||||
}
|
||||
released, err := sqlc.New(store.pool).ReleaseScheduledJobs(ctx, sqlc.ReleaseScheduledJobsParams{
|
||||
LeaseOwner: pgtype.UUID{Bytes: owner, Valid: true},
|
||||
Ids: ids,
|
||||
Attempts: attempts,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ScheduledJobStore.Release - release jobs: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return released, nil
|
||||
}
|
||||
|
||||
func (store *ScheduledJobStore) Backlog(ctx context.Context, now time.Time) (outbound.JobBacklog, error) {
|
||||
row, err := sqlc.New(store.pool).GetScheduledJobBacklog(ctx, timestamp(now))
|
||||
if err != nil {
|
||||
return outbound.JobBacklog{}, fmt.Errorf("ScheduledJobStore.Backlog - read backlog: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return outbound.JobBacklog{
|
||||
Due: row.DueJobs,
|
||||
OldestDueAge: time.Duration(row.OldestDueAgeSeconds * float64(time.Second)),
|
||||
Dead: row.DeadJobs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// jobLeaseGuard has the field layout of the sqlc lock and completion
|
||||
// parameters, so one value converts to both.
|
||||
type jobLeaseGuard struct {
|
||||
ID int64
|
||||
LeaseOwner pgtype.UUID
|
||||
Attempt int32
|
||||
}
|
||||
|
||||
func leaseGuard(job outbound.ClaimedJob) (jobLeaseGuard, error) {
|
||||
if job.Exhausted || job.LeaseOwner == uuid.Nil || job.Attempt < 1 || job.Attempt > math.MaxInt32 {
|
||||
return jobLeaseGuard{}, errors.New("postgres.leaseGuard - job is not held under a lease")
|
||||
}
|
||||
return jobLeaseGuard{
|
||||
ID: job.ID,
|
||||
LeaseOwner: pgtype.UUID{Bytes: job.LeaseOwner, Valid: true},
|
||||
Attempt: int32(job.Attempt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func timestamp(value time.Time) pgtype.Timestamptz {
|
||||
return pgtype.Timestamptz{Time: value, Valid: true}
|
||||
}
|
||||
|
||||
// scheduledJobWriter schedules jobs in the transaction of its unit of work.
|
||||
type scheduledJobWriter struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) ScheduledJobs() outbound.JobScheduler {
|
||||
return scheduledJobWriter{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (writer scheduledJobWriter) Schedule(ctx context.Context, job domain.ScheduledJob) (bool, error) {
|
||||
if job.Kind() == "" {
|
||||
return false, fmt.Errorf("scheduledJobWriter.Schedule - job was not built by domain.NewScheduledJob: %w", domain.ErrInvalidScheduledJob)
|
||||
}
|
||||
maxAttempts := pgtype.Int4{}
|
||||
if limit := job.MaxAttempts(); limit > 0 && limit <= domain.MaxScheduledJobAttempts {
|
||||
maxAttempts = pgtype.Int4{Int32: int32(limit), Valid: true}
|
||||
}
|
||||
inserted, err := writer.queries.InsertScheduledJob(ctx, sqlc.InsertScheduledJobParams{
|
||||
Kind: job.Kind(),
|
||||
DedupKey: job.Key(),
|
||||
Payload: job.Payload(),
|
||||
DueAt: timestamp(job.DueAt()),
|
||||
MaxAttempts: maxAttempts,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("scheduledJobWriter.Schedule - insert job: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return inserted == 1, nil
|
||||
}
|
||||
|
||||
func (writer scheduledJobWriter) Cancel(ctx context.Context, kind, key string) (bool, error) {
|
||||
cancelled, err := writer.queries.CancelScheduledJob(ctx, sqlc.CancelScheduledJobParams{Kind: kind, DedupKey: key})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("scheduledJobWriter.Cancel - cancel job: %w", sanitizedDatabaseError(err))
|
||||
}
|
||||
return cancelled == 1, nil
|
||||
}
|
||||
@@ -138,6 +138,24 @@ type PolicyVersion struct {
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ScheduledJob struct {
|
||||
ID int64
|
||||
Kind string
|
||||
DedupKey string
|
||||
Payload []byte
|
||||
DueAt pgtype.Timestamptz
|
||||
AvailableAt pgtype.Timestamptz
|
||||
Status string
|
||||
Attempts int32
|
||||
MaxAttempts pgtype.Int4
|
||||
LeaseOwner pgtype.UUID
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
StartedAt pgtype.Timestamptz
|
||||
LastErrorClass pgtype.Text
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -14,6 +14,30 @@ type Querier interface {
|
||||
// Adds recipients to the day and the month row. The caller holds their
|
||||
// locks from LockMailQuotaRows and has checked both limits.
|
||||
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
|
||||
// Cancels a job that has not finished. A job whose handler transaction is
|
||||
// in progress holds its row lock, so the statement waits for it: after the
|
||||
// handler committed the job is done and nothing is canceled; otherwise the
|
||||
// worker finds its lease gone and does not run or complete the job.
|
||||
CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error)
|
||||
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
|
||||
// whose available_at has passed, and running jobs whose lease expired
|
||||
// because their worker stopped without finishing them. Rows that another
|
||||
// worker locks are skipped without waiting. Each claimed job gets the lease
|
||||
// of lease_owner and one more attempt, except a job whose expired attempt
|
||||
// never started its handler: that attempt is reused, so a worker that was
|
||||
// busy with other jobs of its batch costs the job nothing. A job whose
|
||||
// started attempt was abandoned on its last allowed attempt becomes dead
|
||||
// with lease_expired instead, so a job that keeps crashing its worker
|
||||
// stops. now is the application clock.
|
||||
//
|
||||
// The kind filter applies after the index on available_at; when many waiting
|
||||
// jobs belong to kinds without a handler in the claiming process, an index
|
||||
// on (kind, available_at, id) is the next step.
|
||||
ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error)
|
||||
// Completes a job in the transaction of its handler effect. The guard is
|
||||
// the lease owner and the attempt, so a worker that lost its lease cannot
|
||||
// complete the job.
|
||||
CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error)
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
|
||||
// against the committed row, so exactly one of them updates it. The join
|
||||
@@ -51,6 +75,11 @@ type Querier interface {
|
||||
// for the first transaction and then inserts nothing. Existing rows are
|
||||
// neither changed nor locked here.
|
||||
EnsureMailQuotaRows(ctx context.Context, arg EnsureMailQuotaRowsParams) error
|
||||
// Records a failed attempt after its handler transaction rolled back: the
|
||||
// job waits for its retry at retry_at (status failed) or is dead, with a
|
||||
// NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
// completion applies.
|
||||
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
|
||||
// Returns the newest open reservation of a delivery under a provider account
|
||||
// made at or after reserved_since. A retry of the delivery inside the
|
||||
// provider's idempotency window reuses it instead of counting again.
|
||||
@@ -77,6 +106,16 @@ type Querier interface {
|
||||
// clock that set occurred_at.
|
||||
GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error)
|
||||
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
|
||||
// Reads the backlog for metrics without locking: jobs that a worker may
|
||||
// claim at now, how long the earliest of them has waited, and the dead
|
||||
// jobs. The
|
||||
// partial indexes keep the cost proportional to those rows. now is the
|
||||
// application clock.
|
||||
GetScheduledJobBacklog(ctx context.Context, now pgtype.Timestamptz) (GetScheduledJobBacklogRow, error)
|
||||
// Reads the status of a job whose completion found it changed, inside
|
||||
// the handler transaction that holds its row lock: only that transaction
|
||||
// can have changed it, for example by canceling its own job.
|
||||
GetScheduledJobStatus(ctx context.Context, id int64) (string, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
// Stores a record that a consumer could not apply. A second delivery of the
|
||||
@@ -106,6 +145,16 @@ type Querier interface {
|
||||
// commit it returns 0, after a rollback it inserts. So a concurrent duplicate
|
||||
// never runs the effect at the same time as the first delivery.
|
||||
InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error)
|
||||
// Lock order. A job handler runs while its transaction holds the row lock
|
||||
// of the job, and may then lock product rows. A business transaction that
|
||||
// cancels a job should cancel it before it locks the product rows the
|
||||
// handler touches, so both take the locks in the same order.
|
||||
// Schedules a job in the caller's transaction. The first schedule of a
|
||||
// (kind, dedup_key) wins: a repeat, also after the job finished or was
|
||||
// canceled, inserts nothing and reports 0 rows, so a repeated command never
|
||||
// moves a deadline. A concurrent insert of the same key waits for the first
|
||||
// transaction and then inserts nothing, or inserts after its rollback.
|
||||
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
@@ -113,6 +162,11 @@ type Querier interface {
|
||||
// Lists the other accounts of a provider that have usage in a month, so
|
||||
// startup can warn about a renamed EMAIL_ACCOUNT.
|
||||
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
|
||||
// Locks a claimed job for its handler transaction and checks that the lease
|
||||
// still belongs to this attempt. It returns no row when the job was
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
// other workers skip the row, so the handler never runs twice at once.
|
||||
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
|
||||
// Locks the listed window rows until the transaction ends, in
|
||||
// (period_kind, period_start) order, the same order for every caller, and
|
||||
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
|
||||
@@ -168,6 +222,12 @@ type Querier interface {
|
||||
// provider's answer outranks the local count until the window resets. The
|
||||
// count never drops below zero.
|
||||
ReleaseMailQuotaUsage(ctx context.Context, arg ReleaseMailQuotaUsageParams) (int64, error)
|
||||
// Returns claimed jobs that did not finish, at shutdown or after a database
|
||||
// failure outside the handler, so another worker can run them at once
|
||||
// instead of after the lease expires. The attempt is not counted, because
|
||||
// the job did not cause the failure. The same guard as the completion
|
||||
// applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Bounds a consumer transaction on the server, local to the transaction.
|
||||
@@ -183,6 +243,19 @@ type Querier interface {
|
||||
// froze or lost the network without closing the connection. Both settings
|
||||
// are local to the transaction.
|
||||
SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error
|
||||
// Bounds a handler transaction on the server, local to the transaction.
|
||||
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
|
||||
// ends the session of a worker that froze or lost the network inside the
|
||||
// handler, which releases the job row lock so the job can be reclaimed once
|
||||
// its lease expires.
|
||||
SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error
|
||||
// Starts a claimed attempt right before its handler transaction: it renews
|
||||
// the lease from now and records the start, committed on its own. It
|
||||
// changes nothing when the lease already expired by now or no longer
|
||||
// belongs to this attempt, so a job whose turn in the batch came too late is
|
||||
// never started on a lease that another worker may take over. now is the
|
||||
// application clock.
|
||||
StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error)
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: scheduled_job.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const cancelScheduledJob = `-- name: CancelScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
status = 'cancelled',
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
kind = $1
|
||||
AND dedup_key = $2
|
||||
AND status IN ('pending', 'failed', 'running')
|
||||
`
|
||||
|
||||
type CancelScheduledJobParams struct {
|
||||
Kind string
|
||||
DedupKey string
|
||||
}
|
||||
|
||||
// Cancels a job that has not finished. A job whose handler transaction is
|
||||
// in progress holds its row lock, so the statement waits for it: after the
|
||||
// handler committed the job is done and nothing is canceled; otherwise the
|
||||
// worker finds its lease gone and does not run or complete the job.
|
||||
func (q *Queries) CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, cancelScheduledJob, arg.Kind, arg.DedupKey)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const claimScheduledJobs = `-- name: ClaimScheduledJobs :many
|
||||
WITH candidates AS (
|
||||
SELECT
|
||||
candidate.id,
|
||||
(
|
||||
candidate.status = 'running'
|
||||
AND candidate.started_at IS NULL
|
||||
) AS unstarted,
|
||||
(
|
||||
candidate.status = 'running'
|
||||
AND candidate.started_at IS NOT NULL
|
||||
AND candidate.attempts >= coalesce(
|
||||
candidate.max_attempts,
|
||||
$3::integer
|
||||
)
|
||||
) AS exhausted
|
||||
FROM scheduled_jobs AS candidate
|
||||
WHERE
|
||||
candidate.kind = any($4::text [])
|
||||
AND (
|
||||
(
|
||||
candidate.status IN ('pending', 'failed')
|
||||
AND candidate.available_at <= $5::timestamptz
|
||||
)
|
||||
OR (
|
||||
candidate.status = 'running'
|
||||
AND candidate.lease_expires_at <= $5::timestamptz
|
||||
)
|
||||
)
|
||||
ORDER BY candidate.available_at, candidate.id
|
||||
LIMIT $6
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
|
||||
UPDATE scheduled_jobs AS job
|
||||
SET
|
||||
status = CASE WHEN candidates.exhausted THEN 'dead' ELSE 'running' END,
|
||||
attempts = CASE
|
||||
WHEN candidates.exhausted OR candidates.unstarted THEN job.attempts
|
||||
ELSE job.attempts + 1
|
||||
END,
|
||||
lease_owner = CASE
|
||||
WHEN candidates.exhausted THEN NULL ELSE $1::uuid
|
||||
END,
|
||||
lease_expires_at = CASE
|
||||
WHEN
|
||||
candidates.exhausted
|
||||
THEN NULL
|
||||
ELSE $2::timestamptz
|
||||
END,
|
||||
started_at = NULL,
|
||||
last_error_class = CASE
|
||||
WHEN
|
||||
job.status = 'running' AND NOT candidates.unstarted
|
||||
THEN 'lease_expired'
|
||||
ELSE job.last_error_class
|
||||
END,
|
||||
updated_at = clock_timestamp()
|
||||
FROM candidates
|
||||
WHERE job.id = candidates.id
|
||||
RETURNING
|
||||
job.id,
|
||||
job.kind,
|
||||
job.dedup_key,
|
||||
job.payload,
|
||||
job.due_at,
|
||||
job.attempts,
|
||||
coalesce(
|
||||
job.max_attempts, $3::integer
|
||||
)::integer AS max_attempts,
|
||||
candidates.exhausted
|
||||
`
|
||||
|
||||
type ClaimScheduledJobsParams struct {
|
||||
LeaseOwner pgtype.UUID
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
DefaultMaxAttempts int32
|
||||
Kinds []string
|
||||
Now pgtype.Timestamptz
|
||||
BatchLimit int32
|
||||
}
|
||||
|
||||
type ClaimScheduledJobsRow struct {
|
||||
ID int64
|
||||
Kind string
|
||||
DedupKey string
|
||||
Payload []byte
|
||||
DueAt pgtype.Timestamptz
|
||||
Attempts int32
|
||||
MaxAttempts int32
|
||||
Exhausted pgtype.Bool
|
||||
}
|
||||
|
||||
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
|
||||
// whose available_at has passed, and running jobs whose lease expired
|
||||
// because their worker stopped without finishing them. Rows that another
|
||||
// worker locks are skipped without waiting. Each claimed job gets the lease
|
||||
// of lease_owner and one more attempt, except a job whose expired attempt
|
||||
// never started its handler: that attempt is reused, so a worker that was
|
||||
// busy with other jobs of its batch costs the job nothing. A job whose
|
||||
// started attempt was abandoned on its last allowed attempt becomes dead
|
||||
// with lease_expired instead, so a job that keeps crashing its worker
|
||||
// stops. now is the application clock.
|
||||
//
|
||||
// The kind filter applies after the index on available_at; when many waiting
|
||||
// jobs belong to kinds without a handler in the claiming process, an index
|
||||
// on (kind, available_at, id) is the next step.
|
||||
func (q *Queries) ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error) {
|
||||
rows, err := q.db.Query(ctx, claimScheduledJobs,
|
||||
arg.LeaseOwner,
|
||||
arg.LeaseExpiresAt,
|
||||
arg.DefaultMaxAttempts,
|
||||
arg.Kinds,
|
||||
arg.Now,
|
||||
arg.BatchLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ClaimScheduledJobsRow
|
||||
for rows.Next() {
|
||||
var i ClaimScheduledJobsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Kind,
|
||||
&i.DedupKey,
|
||||
&i.Payload,
|
||||
&i.DueAt,
|
||||
&i.Attempts,
|
||||
&i.MaxAttempts,
|
||||
&i.Exhausted,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const completeScheduledJob = `-- name: CompleteScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
status = 'done',
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
id = $1
|
||||
AND status = 'running'
|
||||
AND lease_owner = $2
|
||||
AND attempts = $3
|
||||
`
|
||||
|
||||
type CompleteScheduledJobParams struct {
|
||||
ID int64
|
||||
LeaseOwner pgtype.UUID
|
||||
Attempt int32
|
||||
}
|
||||
|
||||
// Completes a job in the transaction of its handler effect. The guard is
|
||||
// the lease owner and the attempt, so a worker that lost its lease cannot
|
||||
// complete the job.
|
||||
func (q *Queries) CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, completeScheduledJob, arg.ID, arg.LeaseOwner, arg.Attempt)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const failScheduledJob = `-- name: FailScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
status = $1,
|
||||
available_at = coalesce($2, available_at),
|
||||
last_error_class = $3,
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
id = $4
|
||||
AND status = 'running'
|
||||
AND lease_owner = $5
|
||||
AND attempts = $6
|
||||
`
|
||||
|
||||
type FailScheduledJobParams struct {
|
||||
Status string
|
||||
RetryAt pgtype.Timestamptz
|
||||
ErrorClass pgtype.Text
|
||||
ID int64
|
||||
LeaseOwner pgtype.UUID
|
||||
Attempt int32
|
||||
}
|
||||
|
||||
// Records a failed attempt after its handler transaction rolled back: the
|
||||
// job waits for its retry at retry_at (status failed) or is dead, with a
|
||||
// NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
// completion applies.
|
||||
func (q *Queries) FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, failScheduledJob,
|
||||
arg.Status,
|
||||
arg.RetryAt,
|
||||
arg.ErrorClass,
|
||||
arg.ID,
|
||||
arg.LeaseOwner,
|
||||
arg.Attempt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getScheduledJobBacklog = `-- name: GetScheduledJobBacklog :one
|
||||
SELECT
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM scheduled_jobs AS due
|
||||
WHERE
|
||||
due.status IN ('pending', 'failed')
|
||||
AND due.available_at <= $1::timestamptz
|
||||
)::bigint AS due_jobs,
|
||||
coalesce((
|
||||
SELECT
|
||||
extract(EPOCH FROM $1::timestamptz - oldest.available_at)
|
||||
FROM scheduled_jobs AS oldest
|
||||
WHERE
|
||||
oldest.status IN ('pending', 'failed')
|
||||
AND oldest.available_at <= $1::timestamptz
|
||||
ORDER BY oldest.available_at
|
||||
LIMIT 1
|
||||
), 0)::float8 AS oldest_due_age_seconds,
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM scheduled_jobs AS dead
|
||||
WHERE dead.status = 'dead'
|
||||
)::bigint AS dead_jobs
|
||||
`
|
||||
|
||||
type GetScheduledJobBacklogRow struct {
|
||||
DueJobs int64
|
||||
OldestDueAgeSeconds float64
|
||||
DeadJobs int64
|
||||
}
|
||||
|
||||
// Reads the backlog for metrics without locking: jobs that a worker may
|
||||
// claim at now, how long the earliest of them has waited, and the dead
|
||||
// jobs. The
|
||||
// partial indexes keep the cost proportional to those rows. now is the
|
||||
// application clock.
|
||||
func (q *Queries) GetScheduledJobBacklog(ctx context.Context, now pgtype.Timestamptz) (GetScheduledJobBacklogRow, error) {
|
||||
row := q.db.QueryRow(ctx, getScheduledJobBacklog, now)
|
||||
var i GetScheduledJobBacklogRow
|
||||
err := row.Scan(&i.DueJobs, &i.OldestDueAgeSeconds, &i.DeadJobs)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getScheduledJobStatus = `-- name: GetScheduledJobStatus :one
|
||||
SELECT job.status
|
||||
FROM scheduled_jobs AS job
|
||||
WHERE job.id = $1
|
||||
`
|
||||
|
||||
// Reads the status of a job whose completion found it changed, inside
|
||||
// the handler transaction that holds its row lock: only that transaction
|
||||
// can have changed it, for example by canceling its own job.
|
||||
func (q *Queries) GetScheduledJobStatus(ctx context.Context, id int64) (string, error) {
|
||||
row := q.db.QueryRow(ctx, getScheduledJobStatus, id)
|
||||
var status string
|
||||
err := row.Scan(&status)
|
||||
return status, err
|
||||
}
|
||||
|
||||
const insertScheduledJob = `-- name: InsertScheduledJob :execrows
|
||||
|
||||
INSERT INTO scheduled_jobs (
|
||||
kind,
|
||||
dedup_key,
|
||||
payload,
|
||||
due_at,
|
||||
available_at,
|
||||
status,
|
||||
attempts,
|
||||
max_attempts
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$4,
|
||||
'pending',
|
||||
0,
|
||||
$5
|
||||
)
|
||||
ON CONFLICT (kind, dedup_key) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertScheduledJobParams struct {
|
||||
Kind string
|
||||
DedupKey string
|
||||
Payload []byte
|
||||
DueAt pgtype.Timestamptz
|
||||
MaxAttempts pgtype.Int4
|
||||
}
|
||||
|
||||
// Lock order. A job handler runs while its transaction holds the row lock
|
||||
// of the job, and may then lock product rows. A business transaction that
|
||||
// cancels a job should cancel it before it locks the product rows the
|
||||
// handler touches, so both take the locks in the same order.
|
||||
// Schedules a job in the caller's transaction. The first schedule of a
|
||||
// (kind, dedup_key) wins: a repeat, also after the job finished or was
|
||||
// canceled, inserts nothing and reports 0 rows, so a repeated command never
|
||||
// moves a deadline. A concurrent insert of the same key waits for the first
|
||||
// transaction and then inserts nothing, or inserts after its rollback.
|
||||
func (q *Queries) InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertScheduledJob,
|
||||
arg.Kind,
|
||||
arg.DedupKey,
|
||||
arg.Payload,
|
||||
arg.DueAt,
|
||||
arg.MaxAttempts,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const lockClaimedScheduledJob = `-- name: LockClaimedScheduledJob :one
|
||||
SELECT job.id
|
||||
FROM scheduled_jobs AS job
|
||||
WHERE
|
||||
job.id = $1
|
||||
AND job.status = 'running'
|
||||
AND job.lease_owner = $2
|
||||
AND job.attempts = $3
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockClaimedScheduledJobParams struct {
|
||||
ID int64
|
||||
LeaseOwner pgtype.UUID
|
||||
Attempt int32
|
||||
}
|
||||
|
||||
// Locks a claimed job for its handler transaction and checks that the lease
|
||||
// still belongs to this attempt. It returns no row when the job was
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
// other workers skip the row, so the handler never runs twice at once.
|
||||
func (q *Queries) LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, lockClaimedScheduledJob, arg.ID, arg.LeaseOwner, arg.Attempt)
|
||||
var id int64
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const releaseScheduledJobs = `-- name: ReleaseScheduledJobs :many
|
||||
UPDATE scheduled_jobs AS job
|
||||
SET
|
||||
status = CASE
|
||||
WHEN job.last_error_class IS NULL THEN 'pending' ELSE 'failed'
|
||||
END,
|
||||
attempts = job.attempts - 1,
|
||||
lease_owner = NULL,
|
||||
lease_expires_at = NULL,
|
||||
started_at = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
FROM (
|
||||
-- Set-returning functions in one select list advance together, so the
|
||||
-- arrays pair up by position. The two-argument unnest(ids, attempts)
|
||||
-- would say the same, but the sqlc analyzer cannot type it, and
|
||||
-- sqlfluff cannot parse ROWS FROM.
|
||||
SELECT
|
||||
unnest($2::bigint []) AS id,
|
||||
unnest($3::integer []) AS attempt
|
||||
) AS released
|
||||
WHERE
|
||||
job.id = released.id
|
||||
AND job.attempts = released.attempt
|
||||
AND job.status = 'running'
|
||||
AND job.lease_owner = $1
|
||||
RETURNING job.id
|
||||
`
|
||||
|
||||
type ReleaseScheduledJobsParams struct {
|
||||
LeaseOwner pgtype.UUID
|
||||
Ids []int64
|
||||
Attempts []int32
|
||||
}
|
||||
|
||||
// Returns claimed jobs that did not finish, at shutdown or after a database
|
||||
// failure outside the handler, so another worker can run them at once
|
||||
// instead of after the lease expires. The attempt is not counted, because
|
||||
// the job did not cause the failure. The same guard as the completion
|
||||
// applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
func (q *Queries) ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error) {
|
||||
rows, err := q.db.Query(ctx, releaseScheduledJobs, arg.LeaseOwner, arg.Ids, arg.Attempts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setScheduledJobTransactionTimeouts = `-- name: SetScheduledJobTransactionTimeouts :exec
|
||||
SELECT
|
||||
set_config('statement_timeout', $1::text, true),
|
||||
set_config(
|
||||
'idle_in_transaction_session_timeout',
|
||||
$2::text,
|
||||
true
|
||||
)
|
||||
`
|
||||
|
||||
type SetScheduledJobTransactionTimeoutsParams struct {
|
||||
StatementTimeoutMs string
|
||||
IdleTimeoutMs string
|
||||
}
|
||||
|
||||
// Bounds a handler transaction on the server, local to the transaction.
|
||||
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
|
||||
// ends the session of a worker that froze or lost the network inside the
|
||||
// handler, which releases the job row lock so the job can be reclaimed once
|
||||
// its lease expires.
|
||||
func (q *Queries) SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error {
|
||||
_, err := q.db.Exec(ctx, setScheduledJobTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
|
||||
return err
|
||||
}
|
||||
|
||||
const startScheduledJob = `-- name: StartScheduledJob :execrows
|
||||
UPDATE scheduled_jobs
|
||||
SET
|
||||
lease_expires_at = $1,
|
||||
started_at = $2,
|
||||
updated_at = clock_timestamp()
|
||||
WHERE
|
||||
id = $3
|
||||
AND status = 'running'
|
||||
AND lease_owner = $4
|
||||
AND attempts = $5
|
||||
AND lease_expires_at > $2
|
||||
`
|
||||
|
||||
type StartScheduledJobParams struct {
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
Now pgtype.Timestamptz
|
||||
ID int64
|
||||
LeaseOwner pgtype.UUID
|
||||
Attempt int32
|
||||
}
|
||||
|
||||
// Starts a claimed attempt right before its handler transaction: it renews
|
||||
// the lease from now and records the start, committed on its own. It
|
||||
// changes nothing when the lease already expired by now or no longer
|
||||
// belongs to this attempt, so a job whose turn in the batch came too late is
|
||||
// never started on a lease that another worker may take over. now is the
|
||||
// application clock.
|
||||
func (q *Queries) StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, startScheduledJob,
|
||||
arg.LeaseExpiresAt,
|
||||
arg.Now,
|
||||
arg.ID,
|
||||
arg.LeaseOwner,
|
||||
arg.Attempt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -31,6 +31,15 @@ type Metrics struct {
|
||||
// consumerFailures counts every failed consumer operation, including the
|
||||
// last handler attempt before a dead letter, by the stage that failed.
|
||||
consumerFailures *client.CounterVec
|
||||
// scheduledJobs counts claimed scheduled jobs by kind and outcome:
|
||||
// done, retry, dead, lease_lost, or released.
|
||||
scheduledJobs *client.CounterVec
|
||||
// scheduledJobsDue, scheduledJobsOldestDueAge, and scheduledJobsDead
|
||||
// describe the waiting and dead jobs. Every backend instance reports the
|
||||
// same database-wide values, so dashboards aggregate them with max.
|
||||
scheduledJobsDue client.Gauge
|
||||
scheduledJobsOldestDueAge client.Gauge
|
||||
scheduledJobsDead client.Gauge
|
||||
}
|
||||
|
||||
// Outbox relay outcome label values.
|
||||
@@ -44,6 +53,8 @@ const (
|
||||
var (
|
||||
consumerOutcomes = []string{"applied", "duplicate", "ignored", "dead_lettered"}
|
||||
consumerStages = []string{"handler", "store", "poll", "commit"}
|
||||
// scheduledJobOutcomes mirror the jobrunner outcome constants.
|
||||
scheduledJobOutcomes = []string{"done", "retry", "dead", "lease_lost", "released"}
|
||||
)
|
||||
|
||||
func New() *Metrics {
|
||||
@@ -77,11 +88,28 @@ func New() *Metrics {
|
||||
Name: "lincodex_event_consumer_failures_total",
|
||||
Help: "Failed event consumer operations, including the last handler attempt before a dead letter, by stage: handler, store, poll, or commit.",
|
||||
}, []string{"consumer", "stage"})
|
||||
scheduledJobs := client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_scheduled_jobs_total",
|
||||
Help: "Claimed scheduled jobs by kind and outcome: done, retry, dead, lease_lost, or released.",
|
||||
}, []string{"kind", "outcome"})
|
||||
scheduledJobsDue := client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_scheduled_jobs_due",
|
||||
Help: "Scheduled jobs that fell due and wait for a worker, at the last backlog read.",
|
||||
})
|
||||
scheduledJobsOldestDueAge := client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_scheduled_jobs_oldest_due_age_seconds",
|
||||
Help: "How long the earliest waiting scheduled job has been due, by the application clock, at the last backlog read; 0 without due jobs.",
|
||||
})
|
||||
scheduledJobsDead := client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_scheduled_jobs_dead",
|
||||
Help: "Dead scheduled jobs, which need an operator, at the last backlog read.",
|
||||
})
|
||||
registry.MustRegister(
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
requests, latency, relayEvents, relayPending, relayOldestAge,
|
||||
consumerRecords, consumerFailures,
|
||||
scheduledJobs, scheduledJobsDue, scheduledJobsOldestDueAge, scheduledJobsDead,
|
||||
)
|
||||
// Expose both series from the start so rate queries see zero, not absence.
|
||||
relayEvents.WithLabelValues(relayOutcomePublished)
|
||||
@@ -96,9 +124,34 @@ func New() *Metrics {
|
||||
|
||||
consumerRecords: consumerRecords,
|
||||
consumerFailures: consumerFailures,
|
||||
|
||||
scheduledJobs: scheduledJobs,
|
||||
scheduledJobsDue: scheduledJobsDue,
|
||||
scheduledJobsOldestDueAge: scheduledJobsOldestDueAge,
|
||||
scheduledJobsDead: scheduledJobsDead,
|
||||
}
|
||||
}
|
||||
|
||||
// PrepareScheduledJobKind exposes every outcome series of kind at zero, so
|
||||
// an alert on the first dead job sees an increase instead of a new series.
|
||||
func (metrics *Metrics) PrepareScheduledJobKind(kind string) {
|
||||
for _, outcome := range scheduledJobOutcomes {
|
||||
metrics.scheduledJobs.WithLabelValues(kind, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
// ObserveScheduledJob counts the outcome of one claimed job.
|
||||
func (metrics *Metrics) ObserveScheduledJob(kind, outcome string) {
|
||||
metrics.scheduledJobs.WithLabelValues(kind, outcome).Inc()
|
||||
}
|
||||
|
||||
// ObserveScheduledJobBacklog records the latest backlog read.
|
||||
func (metrics *Metrics) ObserveScheduledJobBacklog(backlog outbound.JobBacklog) {
|
||||
metrics.scheduledJobsDue.Set(float64(backlog.Due))
|
||||
metrics.scheduledJobsOldestDueAge.Set(backlog.OldestDueAge.Seconds())
|
||||
metrics.scheduledJobsDead.Set(float64(backlog.Dead))
|
||||
}
|
||||
|
||||
// PrepareEventConsumer exposes every series of consumer at zero, so an alert
|
||||
// on the first dead letter sees an increase instead of a new series.
|
||||
func (metrics *Metrics) PrepareEventConsumer(consumer string) {
|
||||
|
||||
@@ -86,3 +86,27 @@ func TestMetricsHandlerExposesEventConsumerOutcomes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesScheduledJobs(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.PrepareScheduledJobKind("invitation.response_deadline")
|
||||
metrics.ObserveScheduledJob("invitation.response_deadline", "done")
|
||||
metrics.ObserveScheduledJob("invitation.response_deadline", "done")
|
||||
metrics.ObserveScheduledJobBacklog(outbound.JobBacklog{Due: 7, OldestDueAge: 2 * time.Minute, Dead: 1})
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
|
||||
body := response.Body.String()
|
||||
for _, want := range []string{
|
||||
`lincodex_scheduled_jobs_total{kind="invitation.response_deadline",outcome="done"} 2`,
|
||||
// Prepared at zero, so an alert sees the first dead job as an increase.
|
||||
`lincodex_scheduled_jobs_total{kind="invitation.response_deadline",outcome="dead"} 0`,
|
||||
"lincodex_scheduled_jobs_due 7",
|
||||
"lincodex_scheduled_jobs_oldest_due_age_seconds 120",
|
||||
"lincodex_scheduled_jobs_dead 1",
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -49,6 +49,7 @@ func initialize(
|
||||
httpadapter.NewRouter,
|
||||
newOutboxRelay,
|
||||
newEventConsumers,
|
||||
newJobWorker,
|
||||
NewApplication,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxScheduledJobPayloadBytes bounds the compact JSON payload. A job
|
||||
// carries identifiers only; its handler reads everything else from the
|
||||
// source tables under the access rules in force when it runs.
|
||||
MaxScheduledJobPayloadBytes = 2 << 10
|
||||
// MaxScheduledJobAttempts bounds a per-job attempt limit.
|
||||
MaxScheduledJobAttempts = 100
|
||||
maxScheduledJobKindLength = 64
|
||||
maxScheduledJobKeyLength = 128
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidScheduledJob = errors.New("invalid scheduled job")
|
||||
|
||||
// Lowercase snake_case names, optionally dotted, such as
|
||||
// "invitation.response_deadline".
|
||||
scheduledJobKindPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$`)
|
||||
// Opaque keys such as a UUID or "<uuid>:<version>". The alphabet leaves
|
||||
// out "@" and spaces, so an email address or a name cannot be a key.
|
||||
scheduledJobKeyPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]*$`)
|
||||
)
|
||||
|
||||
// ScheduledJob is a job that a usecase schedules in its business
|
||||
// transaction, to run once when it falls due.
|
||||
//
|
||||
// Kind names the handler. Key identifies the logical job within its kind:
|
||||
// the first schedule of a (kind, key) pair wins and a repeat does nothing,
|
||||
// also after the job ran or was canceled, so a key must change whenever a
|
||||
// new occurrence is wanted, for example "<aggregate id>:<version>". Neither
|
||||
// the key nor the payload may contain personal data: both are stored next
|
||||
// to operator diagnostics, and the payload carries identifiers only.
|
||||
type ScheduledJob struct {
|
||||
kind string
|
||||
key string
|
||||
dueAt time.Time
|
||||
payload []byte
|
||||
maxAttempts int
|
||||
}
|
||||
|
||||
// ScheduledJobInput describes a new job. DueAt comes from the application
|
||||
// clock. Payload is a flat JSON object of strings, numbers, booleans, or
|
||||
// nulls of at most MaxScheduledJobPayloadBytes in compact form; nil means
|
||||
// an empty object. MaxAttempts is zero for the worker default.
|
||||
type ScheduledJobInput struct {
|
||||
Kind string
|
||||
Key string
|
||||
DueAt time.Time
|
||||
Payload []byte
|
||||
MaxAttempts int
|
||||
}
|
||||
|
||||
// NewScheduledJob validates input. The due time is kept in UTC at the
|
||||
// microsecond precision that PostgreSQL stores.
|
||||
func NewScheduledJob(input ScheduledJobInput) (ScheduledJob, error) {
|
||||
if err := ValidateScheduledJobKind(input.Kind); err != nil {
|
||||
return ScheduledJob{}, err
|
||||
}
|
||||
if len(input.Key) > maxScheduledJobKeyLength || !scheduledJobKeyPattern.MatchString(input.Key) {
|
||||
return ScheduledJob{}, invalidScheduledJob("key must be 1 to 128 letters, digits, dots, underscores, colons, or hyphens")
|
||||
}
|
||||
if input.DueAt.IsZero() {
|
||||
return ScheduledJob{}, invalidScheduledJob("due time must be set")
|
||||
}
|
||||
if input.MaxAttempts < 0 || input.MaxAttempts > MaxScheduledJobAttempts {
|
||||
return ScheduledJob{}, invalidScheduledJob("max attempts must be between 0 and 100")
|
||||
}
|
||||
payload, err := scheduledJobPayload(input.Payload)
|
||||
if err != nil {
|
||||
return ScheduledJob{}, err
|
||||
}
|
||||
return ScheduledJob{
|
||||
kind: input.Kind,
|
||||
key: input.Key,
|
||||
dueAt: input.DueAt.UTC().Truncate(time.Microsecond),
|
||||
payload: payload,
|
||||
maxAttempts: input.MaxAttempts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateScheduledJobKind checks a job kind name. The worker applies it to
|
||||
// the kinds of its handlers too.
|
||||
func ValidateScheduledJobKind(kind string) error {
|
||||
if len(kind) > maxScheduledJobKindLength || !scheduledJobKindPattern.MatchString(kind) {
|
||||
return invalidScheduledJob("kind must be a lowercase dotted name of at most 64 bytes")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scheduledJobPayload(payload []byte) ([]byte, error) {
|
||||
if payload == nil {
|
||||
return []byte("{}"), nil
|
||||
}
|
||||
// encoding/json accepts invalid UTF-8 inside strings; PostgreSQL does not.
|
||||
if !utf8.Valid(payload) {
|
||||
return nil, invalidScheduledJob("payload must be valid UTF-8")
|
||||
}
|
||||
var compact bytes.Buffer
|
||||
if err := json.Compact(&compact, payload); err != nil {
|
||||
return nil, invalidScheduledJob("payload must be valid JSON")
|
||||
}
|
||||
if compact.Len() > MaxScheduledJobPayloadBytes {
|
||||
return nil, invalidScheduledJob("payload exceeds 2 KiB")
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(compact.Bytes(), &fields); err != nil || fields == nil {
|
||||
return nil, invalidScheduledJob("payload must be a JSON object with numbers that fit a float64")
|
||||
}
|
||||
for name, value := range fields {
|
||||
text, isText := value.(string)
|
||||
switch {
|
||||
case strings.ContainsRune(name, 0), isText && strings.ContainsRune(text, 0):
|
||||
return nil, invalidScheduledJob("payload must not contain NUL characters")
|
||||
case isScalar(value):
|
||||
default:
|
||||
return nil, invalidScheduledJob("payload values must be strings, numbers, booleans, or null")
|
||||
}
|
||||
}
|
||||
return compact.Bytes(), nil
|
||||
}
|
||||
|
||||
func isScalar(value any) bool {
|
||||
switch value.(type) {
|
||||
case nil, string, float64, bool:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func invalidScheduledJob(reason string) error {
|
||||
return fmt.Errorf("domain.NewScheduledJob - %s: %w", reason, ErrInvalidScheduledJob)
|
||||
}
|
||||
|
||||
func (job ScheduledJob) Kind() string { return job.kind }
|
||||
func (job ScheduledJob) Key() string { return job.key }
|
||||
func (job ScheduledJob) DueAt() time.Time { return job.dueAt }
|
||||
func (job ScheduledJob) Payload() json.RawMessage { return bytes.Clone(job.payload) }
|
||||
|
||||
// MaxAttempts is zero when the worker default applies.
|
||||
func (job ScheduledJob) MaxAttempts() int { return job.maxAttempts }
|
||||
@@ -0,0 +1,94 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func validScheduledJobInput() ScheduledJobInput {
|
||||
return ScheduledJobInput{
|
||||
Kind: "invitation.response_deadline",
|
||||
Key: "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d",
|
||||
DueAt: time.Date(2026, 10, 13, 9, 0, 0, 123456789, time.FixedZone("MSK", 3*60*60)),
|
||||
Payload: []byte(` { "invitation_id" : "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d", "version": 2 } `),
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewScheduledJobNormalizesValidInput(t *testing.T) {
|
||||
input := validScheduledJobInput()
|
||||
job, err := NewScheduledJob(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewScheduledJob() error = %v", err)
|
||||
}
|
||||
if job.Kind() != input.Kind || job.Key() != input.Key || job.MaxAttempts() != 0 {
|
||||
t.Fatalf("NewScheduledJob() did not keep the identity: %+v", job)
|
||||
}
|
||||
// PostgreSQL keeps microseconds, so a stored job compares equal.
|
||||
if want := time.Date(2026, 10, 13, 6, 0, 0, 123456000, time.UTC); !job.DueAt().Equal(want) || job.DueAt().Location() != time.UTC {
|
||||
t.Fatalf("DueAt() = %s, want %s in UTC", job.DueAt(), want)
|
||||
}
|
||||
if want := `{"invitation_id":"0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d","version":2}`; string(job.Payload()) != want {
|
||||
t.Fatalf("Payload() = %s, want %s", job.Payload(), want)
|
||||
}
|
||||
job.Payload()[0] = '['
|
||||
if job.Payload()[0] != '{' {
|
||||
t.Fatal("Payload() exposed the job's internal buffer")
|
||||
}
|
||||
|
||||
input.Payload = nil
|
||||
input.MaxAttempts = MaxScheduledJobAttempts
|
||||
job, err = NewScheduledJob(input)
|
||||
if err != nil || string(job.Payload()) != "{}" || job.MaxAttempts() != MaxScheduledJobAttempts {
|
||||
t.Fatalf("NewScheduledJob() without a payload = %s, %d, %v; want {}", job.Payload(), job.MaxAttempts(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewScheduledJobRejectsInvalidInput(t *testing.T) {
|
||||
prefix, suffix := `{"padding":"`, `"}`
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*ScheduledJobInput)
|
||||
}{
|
||||
{name: "empty kind", change: func(input *ScheduledJobInput) { input.Kind = "" }},
|
||||
{name: "uppercase kind", change: func(input *ScheduledJobInput) { input.Kind = "Invitation.deadline" }},
|
||||
{name: "empty kind segment", change: func(input *ScheduledJobInput) { input.Kind = "invitation..deadline" }},
|
||||
{name: "long kind", change: func(input *ScheduledJobInput) { input.Kind = strings.Repeat("k", 65) }},
|
||||
{name: "empty key", change: func(input *ScheduledJobInput) { input.Key = "" }},
|
||||
{name: "email as key", change: func(input *ScheduledJobInput) { input.Key = "person@example.com" }},
|
||||
{name: "key with a space", change: func(input *ScheduledJobInput) { input.Key = "a b" }},
|
||||
{name: "long key", change: func(input *ScheduledJobInput) { input.Key = strings.Repeat("k", 129) }},
|
||||
{name: "zero due time", change: func(input *ScheduledJobInput) { input.DueAt = time.Time{} }},
|
||||
{name: "negative attempts", change: func(input *ScheduledJobInput) { input.MaxAttempts = -1 }},
|
||||
{name: "too many attempts", change: func(input *ScheduledJobInput) { input.MaxAttempts = MaxScheduledJobAttempts + 1 }},
|
||||
{name: "array payload", change: func(input *ScheduledJobInput) { input.Payload = []byte(`["id"]`) }},
|
||||
{name: "null payload", change: func(input *ScheduledJobInput) { input.Payload = []byte(`null`) }},
|
||||
{name: "nested payload", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"user":{"id":"1"}}`) }},
|
||||
{name: "invalid JSON", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"id":`) }},
|
||||
{name: "invalid UTF-8", change: func(input *ScheduledJobInput) { input.Payload = []byte("{\"id\":\"\xff\"}") }},
|
||||
{name: "NUL in a value", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"id":"a\u0000b"}`) }},
|
||||
{name: "number out of range", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"n":1e400}`) }},
|
||||
{name: "payload over the limit", change: func(input *ScheduledJobInput) {
|
||||
input.Payload = []byte(prefix + strings.Repeat("a", MaxScheduledJobPayloadBytes-len(prefix)-len(suffix)+1) + suffix)
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := validScheduledJobInput()
|
||||
test.change(&input)
|
||||
if _, err := NewScheduledJob(input); !errors.Is(err, ErrInvalidScheduledJob) {
|
||||
t.Fatalf("NewScheduledJob() error = %v, want ErrInvalidScheduledJob", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewScheduledJobAcceptsPayloadAtSizeLimit(t *testing.T) {
|
||||
input := validScheduledJobInput()
|
||||
prefix, suffix := `{"padding":"`, `"}`
|
||||
input.Payload = []byte(prefix + strings.Repeat("a", MaxScheduledJobPayloadBytes-len(prefix)-len(suffix)) + suffix)
|
||||
if _, err := NewScheduledJob(input); err != nil {
|
||||
t.Fatalf("NewScheduledJob() rejected a payload at the limit: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package inbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// ErrJobRejected marks a handler failure that a retry cannot fix, for
|
||||
// example a payload that breaks the contract of its kind. The worker makes
|
||||
// the job dead at once instead of retrying it.
|
||||
var ErrJobRejected = errors.New("scheduled job rejected by handler")
|
||||
|
||||
// JobHandler runs scheduled jobs of one kind when they fall due. The worker
|
||||
// calls Handle inside the transaction that marks the job done, so a
|
||||
// database-only effect and the completion commit together and a job is
|
||||
// applied once even when workers race or restart. An effect outside the
|
||||
// database, such as a call to another service, can repeat after a crash
|
||||
// and must be idempotent on its own.
|
||||
type JobHandler interface {
|
||||
// JobKind is the stable kind name the handler runs, a lowercase dotted
|
||||
// name of at most 64 bytes. Renaming it strands the scheduled jobs of
|
||||
// the old name.
|
||||
JobKind() string
|
||||
// Handle runs job with unit and the context it receives only. The
|
||||
// context ends when the lease does. A handler decides by job.DueAt, the
|
||||
// deadline the job stands for, which retries keep, rather than by the
|
||||
// time it happens to run. An error rolls back the effect; one matching ErrJobRejected is
|
||||
// final, any other is retried with backoff a bounded number of times.
|
||||
// Errors must not quote the payload or personal data; the worker logs
|
||||
// a sanitized reason and stores only a bounded class.
|
||||
Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrJobLeaseLost reports that a claimed job no longer belongs to the
|
||||
// attempt: it was canceled, or another worker reclaimed it after the
|
||||
// lease expired. Nothing of the attempt was committed.
|
||||
ErrJobLeaseLost = errors.New("scheduled job lease lost")
|
||||
|
||||
// ErrJobEffectRejected reports that PostgreSQL refused to commit the
|
||||
// effect of a job handler that returned nil: the handler ignored a
|
||||
// failed statement, or a deferred integrity constraint failed at commit.
|
||||
// Nothing was committed, and the worker counts it as a failed attempt.
|
||||
ErrJobEffectRejected = errors.New("scheduled job effect rejected by the database")
|
||||
|
||||
// ErrJobCompletionConflict reports that the handler transaction left its
|
||||
// own job in a state that the completion cannot accept, other than
|
||||
// canceling it. Nothing was committed; retrying would repeat it, so the
|
||||
// worker makes the job dead.
|
||||
ErrJobCompletionConflict = errors.New("scheduled job changed by its own handler")
|
||||
)
|
||||
|
||||
// JobScheduler schedules and cancels jobs in the caller's transaction, so a
|
||||
// job exists exactly when the business change that needs it committed.
|
||||
//
|
||||
// A job handler runs while it holds the row lock of its job and may then
|
||||
// lock product rows. A transaction that cancels a job should cancel it
|
||||
// before it locks the rows that the handler touches; the opposite order can
|
||||
// deadlock with a running handler, which PostgreSQL resolves by aborting one
|
||||
// side with ErrTransactionConflict.
|
||||
type JobScheduler interface {
|
||||
// Schedule inserts job unless its (kind, key) pair exists, in any state:
|
||||
// the first schedule wins and a repeat reports scheduled=false without
|
||||
// changing the due time or the payload. A concurrent schedule of the
|
||||
// same pair waits for the first transaction.
|
||||
Schedule(ctx context.Context, job domain.ScheduledJob) (scheduled bool, err error)
|
||||
// Cancel stops a job that has not finished and reports whether it did.
|
||||
// When the job's handler transaction is in progress, Cancel waits for
|
||||
// it: after its commit the job is done and Cancel reports false. A
|
||||
// canceled job keeps its key reserved, so a later Schedule of the same
|
||||
// pair does nothing.
|
||||
Cancel(ctx context.Context, kind, key string) (cancelled bool, err error)
|
||||
}
|
||||
|
||||
// JobErrorClass is the bounded cause of a failed or abandoned attempt. It is
|
||||
// stored with the job and never carries handler text.
|
||||
type JobErrorClass string
|
||||
|
||||
const (
|
||||
// JobErrorHandlerFailed: the handler returned an error; retried.
|
||||
JobErrorHandlerFailed JobErrorClass = "handler_failed"
|
||||
// JobErrorHandlerRejected: the handler can never run the job; final.
|
||||
JobErrorHandlerRejected JobErrorClass = "handler_rejected"
|
||||
// JobErrorHandlerPanic: the handler panicked; final.
|
||||
JobErrorHandlerPanic JobErrorClass = "handler_panic"
|
||||
// JobErrorTimeout: the attempt outlasted its lease; retried.
|
||||
JobErrorTimeout JobErrorClass = "timeout"
|
||||
// JobErrorConflict: a deadlock or serialization failure; retried.
|
||||
JobErrorConflict JobErrorClass = "conflict"
|
||||
// JobErrorEffectRejected: PostgreSQL refused the commit; retried.
|
||||
JobErrorEffectRejected JobErrorClass = "effect_rejected"
|
||||
// JobErrorLeaseExpired: the worker stopped without finishing a started
|
||||
// attempt, and a later claim found its lease expired.
|
||||
JobErrorLeaseExpired JobErrorClass = "lease_expired"
|
||||
// JobErrorCompletionConflict: the handler left its own job in a state
|
||||
// the completion cannot accept; final.
|
||||
JobErrorCompletionConflict JobErrorClass = "completion_conflict"
|
||||
)
|
||||
|
||||
// JobClaim asks for due jobs. Now is the application clock; the database
|
||||
// clock never decides whether a job is due or a lease expired.
|
||||
type JobClaim struct {
|
||||
// Owner identifies the worker instance in the lease.
|
||||
Owner uuid.UUID
|
||||
// Kinds are the kinds the worker has handlers for. Jobs of other kinds
|
||||
// stay untouched, so an instance without a newer handler leaves those
|
||||
// jobs to instances that have it.
|
||||
Kinds []string
|
||||
Now time.Time
|
||||
// Lease is how long a claimed job belongs to Owner.
|
||||
Lease time.Duration
|
||||
// Limit bounds the jobs of one claim.
|
||||
Limit int
|
||||
// DefaultMaxAttempts applies to jobs scheduled without their own limit.
|
||||
DefaultMaxAttempts int
|
||||
}
|
||||
|
||||
// ClaimedJob is one job of a claim.
|
||||
type ClaimedJob struct {
|
||||
ID int64
|
||||
Kind string
|
||||
Key string
|
||||
Payload json.RawMessage
|
||||
// DueAt is the deadline the job stands for, as scheduled. Retries keep
|
||||
// it; only the time the job may be claimed again moves.
|
||||
DueAt time.Time
|
||||
// Attempt counts this attempt; the first one is 1.
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
LeaseOwner uuid.UUID
|
||||
// LeaseExpiresAt is by the application clock.
|
||||
LeaseExpiresAt time.Time
|
||||
// Exhausted reports a running job whose lease expired on its last
|
||||
// allowed attempt. The claim made it dead; it must not run.
|
||||
Exhausted bool
|
||||
}
|
||||
|
||||
// JobFailure records a failed attempt.
|
||||
type JobFailure struct {
|
||||
Class JobErrorClass
|
||||
// Dead ends the job; otherwise it may be claimed again at RetryAt.
|
||||
Dead bool
|
||||
RetryAt time.Time
|
||||
}
|
||||
|
||||
// JobBacklog describes waiting and dead jobs at one moment.
|
||||
type JobBacklog struct {
|
||||
// Due counts jobs that a worker may claim now: due, or due for their
|
||||
// retry.
|
||||
Due int64
|
||||
// OldestDueAge is how long the earliest of them has waited; zero
|
||||
// without such jobs.
|
||||
OldestDueAge time.Duration
|
||||
// Dead counts dead jobs, which need an operator.
|
||||
Dead int64
|
||||
}
|
||||
|
||||
// ApplyJob runs the handler of one job inside the transaction that
|
||||
// completes it.
|
||||
type ApplyJob func(ctx context.Context, unit UnitOfWork) error
|
||||
|
||||
// JobStore keeps scheduled jobs for the worker.
|
||||
type JobStore interface {
|
||||
// Claim leases up to claim.Limit jobs that may be claimed at claim.Now
|
||||
// (due, or due for their retry) in one atomic statement, skipping rows
|
||||
// that another worker locks, and counts one attempt for each. Running
|
||||
// jobs whose lease expired by claim.Now are claimed again; an expired
|
||||
// attempt that never started is reused rather than counted again. Jobs
|
||||
// are returned in due order.
|
||||
Claim(ctx context.Context, claim JobClaim) ([]ClaimedJob, error)
|
||||
// Start renews the lease of a claimed job from now and records that its
|
||||
// attempt started, committed on its own, right before Run. started is
|
||||
// false, with nothing changed, when the lease expired by now or no
|
||||
// longer belongs to the attempt; the job must not run then. The
|
||||
// returned job carries the new lease expiry.
|
||||
Start(ctx context.Context, job ClaimedJob, now time.Time, lease time.Duration) (started ClaimedJob, ok bool, err error)
|
||||
// Run opens a transaction, locks job, checks that its lease still
|
||||
// belongs to this attempt, runs apply, marks the job done, and commits,
|
||||
// so the effect of apply and the completion commit together. When apply
|
||||
// canceled the job itself through the unit, the effect commits and the
|
||||
// job stays cancelled; any other change of the job by apply rolls back
|
||||
// and returns ErrJobCompletionConflict. A lost lease returns
|
||||
// ErrJobLeaseLost without calling apply. An error from
|
||||
// apply rolls back and keeps its identity, with any PostgreSQL text
|
||||
// replaced. A commit that PostgreSQL refuses matches
|
||||
// ErrJobEffectRejected, and a deadlock or serialization failure
|
||||
// ErrTransactionConflict.
|
||||
Run(ctx context.Context, job ClaimedJob, apply ApplyJob) error
|
||||
// Fail records a failed attempt of job if its lease still belongs to the
|
||||
// attempt, and reports whether it did.
|
||||
Fail(ctx context.Context, job ClaimedJob, failure JobFailure) (bool, error)
|
||||
// Release returns jobs whose attempts did not finish to the waiting
|
||||
// state without counting the attempts, skipping jobs whose lease no
|
||||
// longer belongs to the attempt, and returns the IDs it released.
|
||||
Release(ctx context.Context, jobs []ClaimedJob) (released []int64, err error)
|
||||
// Backlog reads the due and dead jobs at now without locking them.
|
||||
Backlog(ctx context.Context, now time.Time) (JobBacklog, error)
|
||||
}
|
||||
@@ -54,6 +54,7 @@ type UnitOfWork interface {
|
||||
MailRequests() MailRequestRepository
|
||||
MailQuotas() MailQuotaRepository
|
||||
Outbox() OutboxWriter
|
||||
ScheduledJobs() JobScheduler
|
||||
}
|
||||
|
||||
// OutboxWriter appends domain events to the transactional outbox. Events become
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
// Package testutil holds small test helpers that several backend packages
|
||||
// share. It has no production callers.
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FakeClock is a manual application clock for tests. Code under test takes
|
||||
// its Now method as its clock function, and the test moves time with
|
||||
// Advance or Set instead of waiting, so a deadline days away is checked in
|
||||
// microseconds. It is safe for concurrent use, so a worker goroutine can
|
||||
// read it while the test moves it.
|
||||
type FakeClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
}
|
||||
|
||||
// NewFakeClock returns a clock that stands at start until it is moved.
|
||||
func NewFakeClock(start time.Time) *FakeClock {
|
||||
return &FakeClock{now: start}
|
||||
}
|
||||
|
||||
// Now returns the current fake time. Its signature matches the
|
||||
// func() time.Time clocks that the backend injects.
|
||||
func (clock *FakeClock) Now() time.Time {
|
||||
clock.mu.Lock()
|
||||
defer clock.mu.Unlock()
|
||||
return clock.now
|
||||
}
|
||||
|
||||
// Advance moves the clock forward by step and returns the new time. A
|
||||
// negative step panics, because application clocks are expected to be
|
||||
// monotonic in tests; use Set to model a clock that jumps back.
|
||||
func (clock *FakeClock) Advance(step time.Duration) time.Time {
|
||||
if step < 0 {
|
||||
panic("testutil.FakeClock.Advance - step must not be negative")
|
||||
}
|
||||
clock.mu.Lock()
|
||||
defer clock.mu.Unlock()
|
||||
clock.now = clock.now.Add(step)
|
||||
return clock.now
|
||||
}
|
||||
|
||||
// Set moves the clock to now, forward or back.
|
||||
func (clock *FakeClock) Set(now time.Time) {
|
||||
clock.mu.Lock()
|
||||
defer clock.mu.Unlock()
|
||||
clock.now = now
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFakeClockMovesOnlyWhenTold(t *testing.T) {
|
||||
start := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
||||
clock := NewFakeClock(start)
|
||||
if !clock.Now().Equal(start) {
|
||||
t.Fatalf("Now() = %s, want %s", clock.Now(), start)
|
||||
}
|
||||
if got := clock.Advance(14 * 24 * time.Hour); !got.Equal(start.AddDate(0, 0, 14)) || !clock.Now().Equal(got) {
|
||||
t.Fatalf("Advance() = %s, Now() = %s, want 14 days later", got, clock.Now())
|
||||
}
|
||||
clock.Set(start)
|
||||
if !clock.Now().Equal(start) {
|
||||
t.Fatalf("Now() after Set = %s, want %s", clock.Now(), start)
|
||||
}
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Fatal("Advance() accepted a negative step")
|
||||
}
|
||||
}()
|
||||
clock.Advance(-time.Second)
|
||||
}
|
||||
|
||||
func TestFakeClockIsSafeForConcurrentUse(t *testing.T) {
|
||||
clock := NewFakeClock(time.Unix(0, 0))
|
||||
const readers, steps = 4, 100
|
||||
var group sync.WaitGroup
|
||||
for range readers {
|
||||
group.Go(func() {
|
||||
for range steps {
|
||||
_ = clock.Now()
|
||||
}
|
||||
})
|
||||
}
|
||||
for range steps {
|
||||
clock.Advance(time.Second)
|
||||
}
|
||||
group.Wait()
|
||||
if got := clock.Now(); !got.Equal(time.Unix(steps, 0)) {
|
||||
t.Fatalf("Now() = %s, want %d seconds after the epoch", got, steps)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user