Watchfire
Jobs and the queue
Jobs. A job is a serializable struct (smeltery make:job SendWelcome), registered with w.job::<SendWelcome>():
use serde::{Deserialize, Serialize};
use smeltery::watchfire::prelude::*;
#[derive(Serialize, Deserialize)]
pub struct SendWelcome {
pub user_id: i64,
}
impl Job for SendWelcome {
const NAME: &'static str = "send_welcome";
fn max_attempts(&self) -> u32 {
3 // the default
}
async fn handle(&self, ctx: JobCtx) -> Result<(), AgentError> {
ctx.log().info(format!("welcoming user {}", self.user_id));
Ok(())
}
}
async fn register_user(app: smeltery::App) -> smeltery::Result<&'static str> {
SendWelcome { user_id: 1 }.dispatch(&app).await?;
SendWelcome { user_id: 1 }.dispatch_later(&app, 10.mins()).await?;
Ok("welcome")
}
Queue workers (queue#0 … queue#n, WATCHFIRE_WORKERS, default 2) take jobs one at a time. The database driver
reserves a job with one atomic UPDATE … WHERE reserved_at IS NULL, so no two workers run the same job;
reservations older than twice WATCHFIRE_JOB_TIMEOUT (a worker that died) are released. A failed attempt (an error,
a panic, or running longer than WATCHFIRE_JOB_TIMEOUT) is retried after Job::backoff(attempt) (5 s, doubling, at
most 10 minutes); after max_attempts the job moves to the dead letters, as does a job with an unknown name or a
payload that does not decode. Moving a job to the dead letters and retry moving it back are one database
transaction each, so the job is in exactly one of the two tables. A job reserved for an attempt beyond max_attempts
(its last attempt ended without its outcome being stored) goes to the dead letters without running again. A job still
running at shutdown goes back to the queue. Each job is recorded as a run of its worker, with the job name. Error
texts stored with runs, agents and dead letters keep their first 8 KiB (marked as truncated). The jobs and
dead_letters tables hold each job's payload as plain JSON, and the API's GET /jobs shows the dead letters'
payloads; dead letters stay until they are retried or deleted (the memory driver keeps the latest 1000).
With QUEUE_DRIVER=redis (feature redis of smeltery) the jobs and dead letters live on the Redis server of
REDIS_URL (rediss:// uses rustls), under keys that start with QUEUE_PREFIX (default
<app name in snake case>_queue_) and {default}:: a hash per job and per dead letter, and sorted sets of the
waiting, reserved and dead ones. {default} is a hash tag, so all of the queue's keys share one hash slot. The driver
connects to one Redis server (a standalone server, or the primary of a replicated one), not to Redis Cluster. Every
queue operation is one Lua script (sent by its SHA-1 with EVALSHA), which Redis runs atomically: each job is reserved
by one worker across all processes on that server and prefix, and a job is waiting, reserved or a dead letter, never
two of them. Order, attempts, backoff, stale reservations, dead letters and the dashboard's retry and delete work as
with the database driver. The driver connects on first use and reconnects by itself; every call has the
WATCHFIRE_STORE_TIMEOUT budget. CACHE_PREFIX is compared with the start of the queue's keys,
<QUEUE_PREFIX>{default}:: neither may start with the other, and QUEUE_PREFIX has no { or }; otherwise the app
refuses to boot, because cache:clear on Redis removes every key that starts with CACHE_PREFIX.
The queue's keys have no expiry. With the maxmemory-policy noeviction (or a volatile-* policy, which only evicts
keys with an expiry) Redis keeps every queued job; when its memory is full it refuses new jobs, and dispatch returns
that error. Redis's persistence (RDB or AOF) decides which jobs survive a restart of Redis: writes it had not saved yet
are lost, so a job can be lost or run again. New job and dead-letter ids never reuse the id of a job or dead letter
that still exists, also when the id counter itself was among the lost writes.