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

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

No files matched your search

+20 -2
View File
@@ -77,6 +77,18 @@ type Config struct {
// ConsumerRebalanceTimeout is the Kafka rebalance timeout of every
// consumer group member.
ConsumerRebalanceTimeout time.Duration
// JobsEnabled runs the scheduled job worker next to the HTTP servers
// when a job handler is registered.
JobsEnabled bool
JobsPollInterval time.Duration
JobsBatchSize int
JobsLeaseDuration time.Duration
// JobsMaxAttempts applies to jobs scheduled without their own limit.
JobsMaxAttempts int
JobsBackoffInitial time.Duration
JobsBackoffMax time.Duration
// JobsShutdownGrace bounds the job in progress after shutdown begins.
JobsShutdownGrace time.Duration
// EmailProvider selects the only active mail transport. Settings of the
// other transports are not loaded.
EmailProvider EmailProvider
@@ -146,6 +158,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadConsumer(lookup); err != nil {
return Config{}, err
}
if err := config.loadJobs(lookup); err != nil {
return Config{}, err
}
if err := config.loadMail(lookup); err != nil {
return Config{}, err
}
@@ -211,11 +226,14 @@ func (config Config) Validate() error {
if config.ShutdownTimeout <= 0 {
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
}
// The consumer shutdown grace is checked against SHUTDOWN_TIMEOUT, so it
// follows that check.
// The consumer and job shutdown graces are checked against
// SHUTDOWN_TIMEOUT, so they follow that check.
if err := config.ValidateConsumer(); err != nil {
return err
}
if err := config.ValidateJobs(); err != nil {
return err
}
switch config.LogLevel {
case "debug", "info", "warn", "error":
default:
+99
View File
@@ -0,0 +1,99 @@
package config
import (
"errors"
"fmt"
"time"
)
const (
// The scheduled job worker runs by default. It starts only when a job
// handler is registered and DATABASE_URL is set.
defaultJobsEnabled = true
// defaultJobsPollInterval is the wait after a pass that claimed less
// than a batch. It is also the usual lateness of a job after its due
// time.
defaultJobsPollInterval = time.Second
minJobsPollInterval = 10 * time.Millisecond
maxJobsPollInterval = 5 * time.Minute
// defaultJobsBatchSize bounds the jobs one claim leases. A worker runs
// them one after another under leases taken together, so a batch stays
// small next to the lease.
defaultJobsBatchSize = 10
maxJobsBatchSize = 100
// defaultJobsLeaseDuration is how long a claimed job belongs to one
// worker. It bounds one handler attempt, and a worker that crashed
// delays its jobs by at most this long.
defaultJobsLeaseDuration = time.Minute
minJobsLeaseDuration = time.Second
maxJobsLeaseDuration = time.Hour
// defaultJobsMaxAttempts bounds the attempts of a job scheduled without
// its own limit before it is dead.
defaultJobsMaxAttempts = 5
// maxJobsMaxAttempts matches the database bound on a per-job limit.
maxJobsMaxAttempts = 100
// A failed job is retried after a delay that starts at the initial
// value, doubles per failed attempt, and stops growing at the maximum.
defaultJobsBackoffInitial = time.Second
defaultJobsBackoffMax = 5 * time.Minute
maxJobsBackoff = 24 * time.Hour
// defaultJobsShutdownGrace is how long the job in progress may continue
// after shutdown begins.
defaultJobsShutdownGrace = 5 * time.Second
)
func (config *Config) loadJobs(lookup LookupEnv) error {
var err error
if config.JobsEnabled, err = boolOrDefault(lookup, "JOBS_ENABLED", defaultJobsEnabled); err != nil {
return err
}
if config.JobsPollInterval, err = durationOrDefault(lookup, "JOBS_POLL_INTERVAL", defaultJobsPollInterval); err != nil {
return err
}
if config.JobsBatchSize, err = intOrDefault(lookup, "JOBS_BATCH_SIZE", defaultJobsBatchSize); err != nil {
return err
}
if config.JobsLeaseDuration, err = durationOrDefault(lookup, "JOBS_LEASE_DURATION", defaultJobsLeaseDuration); err != nil {
return err
}
if config.JobsMaxAttempts, err = intOrDefault(lookup, "JOBS_MAX_ATTEMPTS", defaultJobsMaxAttempts); err != nil {
return err
}
if config.JobsBackoffInitial, err = durationOrDefault(lookup, "JOBS_BACKOFF_INITIAL", defaultJobsBackoffInitial); err != nil {
return err
}
if config.JobsBackoffMax, err = durationOrDefault(lookup, "JOBS_BACKOFF_MAX", defaultJobsBackoffMax); err != nil {
return err
}
config.JobsShutdownGrace, err = durationOrDefault(lookup, "JOBS_SHUTDOWN_GRACE", defaultJobsShutdownGrace)
return err
}
// ValidateJobs checks the scheduled job settings even when the worker is
// disabled, so enabling it later cannot surface an old mistake.
func (config Config) ValidateJobs() error {
if config.JobsPollInterval < minJobsPollInterval || config.JobsPollInterval > maxJobsPollInterval {
return fmt.Errorf("Config.ValidateJobs - JOBS_POLL_INTERVAL must be between %s and %s", minJobsPollInterval, maxJobsPollInterval)
}
if config.JobsBatchSize < 1 || config.JobsBatchSize > maxJobsBatchSize {
return fmt.Errorf("Config.ValidateJobs - JOBS_BATCH_SIZE must be between 1 and %d", maxJobsBatchSize)
}
if config.JobsLeaseDuration < minJobsLeaseDuration || config.JobsLeaseDuration > maxJobsLeaseDuration {
return fmt.Errorf("Config.ValidateJobs - JOBS_LEASE_DURATION must be between %s and %s", minJobsLeaseDuration, maxJobsLeaseDuration)
}
if config.JobsMaxAttempts < 1 || config.JobsMaxAttempts > maxJobsMaxAttempts {
return fmt.Errorf("Config.ValidateJobs - JOBS_MAX_ATTEMPTS must be between 1 and %d", maxJobsMaxAttempts)
}
if config.JobsBackoffInitial <= 0 {
return errors.New("Config.ValidateJobs - JOBS_BACKOFF_INITIAL must be positive")
}
if config.JobsBackoffMax < config.JobsBackoffInitial || config.JobsBackoffMax > maxJobsBackoff {
return fmt.Errorf("Config.ValidateJobs - JOBS_BACKOFF_MAX must be between JOBS_BACKOFF_INITIAL and %s", maxJobsBackoff)
}
// The grace runs while the HTTP servers drain, so it must fit in the
// shutdown budget of the process.
if config.JobsShutdownGrace <= 0 || config.JobsShutdownGrace > config.ShutdownTimeout {
return errors.New("Config.ValidateJobs - JOBS_SHUTDOWN_GRACE must be positive and at most SHUTDOWN_TIMEOUT")
}
return nil
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvJobsDefaults(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(nil))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if !settings.JobsEnabled || settings.JobsPollInterval != time.Second || settings.JobsBatchSize != 10 ||
settings.JobsLeaseDuration != time.Minute || settings.JobsMaxAttempts != 5 ||
settings.JobsBackoffInitial != time.Second || settings.JobsBackoffMax != 5*time.Minute ||
settings.JobsShutdownGrace != 5*time.Second {
t.Fatalf("unexpected job defaults: %+v", jobSettings(settings))
}
}
func TestLoadFromEnvReadsJobSettings(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"JOBS_ENABLED": " FALSE ",
"JOBS_POLL_INTERVAL": "10ms",
"JOBS_BATCH_SIZE": " 100 ",
"JOBS_LEASE_DURATION": "1h",
"JOBS_MAX_ATTEMPTS": "100",
"JOBS_BACKOFF_INITIAL": "2s",
"JOBS_BACKOFF_MAX": "24h",
"JOBS_SHUTDOWN_GRACE": "20s",
"SHUTDOWN_TIMEOUT": "20s",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.JobsEnabled || settings.JobsPollInterval != 10*time.Millisecond || settings.JobsBatchSize != 100 ||
settings.JobsLeaseDuration != time.Hour || settings.JobsMaxAttempts != 100 ||
settings.JobsBackoffInitial != 2*time.Second || settings.JobsBackoffMax != 24*time.Hour ||
settings.JobsShutdownGrace != 20*time.Second {
t.Fatalf("job settings were not loaded: %+v", jobSettings(settings))
}
}
func TestLoadFromEnvRejectsJobSettings(t *testing.T) {
tests := []struct {
key, value, want string
}{
{key: "JOBS_ENABLED", value: "yes", want: "config.boolOrDefault - JOBS_ENABLED"},
{key: "JOBS_POLL_INTERVAL", value: "soon", want: "config.durationOrDefault - parse JOBS_POLL_INTERVAL"},
{key: "JOBS_POLL_INTERVAL", value: "9ms", want: "Config.ValidateJobs - JOBS_POLL_INTERVAL"},
{key: "JOBS_POLL_INTERVAL", value: "6m", want: "Config.ValidateJobs - JOBS_POLL_INTERVAL"},
{key: "JOBS_BATCH_SIZE", value: "", want: "config.intOrDefault - JOBS_BATCH_SIZE"},
{key: "JOBS_BATCH_SIZE", value: "0", want: "Config.ValidateJobs - JOBS_BATCH_SIZE"},
{key: "JOBS_BATCH_SIZE", value: "101", want: "Config.ValidateJobs - JOBS_BATCH_SIZE"},
{key: "JOBS_LEASE_DURATION", value: "999ms", want: "Config.ValidateJobs - JOBS_LEASE_DURATION"},
{key: "JOBS_LEASE_DURATION", value: "61m", want: "Config.ValidateJobs - JOBS_LEASE_DURATION"},
{key: "JOBS_MAX_ATTEMPTS", value: "many", want: "config.intOrDefault - JOBS_MAX_ATTEMPTS"},
{key: "JOBS_MAX_ATTEMPTS", value: "0", want: "Config.ValidateJobs - JOBS_MAX_ATTEMPTS"},
{key: "JOBS_MAX_ATTEMPTS", value: "101", want: "Config.ValidateJobs - JOBS_MAX_ATTEMPTS"},
{key: "JOBS_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateJobs - JOBS_BACKOFF_INITIAL"},
{key: "JOBS_BACKOFF_INITIAL", value: "6m", want: "Config.ValidateJobs - JOBS_BACKOFF_MAX"},
{key: "JOBS_BACKOFF_MAX", value: "25h", want: "Config.ValidateJobs - JOBS_BACKOFF_MAX"},
{key: "JOBS_SHUTDOWN_GRACE", value: "0s", want: "Config.ValidateJobs - JOBS_SHUTDOWN_GRACE"},
// Longer than the default SHUTDOWN_TIMEOUT of 10s.
{key: "JOBS_SHUTDOWN_GRACE", value: "11s", want: "Config.ValidateJobs - JOBS_SHUTDOWN_GRACE"},
}
for _, test := range tests {
t.Run(test.key+"/"+test.value, func(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want)
}
})
}
}
func TestValidateJobsChecksSettingsEvenWhenDisabled(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"JOBS_ENABLED": "false"}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
settings.JobsBatchSize = 0
if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateJobs - JOBS_BATCH_SIZE") {
t.Fatalf("Validate() error = %v, want the job batch size error", err)
}
}
// jobSettings collects the job fields for failure messages.
func jobSettings(settings Config) map[string]any {
return map[string]any{
"enabled": settings.JobsEnabled,
"poll_interval": settings.JobsPollInterval,
"batch_size": settings.JobsBatchSize,
"lease": settings.JobsLeaseDuration,
"max_attempts": settings.JobsMaxAttempts,
"backoff_initial": settings.JobsBackoffInitial,
"backoff_max": settings.JobsBackoffMax,
"shutdown_grace": settings.JobsShutdownGrace,
}
}
@@ -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;
+288
View File
@@ -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)
}
}
}
+19 -7
View File
@@ -18,6 +18,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/outboxrelay"
)
@@ -40,6 +41,10 @@ type Application struct {
// consumers apply events from the event bus while the servers run. The
// list is empty until a handler is registered in eventHandlers.
consumers eventConsumers
// jobs runs scheduled jobs when they fall due while the servers run. It
// is nil when the worker is disabled, no job kind is registered, or the
// database is not configured.
jobs *jobrunner.Worker
}
func NewApplication(
@@ -50,6 +55,7 @@ func NewApplication(
mailSender outbound.MailSender,
relay *outboxrelay.Relay,
consumers eventConsumers,
jobs *jobrunner.Worker,
) *Application {
return &Application{
config: config,
@@ -59,6 +65,7 @@ func NewApplication(
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
}
}
@@ -174,18 +181,20 @@ func (application *Application) run(ctx context.Context) error {
)
application.logger.Info("servers stopped")
stopRun()
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT and
// each consumer its record in progress within CONSUMER_SHUTDOWN_GRACE
// plus one offset commit, so the cleanup that closes their pools,
// producer, and group members runs after all of them stopped.
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, each
// consumer its record in progress within CONSUMER_SHUTDOWN_GRACE plus
// one offset commit, and the job worker its job in progress within
// JOBS_SHUTDOWN_GRACE plus one release, so the cleanup that closes their
// pools, producer, and group members runs after all of them stopped.
<-workersStopped
application.logger.Info("workers stopped")
return err
}
// startWorkers runs the relay and every consumer until ctx ends and returns
// a channel that closes when all of them have stopped. The workers stop
// together with the servers; none of them depends on another.
// startWorkers runs the relay, every consumer, and the scheduled job worker
// until ctx ends and returns a channel that closes when all of them have
// stopped. The workers stop together with the servers; none of them
// depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
var workers sync.WaitGroup
if application.relay != nil {
@@ -194,6 +203,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
for _, consumer := range application.consumers {
workers.Go(func() { consumer.Run(ctx) })
}
if application.jobs != nil {
workers.Go(func() { application.jobs.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
+1 -1
View File
@@ -191,7 +191,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer})
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+109
View File
@@ -0,0 +1,109 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/retry"
)
const (
// jobsPoolMaxConns covers the handler transaction and one statement
// next to it, such as a backlog read; the worker runs one job at a time.
jobsPoolMaxConns = 2
// jobsStoreTimeout bounds one claim, failure record, release, or
// backlog read. Each is one indexed statement, so a healthy database
// answers well below it.
jobsStoreTimeout = 5 * time.Second
// jobsBacklogInterval matches the usual Prometheus scrape interval.
jobsBacklogInterval = 15 * time.Second
)
var _ jobrunner.Metrics = (*prometheus.Metrics)(nil)
// jobHandlers lists the scheduled job handlers, one per kind. A product
// module adds its handler here, for example the invitation response
// deadline, and the worker then claims jobs of that kind with the next
// deployment. Jobs of a kind without a handler wait in the database.
func jobHandlers() []inbound.JobHandler {
return []inbound.JobHandler{}
}
func newJobWorker(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
) (*jobrunner.Worker, func(), error) {
return buildJobWorker(ctx, settings, logger, metrics, jobHandlers())
}
// buildJobWorker builds the scheduled job worker and the PostgreSQL pool it
// owns. Nothing connects here, so an unavailable database never blocks
// startup; the worker retries in the background. It returns no worker when
// JOBS_ENABLED is false, when no handler is registered, or when
// DATABASE_URL is unset. The application clock is time.Now.
func buildJobWorker(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics jobrunner.Metrics,
handlers []inbound.JobHandler,
) (*jobrunner.Worker, func(), error) {
switch {
case !settings.JobsEnabled:
logger.Info("scheduled job worker is disabled; due jobs wait in the database")
return nil, func() {}, nil
case len(handlers) == 0:
logger.Info("no scheduled job kind is registered")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("scheduled job worker skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, jobsPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.buildJobWorker - create pool: %w", err)
}
// The run transaction lasts at most one lease, which also bounds the
// handler.
store := postgres.NewScheduledJobStore(pool, settings.JobsLeaseDuration)
worker, err := jobrunner.New(
handlers,
store,
metrics,
logger.With(slog.String("component", "scheduled_jobs")),
jobWorkerSettings(settings),
time.Now,
)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.buildJobWorker - create worker: %w", err)
}
// The application stops the worker before this cleanup runs, so no job
// uses the pool while it closes.
return worker, pool.Close, nil
}
func jobWorkerSettings(settings config.Config) jobrunner.Settings {
return jobrunner.Settings{
BatchSize: settings.JobsBatchSize,
PollInterval: settings.JobsPollInterval,
Lease: settings.JobsLeaseDuration,
MaxAttempts: settings.JobsMaxAttempts,
Backoff: retry.Backoff{
Initial: settings.JobsBackoffInitial,
Max: settings.JobsBackoffMax,
},
ShutdownGrace: settings.JobsShutdownGrace,
StoreTimeout: jobsStoreTimeout,
BacklogInterval: jobsBacklogInterval,
}
}
+105
View File
@@ -0,0 +1,105 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
type kindHandler string
func (handler kindHandler) JobKind() string { return string(handler) }
func (kindHandler) Handle(context.Context, outbound.UnitOfWork, outbound.ClaimedJob) error {
return nil
}
func TestBuildJobWorkerSkipsWithoutWork(t *testing.T) {
disabled := consumerTestConfig(t)
disabled.JobsEnabled = false
noDatabase := consumerTestConfig(t)
noDatabase.DatabaseURL = ""
tests := []struct {
name string
settings config.Config
handlers []inbound.JobHandler
log string
}{
{name: "disabled", settings: disabled, handlers: []inbound.JobHandler{kindHandler("test.deadline")}, log: "scheduled job worker is disabled"},
{name: "no handler registered", settings: consumerTestConfig(t), log: "no scheduled job kind is registered"},
{name: "database not configured", settings: noDatabase, handlers: []inbound.JobHandler{kindHandler("test.deadline")}, log: "DATABASE_URL is not set"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var logs strings.Builder
logger := slog.New(slog.NewTextHandler(&logs, nil))
worker, cleanup, err := buildJobWorker(t.Context(), test.settings, logger, prometheus.New(), test.handlers)
if err != nil {
t.Fatalf("buildJobWorker() error = %v", err)
}
cleanup()
if worker != nil {
t.Fatal("buildJobWorker() built a worker without work to do")
}
if !strings.Contains(logs.String(), test.log) {
t.Fatalf("logs = %q, want %q", logs.String(), test.log)
}
})
}
}
func TestBootstrapRegistersNoJobKindYet(t *testing.T) {
if handlers := jobHandlers(); len(handlers) != 0 {
t.Fatalf("jobHandlers() = %v; update the documentation when the registered job kinds change", handlers)
}
}
func TestBuildJobWorkerRefusesADuplicateKind(t *testing.T) {
_, _, err := buildJobWorker(t.Context(), consumerTestConfig(t), slog.New(slog.DiscardHandler), prometheus.New(),
[]inbound.JobHandler{kindHandler("test.deadline"), kindHandler("test.deadline")})
if err == nil {
t.Fatal("buildJobWorker() accepted a kind registered twice")
}
}
// TestApplicationRunsAndStopsTheJobWorker starts the worker against a
// database that does not answer: it keeps retrying in the background, and
// the application still stops within its shutdown budget.
func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) {
settings := consumerTestConfig(t)
settings.HTTPAddr = "127.0.0.1:0"
settings.MetricsAddr = "127.0.0.1:0"
settings.ShutdownTimeout = time.Second
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
worker, cleanup, err := buildJobWorker(t.Context(), settings, logger, metrics, []inbound.JobHandler{kindHandler("test.deadline")})
if err != nil {
t.Fatalf("buildJobWorker() error = %v", err)
}
defer cleanup()
if worker == nil {
t.Fatal("buildJobWorker() built no worker for a registered kind")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
time.Sleep(50 * time.Millisecond)
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -49,6 +49,7 @@ func initialize(
httpadapter.NewRouter,
newOutboxRelay,
newEventConsumers,
newJobWorker,
NewApplication,
),
)
+11 -1
View File
@@ -70,8 +70,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers)
worker, cleanup6, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker)
return application, func() {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
+153
View File
@@ -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
+581
View File
@@ -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)
}
}
View File
Whitespace-only changes.
+51
View File
@@ -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
}
+48
View File
@@ -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)
}
}
+31 -8
View File
@@ -50,7 +50,7 @@ Redis is part of the core Compose project and connects through `backend/internal
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; no product consumer is registered yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; one product consumer is registered, `notification_delivery` for mail deliveries. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
### Private file storage
@@ -166,6 +166,28 @@ Trade-offs: one consumer processes one record at a time on one connection. Paral
The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records by `applied`, `duplicate`, `ignored`, or `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter, by `handler`, `store`, `poll` (a failed poll of the event bus), or `commit` (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload.
### Scheduled jobs
Implemented (TASK-035): durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline (TASK-205). Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `<id>:<version>`.
States. `due_at` is the deadline the job stands for and never changes; `available_at` is when a worker may claim the job next, `due_at` at first and the retry time after a failed attempt. `pending` waits for `available_at`; `failed` waits for its retry after a failed attempt; `running` is claimed under a lease; `done`, `dead`, and `cancelled` are final. Finished rows are kept, so their key stays reserved; their retention is not implemented yet.
Claim and lease. The worker claims up to `JOBS_BATCH_SIZE` jobs in one statement: a CTE selects waiting jobs whose `available_at` passed and running jobs whose `lease_expires_at` passed, of the kinds that have a handler in this process, in `available_at` order, with `FOR UPDATE SKIP LOCKED`, and the same statement sets `status = running`, `lease_owner` (a random ID per worker instance), and `lease_expires_at = now + JOBS_LEASE_DURATION`, and counts the attempt. Two partial indexes serve the claim, one on waiting rows and one on running rows; the kind filter applies after the index, so when many waiting jobs belong to kinds that the claiming process has no handler for, an index on `(kind, available_at, id)` is the next step. `now` is passed from the injected application clock; the database clock never decides whether a job is due or a lease expired, so tests move a fake clock instead of waiting days. Jobs of a kind without a handler stay untouched, so an older instance during a rolling deployment leaves them to the instances that have the handler. Right before its handler transaction, each job is started: a separately committed, guarded `UPDATE` renews its lease from now and sets `started_at`, but only while the lease of the claim has not expired. The attempt is counted at the claim, so a job that crashes its process while its handler runs cannot loop forever: when the lease of a started attempt expires on the last allowed attempt, the claim marks the job `dead` with `lease_expired` instead of running it again. A claim whose attempt never started (the worker stopped or was busy before the job's turn) is not the job's fault: the next claim reuses that attempt without counting another one and records no error class.
Run and completion. Each job runs in its own READ COMMITTED transaction: it sets `statement_timeout` and `idle_in_transaction_session_timeout` to the lease duration, locks the job row with a guard on `status = running`, the lease owner, and the attempt number, calls the handler with an `outbound.UnitOfWork` of the same transaction, marks the job `done` with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (`lease_lost`). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job `cancelled` in its own transaction, treats it as finished, and commits the effect, and the job stays `cancelled`. Any other change of its own job by the handler rolls back and makes the job `dead` with `completion_conflict`, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by `job.DueAt`, the deadline the job stands for, which a retry keeps, not by when it happens to run.
Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job, such as accepting an invitation at its deadline, should call `Cancel` before it locks those product rows. `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the expiry; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries.
Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (`conflict`), or a commit that PostgreSQL refuses (`effect_rejected`, for a handler that ignored a failed statement or a deferred constraint) moves the job to `failed` with `available_at = now + backoff`, where the backoff is the shared `worker/retry` delay from `JOBS_BACKOFF_INITIAL`, doubling up to `JOBS_BACKOFF_MAX`, with jitter. `inbound.ErrJobRejected`, a handler panic, and `completion_conflict` are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or `JOBS_MAX_ATTEMPTS`) the job is `dead`: it is logged at error level and counted as `dead`, and it needs an operator. `last_error_class` stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as `lease_expired`, which on the last attempt makes it dead.
Shutdown. When the context ends, the worker claims nothing more. A job in progress has `JOBS_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back, so an unfinished job is never marked done. The worker then releases it, and the claimed jobs of the batch it did not start, explicitly: back to `pending` or `failed`, without counting the attempt, guarded by owner and attempt so a job that another worker reclaimed or a caller canceled meanwhile is left alone. Release makes the jobs claimable at once by another instance instead of after up to one lease, which matters during a rolling deployment; if the release cannot reach the database, the lease expires and a later claim takes the jobs, so the release is only a shortcut and never needed for correctness. Bootstrap starts the worker next to the HTTP servers, the relay, and the consumers, and runs the cleanup that closes its pool only after it stopped.
Trade-offs: one worker runs one job at a time on a pool of two connections; more throughput comes from more backend instances. The jobs of one batch are claimed together but each renews its lease when it starts, so a slow job ahead costs the next ones only waiting time: a job whose claim lease expired before its turn is not started and is released with its attempt intact, or, when another worker already took it over, that worker runs it on the same attempt. Due times are honored with a delay of up to `JOBS_POLL_INTERVAL` plus the batch ahead of it. There is no separate `cmd/worker`: the worker is a goroutine of the backend process, and migrations run as before.
Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `done`, `retry`, `dead`, `lease_lost`, or `released`; the kind label comes from the registered handlers, and every series exists at zero from the start. `lincodex_scheduled_jobs_due`, `lincodex_scheduled_jobs_oldest_due_age_seconds`, and `lincodex_scheduled_jobs_dead` describe all kinds at the last backlog read, at most every 15 seconds. Logs carry the job ID, kind, attempt, and error class, never the key or payload.
### Mail transport
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet: deliveries are stored (see [Mail deliveries](#mail-deliveries)), and the worker that sends them is planned (TASK-016). Settings are described in [DEPLOY.md](DEPLOY.md#mail).
@@ -422,20 +444,21 @@ backend/
prometheus/ bounded Go/process and request metrics
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ embedded migrations and SQL queries; outbox, identity, policy, and event consumer tables
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, and scheduled job tables
codegen/ ogen and sqlc configs
pkg/ reserved for justified shared technical helpers
pkg/testutil/ fake application clock shared by tests
```
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with no registered product handler, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, product job kinds, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
@@ -514,7 +537,7 @@ Resume text is untrusted data, not an instruction to tools. ML does not follow a
A standardized PDF is required in the product even when profile entry is manual. PDFRenderer consumes structured profile data. The planned approach is controlled HTML and isolated headless Chromium with Cyrillic fonts, no external network fetches, and no user-supplied HTML.
Future jobs use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
Jobs that only need to run at a due time use the implemented runtime in [Scheduled jobs](#scheduled-jobs). Future ML and document jobs, which a user waits for, use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
Long operations return 202 and a job ID. The UI polls with a widening interval and stops after completion or page exit. The browser never calls ML directly. Routine tests do not download a model or require GPU. Model, license, inference budget, and production latency are unselected.
@@ -577,7 +600,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo
## Future extensions
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); product consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); one product consumer, `notification_delivery`, is registered; further consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy.
@@ -602,7 +625,7 @@ Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amo
## Metrics, telemetry, and alerts
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. Queue, inference, and product-event metrics are not implemented in the current scaffold.
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. The scheduled job counters and backlog gauges are described in [Scheduled jobs](#scheduled-jobs). Inference and product-event metrics are not implemented in the current scaffold.
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model.
+44
View File
@@ -168,6 +168,50 @@ The table holds no record value; `value_size` and `value_sha256` identify the va
To inspect an `invalid_record` while the topic retains it, read exactly that record with `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1` and compare its SHA-256 with `value_sha256`. The value can contain personal data, so do not paste it into tickets or chats.
### Scheduled jobs
The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: no product job kind is registered, so the backend logs `no scheduled job kind is registered` at startup and runs no worker; the settings below are still validated. With a registered kind, the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled.
| Variable | Default | Meaning |
| --- | --- | --- |
| `JOBS_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no job runs; due jobs wait in `scheduled_jobs` and run after the worker starts again, with their original `due_at`. |
| `JOBS_POLL_INTERVAL` | `1s` | Wait after a pass that claimed less than a full batch, from 10ms to 5m. It is also the usual delay of a job after its due time. |
| `JOBS_BATCH_SIZE` | `10` | Jobs one claim leases, from 1 to 100. They run one after another under leases taken together, so a batch should finish well within one lease. |
| `JOBS_LEASE_DURATION` | `1m` | How long a claimed job belongs to one worker, from 1s to 1h. It bounds one handler attempt and is the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the job transaction. A worker that crashed delays its jobs by at most this long. |
| `JOBS_MAX_ATTEMPTS` | `5` | Attempts of a job scheduled without its own limit before it is dead, from 1 to 100. Database failures outside the handler and shutdown do not count. |
| `JOBS_BACKOFF_INITIAL` | `1s` | Delay before the first retry of a failed job; it doubles with each failed attempt. The same backoff spaces claims while the database fails. |
| `JOBS_BACKOFF_MAX` | `5m` | Longest delay before a retry, from `JOBS_BACKOFF_INITIAL` to 24h. |
| `JOBS_SHUTDOWN_GRACE` | `5s` | Time the job in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back and the job is released unfinished. |
Due times and leases are compared with the backend clock, not the database clock, so keep the hosts of all backend instances synchronized with NTP. A clock ahead runs jobs early and takes over leases early; the row lock still prevents a second run while a handler is in progress.
Shutdown budget. The worker stops in parallel with the other workers: `JOBS_SHUTDOWN_GRACE` (5s) for the job in progress, up to 5s to roll back a canceled transaction, and up to 5s to release the unfinished jobs, 15s at most. This fits the first phase of the budget under [Event consumers](#event-consumers), so the total stays about 23s within `stop_grace_period: 30s`; raise that together with `JOBS_SHUTDOWN_GRACE`. If the backend is killed instead, its jobs stay `running` until their leases expire and then run on another instance or after the restart.
The worker uses its own PostgreSQL pool of at most two connections. Several backend instances share the jobs: each claim skips rows that another instance locks, and every instance can run every registered kind.
Operators watch `lincodex_scheduled_jobs_total{kind,outcome}` on the internal /metrics endpoint: `done`, `retry` (an attempt failed and the job waits for its backoff), `dead`, `lease_lost` (the job was canceled or reclaimed while this instance held it), and `released` (given back unfinished at shutdown or after a database failure). Every series exists at zero from the start, so alert on `increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0`. `lincodex_scheduled_jobs_due` and `lincodex_scheduled_jobs_oldest_due_age_seconds` describe due jobs that wait for a worker; an age that keeps growing beyond a few poll intervals means no instance claims them, for example because the worker is disabled, the database fails, or no running instance has the handler of their kind. `lincodex_scheduled_jobs_dead` counts dead jobs. Every instance reports the same database-wide gauges, so aggregate them with `max`. During a rolling deployment that adds a new kind, its jobs that already fell due wait until an instance with the handler runs, and the age can briefly look like a stuck worker; hold an age alert for longer than a deployment takes. Logs carry the `scheduled_jobs` component, the lease owner, job ID, kind, attempt, and error class, never the key or payload; a dead job is logged at error level as `scheduled job is dead; it needs an operator`.
#### Dead jobs
`last_error_class` says why a job is dead: `handler_rejected` (the handler can never run it), `handler_panic` (the log line `scheduled job handler panicked` with the same job ID holds the stack), `lease_expired` (its last started attempt stopped without finishing, usually a crash or a kill, or its failure could not be recorded because the database failed at that moment), or the class of the last failed attempt after the attempts ran out: `handler_failed`, `timeout`, `conflict`, or `effect_rejected`. `completion_conflict` means the handler changed its own job other than by canceling it. List dead jobs and jobs that are overdue with psql in the database container (see [Dead letters and replay](#dead-letters-and-replay) for the command that opens it):
SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class,
due_at, available_at, updated_at
FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at;
SELECT kind, status, count(*), min(available_at)
FROM scheduled_jobs
WHERE status IN ('pending', 'failed', 'running') AND available_at <= now()
GROUP BY kind, status;
The key identifies a product record, such as an invitation ID; the payload holds identifiers only. After the cause is fixed, usually by deploying a corrected handler, run a dead job again. Change only `available_at`, never `due_at`: the handler decides by the deadline in `due_at`.
UPDATE scheduled_jobs
SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp()
WHERE id = <id> AND status = 'dead';
A worker claims it within one poll interval and runs it with fresh attempts. To give a dead job up, set `status = 'cancelled'` with the same guard; its key stays reserved, so the product flow cannot schedule it again. Do not delete rows: a deleted key can be scheduled again and run a second time.
## Mail
The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read.
+7 -1
View File
@@ -57,7 +57,7 @@ What exists now:
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), and the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`), and the scheduled job table (`scheduled_jobs`, with no product job kind registered yet) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
## Install and work loop
@@ -199,6 +199,12 @@ To send a notification from a usecase, call `notification.MailRequester.RequestN
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
### Scheduled jobs
To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `<id>:<version>`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches.
Then implement `inbound.JobHandler` in the module's usecase package: return the kind from `JobKind()` and write the effect in `Handle` only through the `UnitOfWork` it receives, deciding by `job.DueAt` and the current product state, so the handler is a no-op when the state already moved on. A handler may cancel its own job through the unit, for example from a shared helper that cancels the deadline; the job then counts as finished. It must not change its own job in any other way. Return an error that wraps `inbound.ErrJobRejected` for a job that can never run; any other error is retried. Add the handler to `jobHandlers()` in `backend/internal/bootstrap/jobs.go`. Take the clock as a `func() time.Time` and test deadlines with `testutil.FakeClock` from `backend/pkg/testutil/` and `Worker.RunDue`, which runs the due jobs once without polling, as `TestScheduledJobs` does. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs); settings, metrics, and the dead job procedure are in [DEPLOY.md](DEPLOY.md#scheduled-jobs); tests are in [TESTING.md](TESTING.md#scheduled-job-tests).
## Go readability
- Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call.
+21
View File
@@ -185,6 +185,27 @@ Unit tests (`make -C backend test`) cover the quota rules without a database:
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The suite does not call a transport: the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is TASK-016.
## Scheduled job tests
Unit tests (`make -C backend test`) cover the job runtime with an in-memory store that applies the claim, lease guard, and release rules of the PostgreSQL store and a fake clock from `backend/pkg/testutil/` (`internal/worker/jobrunner/`): only due jobs of registered kinds run, in due order, and a job due in two days runs exactly when the clock reaches it; a failing job is retried after the backoff by the clock, is not claimed again before it, and is dead after the last attempt with an error log and metrics; `ErrJobRejected` and a panic end a job after one attempt without logging the panic value; a handler that outlives its lease fails as `timeout`; a job reclaimed by another worker before it starts is skipped without calling the handler; a job whose last started lease expired becomes dead without running; a slow first job of a batch neither spends the next job's single attempt nor lets it die, and another worker runs a job that a busy worker claimed but did not start, on the same attempt; a database failure outside the handler releases the job and the rest of the batch without counting attempts; failed claims back off instead of looping; at shutdown the job in progress finishes within the grace, a job that outlasts it is canceled and released without an effect or a counted attempt, and claimed jobs that did not start are released; a panic during shutdown still makes the job dead; and the backlog of all kinds is reported. Further unit tests cover the job rules (`internal/domain/`: kind, key, flat payload, size limit, UTC microsecond due time), the settings (`config/`), the counters and gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), and in `internal/bootstrap/` the skip cases with their log lines, the empty kind registry, a duplicate kind, and an application that runs the worker against an unreachable database and still stops.
`TestScheduledJobs` in `backend/integration_test/scheduled_jobs_test.go` uses `bootstrap(t, postgresService)`. Its handler exists only in the test: it writes one row into `job_test.effects`, a table without a unique key, in the transaction that completes the job, so a second effect would stay visible. Each simulated process gets its own pool, store, and worker; building a new one is a restart. All due and lease decisions use one `FakeClock`. The sequential cases are:
- Jobs on different dates: two jobs scheduled through `UnitOfWork.ScheduledJobs()` for tomorrow and in three days, and a repeated schedule that is ignored and does not move the due time. Nothing runs at the start; after a restart and one day the first job runs; after another restart the second job does not run a microsecond early and runs at its due time; a month later nothing runs again. The effects are one per job, in due order.
- Two workers with their own pools run their loops against 40 due jobs at once: every job is done, and there are exactly 40 effects for 40 distinct jobs.
- A handler that outlives its lease by the clock still holds the job row lock, so another worker's claim skips the job; the first worker then completes it, with one effect.
- An expired lease: worker A claims and starts the job and stops inside it. Worker B cannot claim it a microsecond before the lease expires and runs it at expiry, with two counted attempts and `lease_expired` recorded. A's late start is refused, its late `Run` returns `ErrJobLeaseLost` without calling its handler, and its late failure record and release are refused; one effect remains.
- A started attempt with a limit of one attempt whose lease expired: the next claim makes the job dead with one attempt and `lease_expired`, without calling the handler.
- A claim that never started, with a limit of one attempt: after its lease expires another worker runs the job on the same attempt, with no error class.
- A slow first job of a batch runs past the claim lease: the next job, limited to one attempt, is released with its attempt intact and runs in the next pass. With two workers, while the slow job holds its row, the other worker claims only the waiting job and runs it on its single attempt; the busy worker then counts it as `lease_lost`.
- A handler that cancels its own job through the unit: its effect commits, the job stays `cancelled`, and the next job of the pass runs. A handler that changes its own job otherwise makes it dead with `completion_conflict` and leaves no effect.
- Graceful shutdown: a handler writes its effect and then outlasts a 200 ms grace. After the stop the effect is rolled back and the job is `pending` with no attempt and no lease, and a new process runs it at once without waiting for a lease.
- A failing job with its own limit of two attempts: the first attempt moves only `available_at` by the backoff and keeps `due_at`, the job is not claimed before the backoff, the second attempt makes it dead, the handler saw the original due time both times, no effect remains, the backlog reports one dead job, and the counters show one `retry` and one `dead`.
- Cancel: a canceled job is never claimed, a second cancel and a new schedule of the same key do nothing, and nothing is due.
- Cancel during a run: while a handler holds the job, a cancel in another transaction is observed waiting for the row lock in `pg_stat_activity`; after the handler commits, the job is done and the cancel reports false.
`TestPostgresMigrations` also checks that migration 00008 creates and drops `scheduled_jobs`. The suite uses one PostgreSQL and a test-only kind. It does not measure throughput, does not cover clock skew between instances, a database failover, or a product handler, and does not check alert delivery.
## Integration test sharding
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
+31 -8
View File
@@ -50,7 +50,7 @@ Redis входит в основной Compose и подключен через
SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Общий файловый слой и контроль доступа в контейнере SeaweedFS описаны в разделе [Закрытое файловое хранилище](#закрытое-файловое-хранилище). Загрузка резюме, проверка прав, продуктовые правила содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование.
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; продуктовые обработчики пока не зарегистрированы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрирован один продуктовый обработчик - `notification_delivery` для доставок писем. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
### Закрытое файловое хранилище
@@ -166,6 +166,28 @@ Offsets и партиции. Каждый обработчик - один уча
Метрика `lincodex_event_consumer_records_total{consumer,outcome}` считает завершенные записи по `applied`, `duplicate`, `ignored` или `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` считает каждую неудачную операцию, включая последнюю попытку обработчика перед dead letter, по `handler`, `store`, `poll` (неудачное чтение шины событий) или `commit` (неудачный commit offset). Метка consumer берется из зарегистрированных в коде имен, поэтому число рядов ограничено. Все ряды обработчика существуют с его запуска со значением 0. Журналы содержат обработчик, группу, топик, партицию, offset, ID и тип события, но никогда не значение или payload.
### Задания по сроку
Реализовано (TASK-035): устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение (TASK-205). Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `<id>:<version>`.
Состояния. `due_at` - срок, который задание представляет, и он никогда не меняется; `available_at` - момент, когда worker может захватить задание в следующий раз: сначала `due_at`, после неудачной попытки - время повтора. `pending` ждет `available_at`; `failed` после неудачной попытки ждет повтора; `running` захвачено под lease; `done`, `dead` и `cancelled` - финальные. Завершенные строки сохраняются, поэтому их ключ остается занятым; срок их хранения пока не реализован.
Захват и lease. Worker захватывает до `JOBS_BATCH_SIZE` заданий одним оператором: CTE выбирает ожидающие задания с прошедшим `available_at` и выполняемые задания с прошедшим `lease_expires_at` тех видов, для которых в процессе есть обработчик, в порядке `available_at` с `FOR UPDATE SKIP LOCKED`, а тот же оператор ставит `status = running`, `lease_owner` (случайный ID экземпляра worker) и `lease_expires_at = now + JOBS_LEASE_DURATION` и учитывает попытку. Захват обслуживают два частичных индекса: по ожидающим и по выполняемым строкам; фильтр по виду применяется после индекса, поэтому, когда много ожидающих заданий относится к видам без обработчика в захватывающем процессе, следующим шагом нужен индекс `(kind, available_at, id)`. `now` передается из внедренных часов приложения; часы базы данных никогда не решают, наступил ли срок или истек ли lease, поэтому тесты сдвигают fake clock вместо ожидания в несколько дней. Задания вида без обработчика не трогаются, поэтому старый экземпляр во время поэтапного развертывания оставляет их экземплярам, у которых обработчик есть. Непосредственно перед транзакцией обработчика каждое задание запускается: отдельно зафиксированный `UPDATE` с проверкой продлевает его lease от текущего момента и ставит `started_at`, но только пока lease захвата не истек. Попытка учитывается при захвате, поэтому задание, которое роняет процесс во время работы обработчика, не может повторяться бесконечно: если lease начатой попытки истек на последней разрешенной попытке, захват переводит задание в `dead` с классом `lease_expired` вместо нового запуска. Захват, попытка которого так и не началась (worker остановился или был занят до очереди задания), не вина задания: следующий захват использует ту же попытку, не учитывая новую, и не записывает класс ошибки.
Выполнение и завершение. Каждое задание выполняется в собственной транзакции READ COMMITTED: она ставит `statement_timeout` и `idle_in_transaction_session_timeout` равными длительности lease, блокирует строку задания с проверкой `status = running`, владельца lease и номера попытки, вызывает обработчик с `outbound.UnitOfWork` той же транзакции, отмечает задание `done` с той же проверкой и фиксирует транзакцию. Эффект обработчика и завершение фиксируются вместе: для эффекта, который остается в PostgreSQL, задание применяется ровно один раз, даже когда workers конкурируют, перезапускаются или lease истекает. Пока обработчик работает, строка заблокирована, поэтому захват другого worker пропускает ее даже после истечения lease по часам; если проверка не прошла, потому что задание отменили или захватили заново, обработчик не вызывается и ничего не фиксируется (`lease_lost`). Обработчик может отменить собственное задание через unit, например истечение, которое заодно отменяет задание срока, которое оно представляет: тогда завершение находит задание `cancelled` в своей же транзакции, считает его выполненным и фиксирует эффект, а задание остается `cancelled`. Любое другое изменение собственного задания обработчиком откатывается и переводит задание в `dead` с классом `completion_conflict`, потому что оно повторялось бы на каждой попытке. Обработчик, эффект которого выходит за пределы базы данных, например вызов другого сервиса, может повториться после сбоя между этим вызовом и фиксацией и должен быть идемпотентным сам. Context обработчика заканчивается вместе с продленным lease. Обработчик принимает решение по `job.DueAt`, то есть по сроку, который задание представляет и который повтор сохраняет, а не по моменту, когда оно случайно выполнилось.
Порядок блокировок. Обработчик держит блокировку строки задания и затем может блокировать продуктовые строки. Бизнес-транзакция, которая отменяет задание, например принятие приглашения в момент срока, должна вызывать `Cancel` до блокировки этих продуктовых строк. `Cancel` ждет транзакцию обработчика, если она идет: после ее фиксации задание уже `done`, и `Cancel` возвращает `false`, поэтому вызывающий видит истечение; иначе задание отменяется, а worker обнаруживает, что его lease больше не действует. Обратный порядок может привести к deadlock, который PostgreSQL разрешает, прерывая одну сторону с `ErrTransactionConflict`; сторона задания засчитывает неудачную попытку и повторяет ее.
Сбои. Неудачная попытка откатывает свой эффект; второй оператор с той же проверкой записывает ее. Ошибка обработчика, истечение lease, deadlock или serialization failure (`conflict`) и фиксация, которую отверг PostgreSQL (`effect_rejected`, для обработчика, который проигнорировал упавший оператор, или для отложенного ограничения), переводят задание в `failed` с `available_at = now + backoff`, где backoff - общая задержка `worker/retry`: от `JOBS_BACKOFF_INITIAL`, удваивается до `JOBS_BACKOFF_MAX`, со случайным разбросом. `inbound.ErrJobRejected`, panic обработчика и `completion_conflict` финальны, в том числе во время остановки. После последней разрешенной попытки (собственный лимит задания или `JOBS_MAX_ATTEMPTS`) задание становится `dead`: это пишется в журнал на уровне error и считается как `dead`, такому заданию нужен оператор. `last_error_class` хранит только ограниченный класс; очищенная причина есть только в журнале. Сбой базы данных вне обработчика - не вина задания: worker освобождает незавершенные задания без учета попытки и ждет backoff перед следующим захватом, поэтому сбой не создает горячего цикла. Если не удалось записать сам сбой, задание сохраняет начатый lease; следующий захват учтет его как `lease_expired`, а на последней попытке это делает задание dead.
Остановка. Когда context заканчивается, worker больше ничего не захватывает. У задания в работе есть `JOBS_SHUTDOWN_GRACE` на фиксацию; после этого оно отменяется, его транзакция откатывается, поэтому незавершенное задание никогда не отмечается выполненным. Затем worker явно освобождает его и захваченные, но не начатые задания пачки: возвращает их в `pending` или `failed` без учета попытки с проверкой владельца и попытки, поэтому задание, которое тем временем захватил другой worker или отменил вызывающий, не трогается. Освобождение делает задания доступными другому экземпляру сразу, а не через время до одного lease, что важно при поэтапном развертывании; если освобождение не достучалось до базы, lease истекает, и задания берет следующий захват, поэтому освобождение только ускоряет и для корректности не требуется. Bootstrap запускает worker рядом с HTTP-серверами, relay и обработчиками событий и закрывает его пул только после его остановки.
Компромиссы: один worker выполняет одно задание за раз на пуле из двух соединений; большая пропускная способность достигается числом экземпляров backend. Задания одной пачки захватываются вместе, но каждое продлевает свой lease при запуске, поэтому медленное задание впереди стоит следующим только ожидания: задание, lease захвата которого истек до его очереди, не запускается и освобождается с сохраненной попыткой, а если его уже взял другой worker, тот выполняет его на той же попытке. Сроки соблюдаются с задержкой до `JOBS_POLL_INTERVAL` плюс время пачки перед заданием. Отдельного `cmd/worker` нет: worker - горутина процесса backend, миграции запускаются как раньше.
Метрики: `lincodex_scheduled_jobs_total{kind,outcome}` считает захваченные задания по исходам `done`, `retry`, `dead`, `lease_lost` и `released`; метка вида берется из зарегистрированных обработчиков, и каждый ряд существует с нулем с момента старта. `lincodex_scheduled_jobs_due`, `lincodex_scheduled_jobs_oldest_due_age_seconds` и `lincodex_scheduled_jobs_dead` описывают все виды на момент последнего чтения backlog, не чаще чем раз в 15 секунд. Журналы содержат ID задания, вид, номер попытки и класс ошибки, но никогда ключ или payload.
### Почтовый транспорт
Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий: доставки уже сохраняются (см. [Доставки писем](#доставки-писем)), а worker, который их отправляет, запланирован (TASK-016). Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
@@ -422,20 +444,21 @@ backend/
prometheus/ ограниченные Go/process и request metrics
worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка
worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка
worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка
worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers
bootstrap/ конфигурация, wiring, lifecycle, shutdown
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики и обработчиков событий
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты и заданий по сроку
codegen/ конфигурация ogen и sqlc
pkg/ резерв для обоснованных общих технических helpers
pkg/testutil/ fake clock приложения, общий для тестов
```
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий без зарегистрированных продуктовых обработчиков, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
@@ -514,7 +537,7 @@ contact_grant относится к паре кандидат-компания
Стандартизированный PDF обязателен в продуктовой версии, даже при ручном вводе. PDFRenderer получает структурированный профиль; предполагаемый подход - контролируемый HTML и изолированный headless Chromium с кириллическими шрифтами, без внешних сетевых загрузок и пользовательского HTML.
Будущие jobs имеют состояния queued, running, succeeded, failed, cancelled, лимит попыток, available_at, lease/heartbeat и безопасный код ошибки. Взятие атомарно. Истекший lease разрешает повтор; уникальный ключ операции, версия документа и lease token не дают старому worker перезаписать новый результат. Вычисление может повториться, бизнес-эффект - нет. Retry ограничен и использует backoff.
Задания, которым нужно только выполниться в срок, используют реализованный runtime из раздела [Задания по сроку](#задания-по-сроку). Будущие jobs ML и документов, результата которых ждет пользователь, имеют состояния queued, running, succeeded, failed, cancelled, лимит попыток, available_at, lease/heartbeat и безопасный код ошибки. Взятие атомарно. Истекший lease разрешает повтор; уникальный ключ операции, версия документа и lease token не дают старому worker перезаписать новый результат. Вычисление может повториться, бизнес-эффект - нет. Retry ограничен и использует backoff.
Для долгой обработки API возвращает 202 и job ID, интерфейс опрашивает статус с увеличивающимся интервалом и прекращает опрос после завершения или ухода со страницы. Браузер не обращается к ML напрямую. Обычные тесты не загружают модель и не требуют GPU. Модель, лицензия, бюджет inference и реальные сроки отклика пока не выбраны.
@@ -577,7 +600,7 @@ contact_grant относится к паре кандидат-компания
## Будущее расширение
Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox, ее транзакционная запись, relay и runtime обработчиков реализованы (см. "Transactional outbox", "Relay outbox" и "Обработчики событий" выше); продуктовые обработчики и дополнительные топики запланированы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox, ее транзакционная запись, relay и runtime обработчиков реализованы (см. "Transactional outbox", "Relay outbox" и "Обработчики событий" выше); зарегистрирован один продуктовый обработчик, `notification_delivery`; другие обработчики и дополнительные топики запланированы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy.
@@ -602,7 +625,7 @@ k3s не входит в критический путь. Его можно ра
## Метрики, телеметрия и alerts
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики очереди, inference и бизнес-событий пока не реализованы.
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Счетчики и gauges backlog заданий по сроку описаны в разделе [Задания по сроку](#задания-по-сроку). Метрики inference и бизнес-событий пока не реализованы.
План наблюдаемости включает метрики jobs: очередь, возраст старейшего готового задания, время ожидания и выполнения, retries и окончательные ошибки; состояние pgxpool должно собираться внутри Go ограниченными неблокирующими запросами. Nginx `stub_status` не дает latency по HTTP статусам; access logs могут измерять `request_time` и `upstream_response_time`. cAdvisor можно добавить при поддержке выбранного runtime. Redis exporter уже включен в отдельный monitoring Compose, Prometheus опрашивает его на внутреннем порту 9121. Метрики SeaweedFS опрашиваются напрямую на внутреннем порту 9327; сохраняются только выбранные агрегированные серии, без путей объектов. DCGM exporter понадобится только при локальной NVIDIA модели.
+44
View File
@@ -170,6 +170,50 @@ Dead letter - запись, от которой обработчик отказ
Чтобы посмотреть `invalid_record`, пока топик ее хранит, прочитайте ровно эту запись через `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1` и сравните ее SHA-256 с `value_sha256`. Значение может содержать персональные данные, поэтому не вставляйте его в задачи и чаты.
### Задания по сроку
Backend запускает worker заданий по сроку как горутину процесса backend рядом с HTTP-серверами, relay и обработчиками событий. Он выполняет задания, которые usecase запланировали в своих транзакциях, когда наступает их срок; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку). Текущее состояние: продуктовый вид задания не зарегистрирован, поэтому backend при старте пишет в журнал `no scheduled job kind is registered` и не запускает worker; настройки ниже все равно проверяются. С зарегистрированным видом worker работает, когда `JOBS_ENABLED` равно true и задан `DATABASE_URL`. Compose не передает ни одну из этих настроек, поэтому стенд использует значения по умолчанию; чтобы изменить значение, добавьте его в `environment` backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает запуск, даже когда worker выключен.
| Переменная | По умолчанию | Значение |
| --- | --- | --- |
| `JOBS_ENABLED` | `true` | `true` или `false`. При `false` или без `DATABASE_URL` задания не выполняются; наступившие задания ждут в `scheduled_jobs` и выполнятся после нового запуска worker с исходным `due_at`. |
| `JOBS_POLL_INTERVAL` | `1s` | Пауза после прохода, который захватил меньше полной пачки, от 10ms до 5m. Это же обычное опоздание задания после его срока. |
| `JOBS_BATCH_SIZE` | `10` | Задания, которые берет один захват, от 1 до 100. Они выполняются друг за другом под lease, взятыми вместе, поэтому пачка должна укладываться в один lease с запасом. |
| `JOBS_LEASE_DURATION` | `1m` | Сколько захваченное задание принадлежит одному worker, от 1s до 1h. Ограничивает одну попытку обработчика и служит серверными `statement_timeout` и `idle_in_transaction_session_timeout` транзакции задания. Упавший worker задерживает свои задания не больше чем на это время. |
| `JOBS_MAX_ATTEMPTS` | `5` | Попытки задания без собственного лимита до перехода в dead, от 1 до 100. Сбои базы данных вне обработчика и остановка не учитываются. |
| `JOBS_BACKOFF_INITIAL` | `1s` | Задержка перед первым повтором неудачного задания; удваивается с каждой неудачной попыткой. Этот же backoff разносит захваты, пока база данных недоступна. |
| `JOBS_BACKOFF_MAX` | `5m` | Наибольшая задержка перед повтором, от `JOBS_BACKOFF_INITIAL` до 24h. |
| `JOBS_SHUTDOWN_GRACE` | `5s` | Время, за которое задание в работе может зафиксироваться после начала остановки; не больше `SHUTDOWN_TIMEOUT`. После него транзакция откатывается, а задание освобождается незавершенным. |
Сроки и lease сравниваются по часам backend, а не базы данных, поэтому держите часы всех хостов backend синхронизированными через NTP. Спешащие часы запускают задания раньше и раньше перехватывают lease; блокировка строки все равно не дает выполнить задание второй раз, пока работает обработчик.
Бюджет остановки. Worker останавливается параллельно с другими workers: `JOBS_SHUTDOWN_GRACE` (5s) на задание в работе, до 5s на откат отмененной транзакции и до 5s на освобождение незавершенных заданий, всего не больше 15s. Это укладывается в первую фазу бюджета из раздела [Обработчики событий](#обработчики-событий), поэтому общий бюджет остается около 23s внутри `stop_grace_period: 30s`; увеличивайте его вместе с `JOBS_SHUTDOWN_GRACE`. Если backend убит, его задания остаются `running` до истечения lease, а затем выполняются на другом экземпляре или после перезапуска.
У worker собственный пул PostgreSQL не больше чем на два соединения. Несколько экземпляров backend делят задания: каждый захват пропускает строки, заблокированные другим экземпляром, и каждый экземпляр может выполнять любой зарегистрированный вид.
Оператор следит за `lincodex_scheduled_jobs_total{kind,outcome}` на внутреннем endpoint /metrics: `done`, `retry` (попытка не удалась, задание ждет backoff), `dead`, `lease_lost` (задание отменили или захватили заново, пока его держал этот экземпляр) и `released` (возвращено незавершенным при остановке или после сбоя базы данных). Каждый ряд существует с нулем с момента старта, поэтому alert можно строить как `increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0`. `lincodex_scheduled_jobs_due` и `lincodex_scheduled_jobs_oldest_due_age_seconds` описывают наступившие задания, которые ждут worker; если возраст растет дольше нескольких интервалов опроса, их никто не захватывает, например потому что worker выключен, база данных недоступна или ни у одного работающего экземпляра нет обработчика их вида. `lincodex_scheduled_jobs_dead` считает dead задания. Каждый экземпляр сообщает одни и те же значения по всей базе, поэтому агрегируйте их через `max`. Во время поэтапного развертывания, которое добавляет новый вид, его уже наступившие задания ждут, пока заработает экземпляр с обработчиком, и возраст может ненадолго выглядеть как застрявший worker; держите alert по возрасту дольше, чем длится развертывание. Журналы содержат компонент `scheduled_jobs`, владельца lease, ID задания, вид, номер попытки и класс ошибки, но никогда ключ или payload; dead задание пишется на уровне error как `scheduled job is dead; it needs an operator`.
#### Dead задания
`last_error_class` объясняет, почему задание стало dead: `handler_rejected` (обработчик никогда не сможет его выполнить), `handler_panic` (строка журнала `scheduled job handler panicked` с тем же ID задания содержит стек), `lease_expired` (последняя начатая попытка остановилась незавершенной, обычно из-за падения или kill, или ее сбой не удалось записать, потому что в этот момент была недоступна база данных) или класс последней неудачной попытки после исчерпания попыток: `handler_failed`, `timeout`, `conflict` или `effect_rejected`, а также `completion_conflict` (обработчик изменил собственное задание иначе, чем отменой). Список dead и просроченных заданий можно получить через psql в контейнере базы данных (команда открытия описана в разделе [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск)):
SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class,
due_at, available_at, updated_at
FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at;
SELECT kind, status, count(*), min(available_at)
FROM scheduled_jobs
WHERE status IN ('pending', 'failed', 'running') AND available_at <= now()
GROUP BY kind, status;
Ключ указывает на продуктовую запись, например ID приглашения; payload содержит только идентификаторы. После устранения причины, обычно развертывания исправленного обработчика, запустите dead задание снова. Меняйте только `available_at` и никогда `due_at`: обработчик принимает решение по сроку в `due_at`.
UPDATE scheduled_jobs
SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp()
WHERE id = <id> AND status = 'dead';
Worker захватит его в течение одного интервала опроса и выполнит с новыми попытками. Чтобы отказаться от dead задания, задайте `status = 'cancelled'` с тем же условием; его ключ остается занятым, поэтому продуктовый сценарий не сможет запланировать его снова. Не удаляйте строки: удаленный ключ можно запланировать снова и выполнить второй раз.
## Почта
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
+7 -1
View File
@@ -57,7 +57,7 @@ Frontend зависимости выбираются из актуальных s
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`) и таблица заданий по сроку (`scheduled_jobs`, продуктовый вид задания пока не зарегистрирован), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
## Установка и цикл работы
@@ -199,6 +199,12 @@ Backend, запущенный напрямую с зарегистрирован
Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
### Задания по сроку
Чтобы выполнить что-то в срок, например истечение или напоминание, запланируйте задание в собственной транзакции usecase: соберите его через `domain.NewScheduledJob` (вид, например `invitation.response_deadline`, ключ логического задания, например ID агрегата, срок по внедренным часам и payload только из идентификаторов) и вызовите `unit.ScheduledJobs().Schedule(ctx, job)`. Побеждает первое планирование вида и ключа, повтор игнорируется, поэтому для нового повторения используйте новый ключ, например `<id>:<version>`. Отменяйте через `unit.ScheduledJobs().Cancel(ctx, kind, key)` до блокировки продуктовых строк, которые трогает обработчик.
Затем реализуйте `inbound.JobHandler` в пакете usecase модуля: верните вид из `JobKind()` и пишите эффект в `Handle` только через полученный `UnitOfWork`, принимая решение по `job.DueAt` и текущему продуктовому состоянию, чтобы обработчик ничего не делал, если состояние уже изменилось. Обработчик может отменить собственное задание через unit, например из общего helper, который отменяет срок; тогда задание считается выполненным. Иначе менять собственное задание нельзя. Для задания, которое нельзя выполнить никогда, верните ошибку, оборачивающую `inbound.ErrJobRejected`; любая другая ошибка повторяется. Добавьте обработчик в `jobHandlers()` в `backend/internal/bootstrap/jobs.go`. Принимайте часы как `func() time.Time` и проверяйте сроки через `testutil.FakeClock` из `backend/pkg/testutil/` и `Worker.RunDue`, который один раз выполняет наступившие задания без опроса, как это делает `TestScheduledJobs`. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку); настройки, метрики и порядок работы с dead заданиями - в [DEPLOY.md](DEPLOY.md#задания-по-сроку); тесты - в [TESTING.md](TESTING.md#тесты-заданий-по-сроку).
## Читаемость Go-кода
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
+21
View File
@@ -185,6 +185,27 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор не вызывает транспорт: worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, - это TASK-016.
## Тесты заданий по сроку
Unit-тесты (`make -C backend test`) проверяют runtime заданий с хранилищем в памяти, которое повторяет правила захвата, проверки lease и освобождения хранилища PostgreSQL, и с fake clock из `backend/pkg/testutil/` (`internal/worker/jobrunner/`): выполняются только наступившие задания зарегистрированных видов в порядке срока, а задание со сроком через два дня выполняется ровно тогда, когда часы его достигают; неудачное задание повторяется после backoff по часам, не захватывается раньше и после последней попытки становится dead с записью в журнал уровня error и метриками; `ErrJobRejected` и panic завершают задание после одной попытки, а значение panic не попадает в журнал; обработчик, переживший свой lease, падает как `timeout`; задание, которое другой worker захватил до начала, пропускается без вызова обработчика; задание с истекшим lease последней начатой попытки становится dead без выполнения; медленное первое задание пачки не тратит единственную попытку следующего и не убивает его, а другой worker выполняет задание, которое занятый worker захватил, но не начал, на той же попытке; сбой базы данных вне обработчика освобождает задание и остаток пачки без учета попыток; неудачные захваты ждут backoff, а не крутятся в цикле; при остановке задание в работе завершается внутри grace, задание, которое его переживает, отменяется и освобождается без эффекта и без учтенной попытки, а захваченные, но не начатые задания освобождаются; panic во время остановки все равно делает задание dead; backlog всех видов попадает в метрики. Остальные unit-тесты покрывают правила задания (`internal/domain/`: вид, ключ, плоский payload, лимит размера, срок в UTC с точностью до микросекунд), настройки (`config/`), счетчики и gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), а в `internal/bootstrap/` - случаи без запуска с их строками журнала, пустой реестр видов, повторный вид и приложение, которое запускает worker против недоступной базы и все равно останавливается.
`TestScheduledJobs` в `backend/integration_test/scheduled_jobs_test.go` использует `bootstrap(t, postgresService)`. Его обработчик существует только в тесте: он пишет одну строку в `job_test.effects`, таблицу без уникального ключа, в транзакции, которая завершает задание, поэтому второй эффект остался бы виден. У каждого имитируемого процесса свой пул, хранилище и worker; создание нового означает перезапуск. Все решения о сроках и lease принимаются по одному `FakeClock`. Последовательные случаи:
- Задания на разные даты: два задания запланированы через `UnitOfWork.ScheduledJobs()` на завтра и через три дня, а повторное планирование игнорируется и не сдвигает срок. В начале ничего не выполняется; после перезапуска и одного дня выполняется первое задание; после еще одного перезапуска второе не выполняется за микросекунду до срока и выполняется в свой срок; через месяц снова ничего не выполняется. Эффектов по одному на задание, в порядке сроков.
- Два worker с собственными пулами одновременно крутят свои циклы над 40 наступившими заданиями: все задания выполнены, эффектов ровно 40 для 40 разных заданий.
- Обработчик, переживший lease по часам, по-прежнему держит блокировку строки задания, поэтому захват другого worker пропускает задание; затем первый worker завершает его с одним эффектом.
- Истекший lease: worker A захватывает и запускает задание и останавливается внутри него. Worker B не может захватить его за микросекунду до истечения lease и выполняет его в момент истечения, с двумя учтенными попытками и записанным `lease_expired`. Поздний запуск worker A отклоняется, его поздний `Run` возвращает `ErrJobLeaseLost` без вызова обработчика, а поздняя запись сбоя и освобождение отклоняются; эффект остается один.
- Начатая попытка задания с лимитом в одну попытку, lease которой истек: следующий захват делает задание dead с одной попыткой и `lease_expired` без вызова обработчика.
- Захват, который так и не начался, с лимитом в одну попытку: после истечения lease другой worker выполняет задание на той же попытке без класса ошибки.
- Медленное первое задание пачки работает дольше lease захвата: следующее задание с лимитом в одну попытку освобождается с сохраненной попыткой и выполняется в следующем проходе. С двумя worker, пока медленное задание держит свою строку, другой worker захватывает только ожидающее задание и выполняет его на единственной попытке; занятый worker затем считает его `lease_lost`.
- Обработчик, который отменяет собственное задание через unit: его эффект фиксируется, задание остается `cancelled`, а следующее задание прохода выполняется. Обработчик, который меняет собственное задание иначе, переводит его в dead с `completion_conflict` и не оставляет эффекта.
- Корректная остановка: обработчик пишет эффект и переживает grace в 200 ms. После остановки эффект откачен, задание в `pending` без попыток и без lease, а новый процесс сразу выполняет его, не дожидаясь lease.
- Неудачное задание с собственным лимитом в две попытки: первая попытка сдвигает на backoff только `available_at` и сохраняет `due_at`, задание не захватывается до окончания backoff, вторая попытка делает его dead, обработчик оба раза видел исходный срок, эффектов нет, backlog показывает одно dead задание, а счетчики - один `retry` и один `dead`.
- Отмена: отмененное задание никогда не захватывается, повторная отмена и новое планирование того же ключа ничего не делают, наступивших заданий нет.
- Отмена во время выполнения: пока обработчик держит задание, отмена в другой транзакции видна в `pg_stat_activity` как ожидание блокировки строки; после фиксации обработчика задание выполнено, а отмена возвращает false.
`TestPostgresMigrations` также проверяет, что миграция 00008 создает и удаляет `scheduled_jobs`. Набор использует один PostgreSQL и тестовый вид задания. Он не измеряет пропускную способность, не покрывает расхождение часов между экземплярами, переключение базы данных и продуктовый обработчик и не проверяет доставку alerts.
## Шардирование интеграционных тестов
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.