use apalis_sqlite::{SqlitePool, SqliteStorage};
use serde::Serialize;
use sqlx::Row;
pub use apalis::prelude::{BoxDynError, Monitor, TaskBuilder, TaskSink, WorkerBuilder, WorkerContext};
pub mod commands;
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FailedJob {
pub id: String,
pub connection: &'static str,
pub queue: String,
pub payload: Vec<u8>,
pub exception: String,
pub failed_at: i64,
}
pub async fn sqlite<J>(database_url: &str) -> Result<SqliteStorage<J>, Error> {
let pool = SqlitePool::connect(database_url).await?;
ensure_schema(&pool).await?;
Ok(SqliteStorage::new(&pool))
}
pub async fn failed(database_url: &str, queue: Option<&str>) -> Result<Vec<FailedJob>, Error> {
let pool = SqlitePool::connect(database_url).await?;
ensure_schema(&pool).await?;
let rows = sqlx::query(
"SELECT id, job_type, job, last_result, done_at \
FROM Jobs \
WHERE status = 'Failed' AND attempts >= max_attempts \
AND (?1 IS NULL OR job_type = ?1) \
ORDER BY done_at DESC, id DESC",
)
.bind(queue)
.fetch_all(&pool)
.await?;
rows.into_iter()
.map(|row| {
let exception = row.try_get::<Option<String>, _>("last_result")?.unwrap_or_default();
let exception = serde_json::from_str::<String>(&exception).unwrap_or(exception);
Ok(FailedJob {
id: row.try_get("id")?,
connection: "sqlite",
queue: row.try_get("job_type")?,
payload: row.try_get("job")?,
exception,
failed_at: row.try_get::<Option<i64>, _>("done_at")?.unwrap_or_default(),
})
})
.collect()
}
pub async fn retry(database_url: &str, id: &str) -> Result<bool, Error> {
let pool = SqlitePool::connect(database_url).await?;
ensure_schema(&pool).await?;
let result = sqlx::query(
"UPDATE Jobs SET status = 'Pending', attempts = 0, run_at = strftime('%s', 'now'), \
last_result = NULL, done_at = NULL, lock_at = NULL, lock_by = NULL \
WHERE id = ?1 AND status = 'Failed' AND attempts >= max_attempts",
)
.bind(id)
.execute(&pool)
.await?;
Ok(result.rows_affected() > 0)
}
pub async fn forget(database_url: &str, id: &str) -> Result<bool, Error> {
let pool = SqlitePool::connect(database_url).await?;
ensure_schema(&pool).await?;
let result = sqlx::query("DELETE FROM Jobs WHERE id = ?1 AND status = 'Failed' AND attempts >= max_attempts")
.bind(id)
.execute(&pool)
.await?;
Ok(result.rows_affected() > 0)
}
pub async fn flush(database_url: &str, hours: Option<u64>, queue: Option<&str>) -> Result<u64, Error> {
let pool = SqlitePool::connect(database_url).await?;
ensure_schema(&pool).await?;
let retained_seconds = hours
.map(|hours| hours.saturating_mul(60).saturating_mul(60))
.map(i64::try_from)
.transpose()
.map_err(|_| Error::InvalidRetention)?;
let result = sqlx::query(
"DELETE FROM Jobs \
WHERE status = 'Failed' AND attempts >= max_attempts \
AND (?1 IS NULL OR done_at <= strftime('%s', 'now') - ?1) \
AND (?2 IS NULL OR job_type = ?2)",
)
.bind(retained_seconds)
.bind(queue)
.execute(&pool)
.await?;
Ok(result.rows_affected())
}
async fn ensure_schema(pool: &SqlitePool) -> Result<(), Error> {
let tables = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM sqlite_master \
WHERE type = 'table' AND lower(name) IN ('jobs', 'workers')",
)
.fetch_one(pool)
.await?;
if tables != 2 {
return Err(Error::PendingMigrations("queue migrations are pending; run `cargo aurelin migrate`"));
}
Ok(())
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("connect to the queue database: {0}")]
Connect(#[from] apalis_sqlite::SqlxError),
#[error("{0}")]
PendingMigrations(&'static str),
#[error("failed-job retention is too large")]
InvalidRetention,
}