Expand description
Background jobs for id_effect services: a Postgres SKIP LOCKED queue on id_effect_sql,
workers, retries with backoff and cron schedules.
- A
Jobis a#[derive(Schema)]struct with a stableJob::NAME, a queue, a priority, a maximum number of attempts, an optionalUniqueKeyand a retrySchedule. Its payload is stored asjsonbthrough its schema. - The
JobQueuecapability enqueues (JobQueueExt::enqueue,enqueue) and administers jobs;JobStoreadds the worker side (claim, fenced outcomes, heartbeat, rescue).PgJobQueuestores them in the tableid_effect_jobs(migrator,PgJobQueue::ensure_schema),MemoryJobQueuein memory for tests. enqueue_ininserts a job with the caller’sSqlTransaction, so it commits or rolls back with the caller’s work.- A
Workerruns the handlers of aJobRegistrywith a concurrency limit per queue, a heartbeat and lease, rescues the jobs of crashed workers, and drains on shutdown. - With the feature
cron,enqueue_on_tickmakes a core cron entry enqueue one job per tick (deduplicated across schedulers bytick_key), andCronLeaderruns the schedule on the node holding a cluster singleton.
Every time the queue reads (run_at, leases, finished_at) comes from a
WallClock, so tests run on virtual time. Delivery is at least once:
a job whose worker died mid-run runs again, so handlers must be idempotent.
JobState is the lifecycle every queued job moves through; JobState::as_str is the value
stored in the queue table’s state column.
use id_effect_jobs::JobState;
let state: JobState = "failed".parse().unwrap();
assert!(!state.is_terminal());
assert_eq!(state.as_str(), "failed");A job, its handler, and a worker draining the queue on a test executor:
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use id_effect::{Executor, Schema, TestExecutor, UtcDateTime, WallClock, hlist, sync};
use id_effect_jobs::{
Job, JobFailure, JobOptions, JobQueueExt, JobQueueService, JobRegistry, MemoryJobQueue, Worker,
};
#[derive(Clone, Schema)]
struct Welcome {
email: String,
}
impl Job for Welcome {
const NAME: &'static str = "app.welcome";
}
let sent = Arc::new(AtomicU32::new(0));
let s = Arc::clone(&sent);
let registry = JobRegistry::new()
.register::<Welcome, JobFailure>(move |job, _ctx| {
let s = Arc::clone(&s);
sync(move || {
assert_eq!(job.email, "ada@example.com");
s.fetch_add(1, Ordering::SeqCst);
})
})
.unwrap();
let exec = TestExecutor::new();
let clock = WallClock::anchored(exec.now(), UtcDateTime::unsafe_make(1_800_000_000_000));
let store = MemoryJobQueue::new(clock);
let env = hlist![JobQueueService::new(store.clone())];
let job = Welcome { email: "ada@example.com".into() };
let program = store
.enqueue(job, JobOptions::default())
.flat_map(move |_| Worker::new(registry).run_until_idle().provide_all(env));
let done = program.fork_root(Arc::new(exec.clone()));
exec.run_until_stalled();
assert!(done.is_done());
assert_eq!(sent.load(Ordering::SeqCst), 1);Tier platform (ADR 0010 Amendment 6): the Ledger reference app under
examples/reference/ depends on it.
Structs§
- Claimed
- A job a worker claimed: it is
running, leased to that worker, with its attempt counted. - Cluster
Singleton - What
CronLeader::newis built from: the singleton and its PostgreSQL lease (id_effect_node), and the local process id (id_effect_process), so a service reaches them through this crate. Cluster singleton handle: lease + optional local pid for the holder. - Cron
Leader - Runs a
CronRegistryonly while this node holds aClusterSingleton(production: over aPgAdvisoryLease). The holder runs the registry and heartbeats the lease; once a heartbeat fails it stops its schedule, resigns and competes again after a retry interval, and a follower that acquires the lease takes the schedule over. Entries built withenqueue_on_tickinsert a tick both nodes enqueue around a handover once. Cloning shares the singleton. - Drain
Report - What
Worker::run_until_idledid. - JobContext
- What a handler knows about the attempt it runs.
- JobFilter
- Which jobs
JobQueue::listreturns: newest first, at mostlimit. - JobId
- A job’s id (the
idcolumn). - JobOptions
- Per-enqueue choices that override the
Job’s own: queue, priority, unique key, and when it may run (default: now, onJob::QUEUEwith the job’s priority and key). - JobQueue
Service - Capability: an
Arc<dyn JobStore>in the typed environment (derefs todyn JobStore). - JobRecord
- One row of the queue, as
JobQueue::listreturns it. - JobRegistry
- The handlers a
Workerruns, keyed byJob::NAME: typed when registered, erased by name, with handlers in the environmentR(provided the normal way to the worker’s effect). Cloning shares the handlers. - Memory
JobQueue JobStorein memory. Clones share the jobs. Every time is read from itsWallClock(anchor it to aTestExecutorfor virtual time); jobs do not survive a restart.enqueue_inneedsPgJobQueue.- NewJob
- A job ready to insert:
NewJob::ofencodes aJobwith its options. - Node
Name - Logical node name, BEAM-style
name@host. - Noop
Observer - The default
JobObserver: observes nothing. - PgAdvisory
Lease - What
CronLeader::newis built from: the singleton and its PostgreSQL lease (id_effect_node), and the local process id (id_effect_process), so a service reaches them through this crate. Postgres session-level advisory-lockSingletonLease— the CP production path (ADR 0009). - PgJob
Queue JobStorein the PostgreSQL tableid_effect_jobs, over anySqlClient(id_effect_sql::pg::PgSqlClientin production). Clones share the client.- Pid
- Process identifier: node + local id + incarnation.
- Priority
- A job’s priority within its queue: higher runs first (the
prioritycolumn). - Queue
- A queue name (the
queuecolumn). Cloning is cheap. - Queue
Stats - Per-queue counts, as
JobQueue::statsreturns them. - Unique
Key - Deduplicates jobs within a queue: while a job holds
key(seeUniqueScope), enqueuing another job with the same key in the same queue inserts nothing and reportsEnqueued::Duplicate. - Unknown
JobState - A
statecolumn value that names noJobState. - Wake
Signal - In-process wake-ups from a store to the workers polling it (see
JobStore::wake_signal). Cloning gives another handle to the same signal. - Worker
- Runs the jobs of a
JobRegistry. - Worker
Config - A
Worker’s settings. - Worker
Handle - The capability
Worker::layerprovides while the worker runs. - Worker
Id - The worker’s identity in the
locked_bycolumn: unique per worker process (defaulthost:pid:random).
Enums§
- Enqueued
- The result of an enqueue.
- Fenced
- Whether a worker’s outcome was recorded. Outcomes are fenced on the worker’s lease: once the lease expired and the job was rescued, the late outcome is dropped.
- JobError
- A queue operation’s failure.
- JobFailure
- Why an attempt failed, and whether to try again.
- JobState
- Lifecycle of a queued job.
- Outcome
- How an attempt ended, as a
JobObserversees it. - RunAt
- When an enqueued job may first run. Resolved on the store’s
WallClockwhen the job is inserted. - Singleton
Error - What
CronLeader::newis built from: the singleton and its PostgreSQL lease (id_effect_node), and the local process id (id_effect_process), so a service reaches them through this crate. Why a singleton acquire failed. - Unique
Scope - How long a
UniqueKeyblocks another job with the same key in the same queue.
Traits§
- Job
- A job type: its payload is the type itself, encoded with its
HasSchemaschema (derive it with#[derive(Schema)]) and stored as JSON. - JobObserver
- Hooks for metrics and the console; every method defaults to doing nothing. Called on the worker’s fibers: keep them cheap and non-blocking.
- JobQueue
- The producer and administration side of a job queue. Object safe; the typed enqueue methods
are in
JobQueueExt. - JobQueue
Ext - Typed enqueue on any
JobQueue. - JobStore
- The worker side of a job queue.
Functions§
- default_
retry - The default
Job::retry: exponential from 1 s, capped at 1 h, jittered by ±20 %. - enqueue
- Enqueues
jobwithoptson theJobQueueServiceinR. - enqueue_
in - Enqueues
jobwith the caller’s transactiontx: the row commits or rolls back with the caller’s work (the transactional outbox for jobs). A unique-key conflict inserts nothing (Enqueued::Duplicate) and leavestxusable.clockis the queue’s clock (bind the same one thePgJobQueuereads). Needs only theid_effect_jobstable, no queue capability; it does not wake an in-process worker (it polls). - enqueue_
on_ tick - A cron entry named
namethat enqueuesmake(tick)on theJobQueueServiceinRat every fire time ofcron, keyedtick_key(name, tick)and runnable at the tick. A duplicate (another scheduler enqueued the tick) is a success; a queue error is the run’s failure. - job_
queue_ env - A
JobQueueEnvwrappingstore. - memory_
job_ queue_ layer - A
Layerprovidingstoreas theJobQueueService(keep a clone to inspect it). - migrator
- The crate’s schema as an
id_effect_sqlMigratortracked in its own table_id_effect_jobs_migrations, so the version numbers never collide with the application’s migrations. Run it at startup (migrator().run_on(client)ormigrator().layer()); it takes the migration advisory lock, so replicas starting together apply it once. The alternative is to copymigrations/0001_id_effect_jobs.{up,down}.sqlinto the application’s own migrations. - pg_
job_ queue_ layer - A
Layerproviding aPgJobQueue(system clock) as theJobQueueService, over theSqlClientServiceit needs (feed itPgSqlClient::layer(config)withprovide_to). It does not create the table: runmigratororPgJobQueue::ensure_schemaat startup. - retry_
delay - The delay before the attempt after attempt number
attempt(1-based) failed withfailure, orNonewhenscheduleis done. - tick_
key - The
UniqueKeyof the job the cron entrynameenqueues fortick:{name}@{tick}(the tick as an RFC 3339 UTC instant), held until the row is pruned.
Type Aliases§
- JobQueue
Env - The minimal typed environment holding only
JobQueueService.