Skip to main content

Crate id_effect_jobs

Crate id_effect_jobs 

Source
Expand description

Background jobs for id_effect services: a Postgres SKIP LOCKED queue on id_effect_sql, workers, retries with backoff and cron schedules.

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.
ClusterSingleton
What CronLeader::new is 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.
CronLeader
Runs a CronRegistry only while this node holds a ClusterSingleton (production: over a PgAdvisoryLease). 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 with enqueue_on_tick insert a tick both nodes enqueue around a handover once. Cloning shares the singleton.
DrainReport
What Worker::run_until_idle did.
JobContext
What a handler knows about the attempt it runs.
JobFilter
Which jobs JobQueue::list returns: newest first, at most limit.
JobId
A job’s id (the id column).
JobOptions
Per-enqueue choices that override the Job’s own: queue, priority, unique key, and when it may run (default: now, on Job::QUEUE with the job’s priority and key).
JobQueueService
Capability: an Arc<dyn JobStore> in the typed environment (derefs to dyn JobStore).
JobRecord
One row of the queue, as JobQueue::list returns it.
JobRegistry
The handlers a Worker runs, keyed by Job::NAME: typed when registered, erased by name, with handlers in the environment R (provided the normal way to the worker’s effect). Cloning shares the handlers.
MemoryJobQueue
JobStore in memory. Clones share the jobs. Every time is read from its WallClock (anchor it to a TestExecutor for virtual time); jobs do not survive a restart. enqueue_in needs PgJobQueue.
NewJob
A job ready to insert: NewJob::of encodes a Job with its options.
NodeName
Logical node name, BEAM-style name@host.
NoopObserver
The default JobObserver: observes nothing.
PgAdvisoryLease
What CronLeader::new is 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-lock SingletonLease — the CP production path (ADR 0009).
PgJobQueue
JobStore in the PostgreSQL table id_effect_jobs, over any SqlClient (id_effect_sql::pg::PgSqlClient in production). Clones share the client.
Pid
Process identifier: node + local id + incarnation.
Priority
A job’s priority within its queue: higher runs first (the priority column).
Queue
A queue name (the queue column). Cloning is cheap.
QueueStats
Per-queue counts, as JobQueue::stats returns them.
UniqueKey
Deduplicates jobs within a queue: while a job holds key (see UniqueScope), enqueuing another job with the same key in the same queue inserts nothing and reports Enqueued::Duplicate.
UnknownJobState
A state column value that names no JobState.
WakeSignal
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.
WorkerConfig
A Worker’s settings.
WorkerHandle
The capability Worker::layer provides while the worker runs.
WorkerId
The worker’s identity in the locked_by column: unique per worker process (default host: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 JobObserver sees it.
RunAt
When an enqueued job may first run. Resolved on the store’s WallClock when the job is inserted.
SingletonError
What CronLeader::new is 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.
UniqueScope
How long a UniqueKey blocks another job with the same key in the same queue.

Traits§

Job
A job type: its payload is the type itself, encoded with its HasSchema schema (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.
JobQueueExt
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 job with opts on the JobQueueService in R.
enqueue_in
Enqueues job with the caller’s transaction tx: 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 leaves tx usable. clock is the queue’s clock (bind the same one the PgJobQueue reads). Needs only the id_effect_jobs table, no queue capability; it does not wake an in-process worker (it polls).
enqueue_on_tick
A cron entry named name that enqueues make(tick) on the JobQueueService in R at every fire time of cron, keyed tick_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 JobQueueEnv wrapping store.
memory_job_queue_layer
A Layer providing store as the JobQueueService (keep a clone to inspect it).
migrator
The crate’s schema as an id_effect_sql Migrator tracked 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) or migrator().layer()); it takes the migration advisory lock, so replicas starting together apply it once. The alternative is to copy migrations/0001_id_effect_jobs.{up,down}.sql into the application’s own migrations.
pg_job_queue_layer
A Layer providing a PgJobQueue (system clock) as the JobQueueService, over the SqlClientService it needs (feed it PgSqlClient::layer(config) with provide_to). It does not create the table: run migrator or PgJobQueue::ensure_schema at startup.
retry_delay
The delay before the attempt after attempt number attempt (1-based) failed with failure, or None when schedule is done.
tick_key
The UniqueKey of the job the cron entry name enqueues for tick: {name}@{tick} (the tick as an RFC 3339 UTC instant), held until the row is pruned.

Type Aliases§

JobQueueEnv
The minimal typed environment holding only JobQueueService.