glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Background jobs, kept in the database as Rails' Solid Queue keeps them:
//! enqueued in the same transaction as the work that asks for them, run by
//! workers the app starts, retried with backoff, and left marked failed
//! after their last attempt.
//!
//! ```ignore
//! #[derive(Serialize, Deserialize)]
//! pub struct SendReport {
//!     pub report_id: i64,
//! }
//!
//! impl Job for SendReport {
//!     const NAME: &'static str = "send_report";
//!
//!     async fn perform(self) -> glacier::Result<()> {
//!         // …
//!         Ok(())
//!     }
//! }
//!
//! SendReport { report_id: report.id }.enqueue().await?;
//!
//! // The app runs them (two workers by default):
//! App::new().database(repo).jobs(Jobs::new().register::<SendReport>())
//! ```
//!
//! The table comes from a migration: `glacier::jobs::create_table(s)`.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::db::migration::Schema;
use crate::db::{self, Repo, Sql, Value};
use crate::error::{Error, Result};

const TABLE: &str = "glacier_jobs";

/// A job a migration lists in `up`: `glacier::jobs::create_table(s)`.
pub fn create_table(s: &mut Schema) {
    s.create_table(TABLE, |t| {
        t.string("name").not_null();
        t.string("queue").not_null();
        t.text("args").not_null();
        t.integer("attempts").not_null().default(0);
        t.integer("max_attempts").not_null().default(5);
        t.timestamp("run_at").not_null();
        t.timestamp("locked_at");
        t.timestamp("failed_at");
        t.text("last_error");
        t.timestamps();
    });
    s.add_index(TABLE, &["run_at"]);
}

/// How long before a job runs: a `chrono::TimeDelta` (`30.days()`) or a
/// `std::time::Duration`.
pub trait Delay {
    fn delay(self) -> chrono::TimeDelta;
}

impl Delay for chrono::TimeDelta {
    fn delay(self) -> chrono::TimeDelta {
        self
    }
}

impl Delay for Duration {
    fn delay(self) -> chrono::TimeDelta {
        chrono::TimeDelta::from_std(self).unwrap_or(chrono::TimeDelta::MAX)
    }
}

/// Work to do later. Its fields are its arguments, stored as JSON.
pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
    /// The name it's stored and registered under: keep it when renaming
    /// the type, or queued jobs won't find it.
    const NAME: &'static str;
    const QUEUE: &'static str = "default";
    /// Attempts before the job is left failed.
    const MAX_ATTEMPTS: i32 = 5;

    fn perform(self) -> impl Future<Output = Result<()>> + Send;

    /// Queues the job to run now, returning its id. Inside a transaction,
    /// it's only queued if the transaction commits.
    fn enqueue(&self) -> impl Future<Output = Result<i64>> + Send {
        self.enqueue_in(chrono::TimeDelta::zero())
    }

    /// Queues the job to run after `delay`: `enqueue_in(30.days())`, or a
    /// `std::time::Duration`.
    fn enqueue_in(&self, delay: impl Delay) -> impl Future<Output = Result<i64>> + Send {
        let args = serde_json::to_string(self);
        let delay = delay.delay();
        async move {
            let args = args.map_err(|e| Error::internal(format!("job arguments: {e}")))?;
            let now = crate::time::now();
            let run_at = now + delay;
            let mut sql = Sql::new();
            sql.push(&format!(
                "INSERT INTO {TABLE} (name, queue, args, attempts, max_attempts, run_at, inserted_at, updated_at) VALUES ("
            ));
            for (i, value) in [
                Value::Text(Self::NAME.to_owned()),
                Value::Text(Self::QUEUE.to_owned()),
                Value::Text(args),
                Value::Int(0),
                Value::Int(i64::from(Self::MAX_ATTEMPTS)),
                Value::Timestamp(run_at),
                Value::Timestamp(now),
                Value::Timestamp(now),
            ]
            .into_iter()
            .enumerate()
            {
                if i > 0 {
                    sql.push(", ");
                }
                sql.push_value(value);
            }
            sql.push(") RETURNING id");
            let rows = db::current()?.fetch_all(&sql).await?;
            let row = rows.first().ok_or_else(|| Error::internal("no job id"))?;
            row.get::<i64>("id")
                .or_else(|_| row.get::<i32>("id").map(i64::from))
        }
    }
}

type Perform = Arc<dyn Fn(&str) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> + Send + Sync>;

/// The jobs an app can run, by name, and how many workers run them.
#[derive(Clone)]
pub struct Jobs {
    handlers: Arc<HashMap<&'static str, Perform>>,
    workers: usize,
    poll: Duration,
}

impl Default for Jobs {
    fn default() -> Self {
        Self::new()
    }
}

impl Jobs {
    pub fn new() -> Self {
        Self {
            handlers: Arc::new(HashMap::new()),
            workers: 2,
            poll: Duration::from_secs(1),
        }
    }

    /// Lets the workers run `J`.
    #[must_use]
    pub fn register<J: Job>(mut self) -> Self {
        let perform: Perform = Arc::new(|args: &str| {
            let job = serde_json::from_str::<J>(args);
            Box::pin(async move {
                let job = job.map_err(|e| Error::internal(format!("job arguments: {e}")))?;
                job.perform().await
            })
        });
        Arc::make_mut(&mut self.handlers).insert(J::NAME, perform);
        self
    }

