Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Queue

A job is a struct that implements Job; pushing it stores the struct as JSON, and a worker runs it with retries, a timeout and a failed list.

use laterite_core::queue::{Job, JobCx, JobError, QueueRegistry};
use laterite_core::strata::async_trait;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct SendDigest {
    user_id: i64,
}

#[async_trait]
impl Job for SendDigest {
    const NAME: &'static str = "acme.blog::send_digest";

    async fn run(&self, cx: &JobCx) -> Result<(), JobError> {
        digest::send(cx.db(), self.user_id).await?;
        Ok(())
    }
}

fn register(&self, registry: &mut Registry) {
    registry.add_job::<SendDigest>();
}
ctx.queue().push(&SendDigest { user_id: 7 }).await?;
ctx.queue().push_in(&SendDigest { user_id: 7 }, Duration::from_secs(600)).await?;
ctx.queue().push_at(&SendDigest { user_id: 7 }, tonight).await?;
MethodDoes
push(&job)Stores the job, due now. Pushed::Queued(id), Pushed::Ran in inline mode, Pushed::Duplicate when its unique key is already waiting.
push_in(&job, delay)Due after delay.
push_at(&job, when)Due at when.
counts()How many jobs wait and run on each queue.
failed()The failed list, newest first.
retry(id) / forget(id)Put a failed job back, or drop it; None for every one.
clear(queue)Drops the waiting jobs on one queue, or on all with None.

A job whose type is not registered is refused at push with CoreError::Validation.

Set the job’s rules

#[async_trait]
impl Job for SendDigest {
    const NAME: &'static str = "acme.blog::send_digest";
    async fn run(&self, cx: &JobCx) -> Result<(), JobError> { /* ... */ }

    fn queue(&self) -> String { "mail".into() }
    fn tries(&self) -> u32 { 5 }
    fn backoff(&self, attempt: u32) -> Duration { Duration::from_secs(30 * u64::from(attempt)) }
    fn timeout(&self) -> Option<Duration> { Some(Duration::from_secs(120)) }
    fn retry_until(&self) -> Option<DateTime<Utc>> { Some(Utc::now() + Duration::hours(6)) }
    fn unique_key(&self) -> Option<String> { Some(format!("digest:{}", self.user_id)) }
}
MethodDefaultMeaning
queue()defaultThe queue the job lands on.
tries()3Attempts before the job fails; 0 leaves it to retry_until.
backoff(attempt)10 s, doublingThe wait after attempt attempt failed.
timeout()60 sThe longest one attempt may run; None for no limit.
retry_until()NoneKeep retrying until this moment, whatever tries says.
unique_key()NoneA push while a job with this key waits or runs is dropped, scheduled pushes included.
ReturnEffect
Ok(())The job is removed.
Err(JobError::retry(message))Released for the next attempt after the backoff, or failed on the last one.
Err(JobError::fail(message))Failed at once, whatever tries remain.
Err(JobError::release(wait, reason))Back after wait on the same attempt: a rate limit or a Retry-After.
async fn run(&self, cx: &JobCx) -> Result<(), JobError> {
    let token = cx.crypt().and_then(|c| c.decrypt(FIELD_PURPOSE, b"api_token", &sealed).ok());
    match acme::api::fetch(token).await {
        Err(acme::api::Error::Limited { retry_after }) => Err(JobError::release(retry_after, "rate limited")),
        Err(e) => Err(JobError::retry(e)),
        Ok(page) => {
            cx.queue().push(&StorePage { page }).await?;
            Ok(())
        }
    }
}
MethodReturns
db(), events(), cache(), parameters()The application’s services.
queue()The queue, to push further jobs.
crypt()The application’s crypt, None on a queue built without one.
attempt()Which attempt this is, from 1.
queue_name()The queue the job was taken from.
id()The job’s row id, None inline.

Configure the queue

# config/default.toml
[queue]
store = "auto"            # auto | database | redis
mode = "worker"           # worker | external | inline
workers = 2
queues = ["default"]
retry_after_seconds = 90
poll_seconds = 1
# url = "redis://127.0.0.1:6379/0"
# prefix = "acme"
KeyDescription
queue.storeWhere jobs wait. auto is database; redis needs the redis feature of laterite-core and queue.url.
queue.urlThe Redis URL for the redis store.
queue.prefixThe prefix of every Redis key. Default laterite.
queue.modeworker runs the workers in the application process; external leaves them to queue work; inline runs a job as it is pushed.
queue.workersHow many workers the process runs in worker mode. Default 2.
queue.queuesThe queues a worker takes from, in priority order: a job waiting on an earlier queue is taken first. Default ["default"].
queue.retry_after_secondsAfter this long a claimed job counts as abandoned and is claimed again. Longer than any job’s timeout. Default 90.
queue.poll_secondsHow long an idle worker waits before looking again. Default 1.

Run a worker apart

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    Bootstrap::new("config")
        .module(migrations::AppModule)
        .run()
        .await
}
lat queue work                       # cargo run -- queue work
lat queue work --once
lat queue work --stop-when-empty --queue high,default
acme queue work                      # the built binary

Bootstrap::run reads the process’s arguments: serve (the default), queue work or schedule run. With queue.mode = "external", the serving process runs no worker.

Act on the failed list

lat queue list
lat queue failed
lat queue retry 42
lat queue retry all
lat queue forget 42
lat queue flush --queue mail
use laterite_core::queue::JobFailed;
use laterite_core::{EventCx, EventError, Listener};

struct Alert;

#[laterite_core::strata::async_trait]
impl Listener<JobFailed> for Alert {
    async fn handle(&self, cx: &EventCx<'_>, failed: &JobFailed) -> Result<(), EventError> {
        acme::alerts::record(cx.db(), &failed.name, &failed.error).await?;
        Ok(())
    }
}

fn register(&self, registry: &mut Registry) {
    registry.listen::<JobFailed>(Alert);
}

A job reaching the failed list announces queue.job_failed with its id, name, queue, attempts and error.

Grant the Jobs screen

# a role's permissions
- backend.manage_jobs
PermissionGrants
backend.manage_jobsSettings → System → Jobs: the waiting and running counts per queue, the failed list with each job’s payload and error, Retry and Forget for one job or all.

Test a job

let queue = Queue::inline(vec![JobReg::of::<SendDigest>()], services);
assert_eq!(queue.push(&SendDigest { user_id: 7 }).await?, Pushed::Ran);
# config/test.toml
[queue]
mode = "inline"