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

@@ -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)
}
}