Expand description
§navree-queue
QueueModule: database and memory job queues, workers, retries with
backoff, unique and delayed jobs, job batches, and operations
(user-visible long work with progress).
QueueModuleis global. It providesQueueand registers it as the app’sdyn Dispatcher, so navree-mail, navree-events, navree-notify and navree-schedule queue through it without depending on this crate. Its settings areQueueOptions(configuration sectionqueue).- Jobs implement
navree_contracts::Job; a module registers each job type withm.job::<J>()(ModuleBuilderJobsExt). Dispatching a type no module registered fails withQueueError::UnknownJob. - Drivers (
QueueDriver):database(tablesjobsandfailed_jobs, created by thequeuemigration set; workers in several processes share them),memory(one process, for tests and development) andredis(theQueueStoreprovider namedredis, from navree-redis’sRedisModule). They behave the same;QueueStorestates the contract other drivers implement. - Workers (
Queue::work, commandqueue:work) reserve jobs atomically (SQLite:UPDATE … WHERE id = (SELECT … LIMIT 1) RETURNING; PostgreSQL addsFOR UPDATE SKIP LOCKED; MySQL, which cannot return the rows of anUPDATE, locks the candidate withSELECT … FOR UPDATE SKIP LOCKEDin a short transaction first), run each attempt within the job’stimeout_secs(a panic or a timeout is a failed attempt), retry failed attempts afterBackoff::delay_forand move a job that used itsmax_attemptsto the failed jobs (Queue::failed,Queue::retry,Queue::flush_failed). A reservation abandoned by a crashed worker is taken over once it is older than the job’s timeout plusSTALE_RESERVATION_GRACE_SECS. - Unique jobs (
unique_for_secs): while an identical job (same type and payload, or the envelope’sunique_key) is pending and inside the window, dispatching returns the pending job’s id instead of queueing. Queue::dispatch_inqueues as part of a unit of work: nothing is queued if it rolls back. Plain dispatches (anddyn Dispatcher) do the same with the current unit of work (navree_db::Uow::current, e.g. the request’s while a handler runs) when there is an unfinished one.- Batches (
Batch, tablejob_batches): jobs dispatched together and followed as one, withthen,catchandfinallycallbacks; the first failure cancels the rest unless the batchallow_failures. A job reports progress withctx.progress(done, total, note)and sees a cancelled batch through it (JobCancelled). - Operations (
Operations, tableoperations): user-visible long work with an owner, a workspace, a status, progress, a result and a heartbeat, driven by its job or batch. RoutesGET /api/operations,GET /api/operations/{id}, the SSE streamGET /api/operations/{id}/eventsand the cooperative cancelDELETE /api/operations/{id}(OperationsController); every change is broadcast asoperation.updatedon the private channeloperations.{id}. The owner and holders ofoperations.view(app-wide or in the operation’s workspace) may see one. A watchdog (Operations::sweep) fails or restarts operations that stopped responding: scheduled every minute in apps withScheduleModule, orqueue:watchdogfrom system cron. - Every attempt is logged at target
navree::jobwith the job type (name), id, queue, attempt,duration_msandoutcome(succeeded,released,failedorcancelled); payloads are never logged. - Introspection:
Queue::status(a queue’s waiting, delayed and running jobs and how long its oldest job has waited),Queue::pending_jobsandQueue::pending_job,Queue::failed_jobandQueue::forget(delete one failed job). - Supervision:
Queue::work_supervisedruns workers for a supervisor (navree-fleet): its own concurrency and stop token, andWorkHooksasked before each reservation (pause) and told everyAttempt. - Commands:
queue:work [--queue a,b] [--once] [--stop-when-empty] [--max-jobs N],queue:failed,queue:retry <id|all>,queue:flush,queue:batches [--limit N],queue:watchdogandqueue:prune [--hours N]. - Testing:
QueueFakerecords dispatched jobs and batches for assertions;Queue::run_pendingruns every available job before returning.
use navree_contracts::{BoxError, Job, JobContext, JobOptions, ModuleBuilderJobsExt};
use navree_kernel::{Navree, Module, ModuleBuilder};
use navree_queue::{Queue, QueueModule};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct SendInvoice {
invoice_id: u64,
}
impl Job for SendInvoice {
const NAME: &'static str = "billing.send_invoice";
fn options() -> JobOptions {
JobOptions {
queue: "emails".into(),
max_attempts: 5,
..JobOptions::default()
}
}
async fn handle(self, ctx: JobContext) -> Result<(), BoxError> {
// Resolve services from `ctx.app`, open a unit of work, ...
let _ = (self.invoice_id, ctx.attempt);
Ok(())
}
}
struct BillingModule;
impl Module for BillingModule {
fn register(&self, m: &mut ModuleBuilder) {
m.job::<SendInvoice>();
}
}
// Anywhere with access to the app:
let id = queue.dispatch(SendInvoice { invoice_id: 42 }).await?;
fn main() -> Result<(), navree_kernel::BoxError> {
// `<app> queue:work --queue emails,default` runs the jobs.
Navree::app()
.module(navree_config::ConfigModule::for_root(
navree_config::ConfigSources::defaults(),
))
.module(navree_db::DatabaseModule::from_config())
.module(QueueModule::from_config())
.module(BillingModule)
.run()
}Modules§
- ui
ui - A Navree UI part for an operation (the
uifeature):OperationProgress, a region that follows a queued operation and ends as a link to its result.
Structs§
- Attempt
- One finished attempt, as a supervised worker tells its
WorkHooks. - Batch
- A group of jobs dispatched together and followed as one: how many are
still pending, how many failed, whether the group was cancelled, plus
callbacks for its outcome. Dispatch it with
dispatchordispatch_in(or the same methods onQueue:dispatch_batch,dispatch_batch_in). - Cancellation
Token - The cancellation token
Supervision::stoptakes (tokio-util’s). A token which can be used to signal a cancellation request to one or more tasks. - Failed
Job - A job that used up its attempts (or could not run at all), as kept in
failed_jobsuntil it is retried or flushed. - Failed
JobBrief - A failed job without its payload, as an overview lists it.
- Failed
Summary - The failed jobs in figures, and the newest of them: what a page polled every
few seconds reads, however many have failed (
Queue::failed_summary). - JobBatch
- A dispatched batch, as stored in
job_batches: whatQueue::find_batchandQueue::batchesreturn. - Membership
- What a job belongs to: a batch (as one of its jobs or as one of its callbacks) and an operation. The default belongs to neither.
- NewJob
- A job ready to be stored: what
QueueStore::insertreceives. Times are Unix milliseconds. - Operation
- An operation to start with
Operations::start:Operation::new("export").owner(user_id).workspace(workspace_id). - Operation
Progress - How far an operation got.
- Operation
Record - A stored operation: what
Operationsreturns,GET /api/operations/{id}answers, the SSE stream sends andoperation.updatedbroadcasts. - Operations
- User-visible long work: provided and exported by
QueueModule(it needsDatabaseModule). - Operations
Controller - The routes of operations, under
{http.api_prefix}/operations(default/api/operations). They mount whenqueue.operations.routesis true (the default) and the app hasDatabaseModuleand an authenticator. Every route needs a signed-in user; an operation is visible to its owner and to holders ofoperations.view(app-wide or in its workspace), and is a 404 to everyone else. - Operations
Options - Operations settings: configuration section
queue.operations. - Pending
Job - A job that is not finished yet, as
Queue::pending_jobslists it. - Pending
Query - Which pending jobs
Queue::pending_jobslists. - Queue
- The job queue: provided and exported by
QueueModule, which also registers it as the app’sdyn Dispatcher. - Queue
Fake - A queue that records jobs instead of running them, for tests.
- Queue
Module - The queue module. Global; provides and exports
Queue(also as the app’sdyn Dispatcher, so mail, events, notifications and schedules queue through it, and as thedyn JobMonitorbehindctx.progress(..)),OperationsandQueueOptions; contributes thequeuemigrations (tablesjobs,failed_jobs,job_batchesandoperations), theOperationsControllerroutes, the private channeloperations.{id}and the scheduled taskqueue.watchdog(every minute, in apps withScheduleModule); registers the commandsqueue:work [--queue a,b] [--once] [--stop-when-empty] [--max-jobs N],queue:failed,queue:retry <id|all>,queue:flush,queue:batches [--limit N],queue:watchdogandqueue:prune [--hours N]. - Queue
Options QueueModulesettings: configuration sectionqueue.- Queue
Status - One queue’s unfinished jobs at a moment, from
Queue::status. - Recorded
Batch - A batch
QueueFakerecorded: the stored batch, its jobs and its callbacks. - Reserved
Job - A job a worker reserved: what
QueueStore::reservereturns. - Supervision
- How
Queue::work_supervisedruns besides itsWorkOptions. - Sweep
Report - What one
Operations::sweepdid. - Work
Options - How a
Queue::workcall runs. - Work
Stats - What a
Queue::workcall did.
Enums§
- Attempt
Outcome - How one attempt of a job ended.
- Operation
Status - Where an operation is.
- Pending
State - Where a job that is not finished yet stands (
PendingJob::state). - Queue
Driver - Where queued jobs are stored.
- Queue
Error - What can go wrong when queueing or working jobs.
- Retry
Target - Which failed jobs
Queue::retryputs back on their queues. Converts from a string:"all"isAll, anything else a job id.
Constants§
- FAILED_
JOBS_ TABLE - The table of failed jobs.
- FAILED_
MESSAGE - The error of an operation whose job failed.
- JOBS_
TABLE - The table of queued jobs.
- JOB_
BATCHES_ TABLE - The table of job batches.
- OPERATIONS_
TABLE - The table of operations.
- OPERATION_
EVENT - The SSE event name of an operation snapshot.
- OPERATION_
UPDATED_ EVENT - The realtime event every change of an operation is broadcast as, on the
private channel
operations.{id}. - STALE_
RESERVATION_ GRACE_ SECS - A reservation older than the job’s
timeout_secsplus this many seconds is considered abandoned (its worker crashed or was killed): another worker may take the job, and that counts as a new attempt. A live worker never holds a job that long, because each attempt is cut off at its timeout. - STALLED_
MESSAGE - The error of an operation the watchdog found stalled.
Traits§
- Queue
Store - A queue driver implemented outside this crate (navree-redis’s Redis driver is one): where jobs wait, are reserved by workers and end up when they fail. Times are Unix milliseconds from the app’s clock, passed in by the queue; a store never reads its own clock to decide what is due.
- Work
Hooks - What a supervisor (navree-fleet’s workers) puts around a worker: asked before every reservation, told after every attempt. Both run on the worker’s task, so keep them quick.
Functions§
- operation_
topic - The topic of the live hub a page hears an operation change on:
operation.{id}, told to the operation’s owner and, when it has one, to the members of its workspace (seeRealtimeModule). A nudge carries nothing; the page fetches the operation again.