Skip to main content

aurelin_framework/
queue.rs

1//! Durable background jobs backed by SQLite and Apalis.
2
3use apalis_sqlite::{SqlitePool, SqliteStorage};
4use serde::Serialize;
5use sqlx::Row;
6
7pub use apalis::prelude::{BoxDynError, Monitor, TaskBuilder, TaskSink, WorkerBuilder, WorkerContext};
8
9pub mod commands;
10
11/// A job that exhausted all of its configured attempts.
12#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
13pub struct FailedJob {
14    /// Durable task identifier used by retry and forget operations.
15    pub id: String,
16    /// Queue connection that stored the task.
17    pub connection: &'static str,
18    /// Apalis queue name associated with the serialized job type.
19    pub queue: String,
20    /// Serialized application job payload.
21    pub payload: Vec<u8>,
22    /// Last handler error recorded by the worker.
23    pub exception: String,
24    /// Unix timestamp when the final attempt completed.
25    pub failed_at: i64,
26}
27
28/// Connect to an explicitly migrated SQLite queue.
29pub async fn sqlite<J>(database_url: &str) -> Result<SqliteStorage<J>, Error> {
30    let pool = SqlitePool::connect(database_url).await?;
31    ensure_schema(&pool).await?;
32    Ok(SqliteStorage::new(&pool))
33}
34
35/// List jobs that exhausted all configured attempts, newest first.
36pub async fn failed(database_url: &str, queue: Option<&str>) -> Result<Vec<FailedJob>, Error> {
37    let pool = SqlitePool::connect(database_url).await?;
38    ensure_schema(&pool).await?;
39    let rows = sqlx::query(
40        "SELECT id, job_type, job, last_result, done_at \
41         FROM Jobs \
42         WHERE status = 'Failed' AND attempts >= max_attempts \
43           AND (?1 IS NULL OR job_type = ?1) \
44         ORDER BY done_at DESC, id DESC",
45    )
46    .bind(queue)
47    .fetch_all(&pool)
48    .await?;
49
50    rows.into_iter()
51        .map(|row| {
52            let exception = row.try_get::<Option<String>, _>("last_result")?.unwrap_or_default();
53            let exception = serde_json::from_str::<String>(&exception).unwrap_or(exception);
54            Ok(FailedJob {
55                id: row.try_get("id")?,
56                connection: "sqlite",
57                queue: row.try_get("job_type")?,
58                payload: row.try_get("job")?,
59                exception,
60                failed_at: row.try_get::<Option<i64>, _>("done_at")?.unwrap_or_default(),
61            })
62        })
63        .collect()
64}
65
66/// Make an exhausted job available to a worker again with a fresh attempt count.
67pub async fn retry(database_url: &str, id: &str) -> Result<bool, Error> {
68    let pool = SqlitePool::connect(database_url).await?;
69    ensure_schema(&pool).await?;
70    let result = sqlx::query(
71        "UPDATE Jobs SET status = 'Pending', attempts = 0, run_at = strftime('%s', 'now'), \
72         last_result = NULL, done_at = NULL, lock_at = NULL, lock_by = NULL \
73         WHERE id = ?1 AND status = 'Failed' AND attempts >= max_attempts",
74    )
75    .bind(id)
76    .execute(&pool)
77    .await?;
78    Ok(result.rows_affected() > 0)
79}
80
81/// Delete an exhausted job permanently.
82pub async fn forget(database_url: &str, id: &str) -> Result<bool, Error> {
83    let pool = SqlitePool::connect(database_url).await?;
84    ensure_schema(&pool).await?;
85    let result = sqlx::query("DELETE FROM Jobs WHERE id = ?1 AND status = 'Failed' AND attempts >= max_attempts")
86        .bind(id)
87        .execute(&pool)
88        .await?;
89    Ok(result.rows_affected() > 0)
90}
91
92/// Delete exhausted jobs, optionally retaining recent failures or filtering by queue.
93pub async fn flush(database_url: &str, hours: Option<u64>, queue: Option<&str>) -> Result<u64, Error> {
94    let pool = SqlitePool::connect(database_url).await?;
95    ensure_schema(&pool).await?;
96    let retained_seconds = hours
97        .map(|hours| hours.saturating_mul(60).saturating_mul(60))
98        .map(i64::try_from)
99        .transpose()
100        .map_err(|_| Error::InvalidRetention)?;
101    let result = sqlx::query(
102        "DELETE FROM Jobs \
103         WHERE status = 'Failed' AND attempts >= max_attempts \
104           AND (?1 IS NULL OR done_at <= strftime('%s', 'now') - ?1) \
105           AND (?2 IS NULL OR job_type = ?2)",
106    )
107    .bind(retained_seconds)
108    .bind(queue)
109    .execute(&pool)
110    .await?;
111    Ok(result.rows_affected())
112}
113
114async fn ensure_schema(pool: &SqlitePool) -> Result<(), Error> {
115    let tables = sqlx::query_scalar::<_, i64>(
116        "SELECT COUNT(*) FROM sqlite_master \
117         WHERE type = 'table' AND lower(name) IN ('jobs', 'workers')",
118    )
119    .fetch_one(pool)
120    .await?;
121    if tables != 2 {
122        return Err(Error::PendingMigrations("queue migrations are pending; run `cargo aurelin migrate`"));
123    }
124    Ok(())
125}
126
127/// Failures encountered while opening or preparing a SQLite queue.
128#[derive(Debug, thiserror::Error)]
129pub enum Error {
130    /// The SQLite connection could not be opened.
131    #[error("connect to the queue database: {0}")]
132    Connect(#[from] apalis_sqlite::SqlxError),
133    /// The generated application's queue migration has not been applied.
134    #[error("{0}")]
135    PendingMigrations(&'static str),
136    /// The requested failed-job retention cannot be represented by SQLite.
137    #[error("failed-job retention is too large")]
138    InvalidRetention,
139}