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

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