Skip to main content

Crate navree_queue

Crate navree_queue 

Source
Expand description

QueueModule: database and memory job queues, workers, retries with backoff, unique and delayed jobs, job batches, and operations (user-visible long work with progress).

  • QueueModule is global. It provides Queue and registers it as the app’s dyn Dispatcher, so navree-mail, navree-events, navree-notify and navree-schedule queue through it without depending on this crate. Its settings are QueueOptions (configuration section queue).
  • Jobs implement navree_contracts::Job; a module registers each job type with m.job::<J>() (ModuleBuilderJobsExt). Dispatching a type no module registered fails with QueueError::UnknownJob.
  • Drivers (QueueDriver): database (tables jobs and failed_jobs, created by the queue migration set; workers in several processes share them), memory (one process, for tests and development) and redis (the QueueStore provider named redis, from navree-redis’s RedisModule). They behave the same; QueueStore states the contract other drivers implement, and a module registers one under a name of its own with m.queue_store, which queue.driver then selects.
  • Workers (Queue::work, command queue:work) reserve jobs atomically (SQLite: UPDATE … WHERE id = (SELECT … LIMIT 1) RETURNING; PostgreSQL adds FOR UPDATE SKIP LOCKED; MySQL, which cannot return the rows of an UPDATE, locks the candidate with SELECT … FOR UPDATE SKIP LOCKED in a short transaction first), run each attempt within the job’s timeout_secs (a panic or a timeout is a failed attempt), retry failed attempts after Backoff::delay_for and move a job that used its max_attempts to 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 plus STALE_RESERVATION_GRACE_SECS.
  • Unique jobs (unique_for_secs): while an identical job (same type and payload, or the envelope’s unique_key) is pending and inside the window, dispatching returns the pending job’s id instead of queueing.
  • Queue::dispatch_in queues as part of a unit of work: nothing is queued if it rolls back. Plain dispatches (and dyn 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, table job_batches): jobs dispatched together and followed as one, with then, catch and finally callbacks; the first failure cancels the rest unless the batch allow_failures. A job reports progress with ctx.progress(done, total, note) and sees a cancelled batch through it (JobCancelled).
  • Operations (Operations, table operations): user-visible long work with an owner, a workspace, a status, progress, a result and a heartbeat, driven by its job or batch. Routes GET /api/operations, GET /api/operations/{id}, the SSE stream GET /api/operations/{id}/events and the cooperative cancel DELETE /api/operations/{id} (OperationsController); every change is broadcast as operation.updated on the private channel operations.{id}. The owner and holders of operations.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 with ScheduleModule, or queue:watchdog from system cron.
  • Every attempt is logged at target navree::job with the job type (name), id, queue, attempt, duration_ms and outcome (succeeded, released, failed or cancelled); 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_jobs and Queue::pending_job, Queue::failed_job and Queue::forget (delete one failed job).
  • Supervision: Queue::work_supervised runs workers for a supervisor (navree-fleet): its own concurrency and stop token, and WorkHooks asked before each reservation (pause) and told every Attempt.
  • 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:watchdog and queue:prune [--hours N].
  • Testing: QueueFake records dispatched jobs and batches for assertions; Queue::run_pending runs 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§

uiui
A Navree UI part for an operation (the ui feature): 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 dispatch or dispatch_in (or the same methods on Queue: dispatch_batch, dispatch_batch_in).
CancellationToken
The cancellation token Supervision::stop takes (tokio-util’s). A token which can be used to signal a cancellation request to one or more tasks.
FailedJob
A job that used up its attempts (or could not run at all), as kept in failed_jobs until it is retried or flushed.
FailedJobBrief
A failed job without its payload, as an overview lists it.
FailedSummary
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: what Queue::find_batch and Queue::batches return.
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::insert receives. Times are Unix milliseconds.
Operation
An operation to start with Operations::start: Operation::new("export").owner(user_id).workspace(workspace_id).
OperationProgress
How far an operation got.
OperationRecord
A stored operation: what Operations returns, GET /api/operations/{id} answers, the SSE stream sends and operation.updated broadcasts.
Operations
User-visible long work: provided and exported by QueueModule (it needs DatabaseModule).
OperationsController
The routes of operations, under {http.api_prefix}/operations (default /api/operations). They mount when queue.operations.routes is true (the default) and the app has DatabaseModule and an authenticator. Every route needs a signed-in user; an operation is visible to its owner and to holders of operations.view (app-wide or in its workspace), and is a 404 to everyone else.
OperationsOptions
Operations settings: configuration section queue.operations.
PendingJob
A job that is not finished yet, as Queue::pending_jobs lists it.
PendingQuery
Which pending jobs Queue::pending_jobs lists.
Queue
The job queue: provided and exported by QueueModule, which also registers it as the app’s dyn Dispatcher.
QueueFake
A queue that records jobs instead of running them, for tests.
QueueModule
The queue module. Global; provides and exports Queue (also as the app’s dyn Dispatcher, so mail, events, notifications and schedules queue through it, and as the dyn JobMonitor behind ctx.progress(..)), Operations and QueueOptions; contributes the queue migrations (tables jobs, failed_jobs, job_batches and operations), the OperationsController routes, the private channel operations.{id} and the scheduled task queue.watchdog (every minute, in apps with ScheduleModule); registers the 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:watchdog and queue:prune [--hours N].
QueueOptions
QueueModule settings: configuration section queue.
QueueStatus
One queue’s unfinished jobs at a moment, from Queue::status.
RecordedBatch
A batch QueueFake recorded: the stored batch, its jobs and its callbacks.
ReservedJob
A job a worker reserved: what QueueStore::reserve returns.
Supervision
How Queue::work_supervised runs besides its WorkOptions.
SweepReport
What one Operations::sweep did.
WorkOptions
How a Queue::work call runs.
WorkStats
What a Queue::work call did.

Enums§

AttemptOutcome
How one attempt of a job ended.
OperationStatus
Where an operation is.
PendingState
Where a job that is not finished yet stands (PendingJob::state).
QueueDriver
Where queued jobs are stored.
QueueError
What can go wrong when queueing or working jobs.
RetryTarget
Which failed jobs Queue::retry puts back on their queues. Converts from a string: "all" is All, 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_secs plus 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§

ModuleBuilderQueueExt
Registers queue stores on a ModuleBuilder: use navree::plugin::prelude::*; (or this trait) brings the method.
QueueStore
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.
WorkHooks
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 (see RealtimeModule). A nudge carries nothing; the page fetches the operation again.