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";
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"]);
}
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)
}
}
pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
const NAME: &'static str;
const QUEUE: &'static str = "default";
const MAX_ATTEMPTS: i32 = 5;
fn perform(self) -> impl Future<Output = Result<()>> + Send;
fn enqueue(&self) -> impl Future<Output = Result<i64>> + Send {
self.enqueue_in(chrono::TimeDelta::zero())
}
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>;
#[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),
}
}
#[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
}
#[must_use]
pub fn workers(mut self, workers: usize) -> Self {
self.workers = workers.max(1);
self
}
#[must_use]
pub fn poll_every(mut self, interval: Duration) -> Self {
self.poll = interval;
self
}
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;
}
}
}
});
}
}
pub async fn perform_due(&self) -> Result<usize> {
let mut count = 0;
while self.run_next().await? {
count += 1;
}
Ok(count)
}
async fn run_next(&self) -> Result<bool> {
let conn = db::current()?;
let now = crate::time::now();
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);
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)
}
}
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]);
}
}