    /// How many jobs run at once (default 2).
    #[must_use]
    pub fn workers(mut self, workers: usize) -> Self {
        self.workers = workers.max(1);
        self
    }

    /// How long an idle worker waits before looking again (default 1s).
    #[must_use]
    pub fn poll_every(mut self, interval: Duration) -> Self {
        self.poll = interval;
        self
    }

    /// Starts the workers on `repo`; they run until the process ends.
    /// `App::serve` does this; call it yourself to run jobs in a process
    /// of their own.
    pub fn start(&self, repo: Repo) {
        for _ in 0..self.workers {
            let jobs = self.clone();
            let repo = repo.clone();
            tokio::spawn(async move {
                loop {
                    let ran = db::with(&repo, jobs.run_next()).await;
                    match ran {
                        Ok(true) => {}
                        Ok(false) => tokio::time::sleep(jobs.poll).await,
                        Err(err) => {
                            tracing::error!(target: "glacier::jobs", "job queue: {err}");
                            tokio::time::sleep(jobs.poll).await;
                        }
                    }
                }
            });
        }
    }

    /// Runs every job that's due, one after another, on the current
    /// connection; returns how many ran. For tests, and for one-off
    /// processing without workers.
    pub async fn perform_due(&self) -> Result<usize> {
        let mut count = 0;
        while self.run_next().await? {
            count += 1;
        }
        Ok(count)
    }

    /// Claims the next due job and runs it: `false` when none is due.
    async fn run_next(&self) -> Result<bool> {
        let conn = db::current()?;
        let now = crate::time::now();
        // A worker that died holding a job: let another take it.
        let stale = now - chrono::Duration::minutes(30);
        let skip_locked = match conn.dialect() {
            db::Dialect::Postgres => " FOR UPDATE SKIP LOCKED",
            db::Dialect::Sqlite => "",
        };
        let mut sql = Sql::new();
        sql.push(&format!("UPDATE {TABLE} SET locked_at = "));
        sql.push_value(Value::Timestamp(now));
        sql.push(", attempts = attempts + 1 WHERE id = (SELECT id FROM ");
        sql.push(TABLE);
        sql.push(" WHERE failed_at IS NULL AND run_at <= ");
        sql.push_value(Value::Timestamp(now));
        sql.push(" AND (locked_at IS NULL OR locked_at < ");
        sql.push_value(Value::Timestamp(stale));
        sql.push(&format!(
            ") ORDER BY run_at, id LIMIT 1{skip_locked}) RETURNING id, name, args, attempts, max_attempts"
        ));
        let rows = conn.fetch_all(&sql).await?;
        let Some(row) = rows.first() else {
            return Ok(false);
        };
        let id: i64 = row
            .get::<i64>("id")
            .or_else(|_| row.get::<i32>("id").map(i64::from))?;
        let name: String = row.get("name")?;
        let args: String = row.get("args")?;
        let attempts: i32 = row.get("attempts")?;
        let max_attempts: i32 = row.get("max_attempts")?;

        let outcome = match self.handlers.get(name.as_str()) {
            Some(perform) => {
                let span = tracing::info_span!(target: "glacier::jobs", "job", job.name = %name, job.id = id);
                let run = tracing::Instrument::instrument(perform(&args), span);
                // In a transaction (tests), a failing job's writes are undone
                // without spoiling the rest of it.
                if conn.in_transaction() {
                    db::savepoint(run).await
                } else {
                    run.await
                }
            }
            None => Err(Error::internal(format!("no job is registered as `{name}`"))),
        };
        let mut sql = Sql::new();
        match outcome {
            Ok(()) => {
                sql.push(&format!("DELETE FROM {TABLE} WHERE id = "));
                sql.push_value(Value::Int(id));
            }
            Err(err) => {
                let message = err.to_string();
                tracing::warn!(target: "glacier::jobs", "job {name} #{id} failed (attempt {attempts}): {message}");
                sql.push(&format!(
                    "UPDATE {TABLE} SET locked_at = NULL, last_error = "
                ));
                sql.push_value(Value::Text(message));
                sql.push(", updated_at = ");
                sql.push_value(Value::Timestamp(crate::time::now()));
                if attempts >= max_attempts {
                    sql.push(", failed_at = ");
                    sql.push_value(Value::Timestamp(crate::time::now()));
                } else {
                    sql.push(", run_at = ");
                    sql.push_value(Value::Timestamp(crate::time::now() + backoff(attempts)));
                }
                sql.push(" WHERE id = ");
                sql.push_value(Value::Int(id));
            }
        }
        conn.execute(&sql).await?;
        Ok(true)
    }
}

/// Active Job's polynomial backoff: attempts⁴ + 2 seconds (3s, 18s, 83s…).
fn backoff(attempts: i32) -> chrono::Duration {
    let n = i64::from(attempts.max(1));
    chrono::Duration::seconds(n.pow(4) + 2)
}

#[cfg(test)]
mod tests {
    #[test]
    fn backs_off_polynomially() {
        let seconds: Vec<i64> = (1..=4).map(|n| super::backoff(n).num_seconds()).collect();
        assert_eq!(seconds, [3, 18, 83, 258]);
    }
}