pub mod cron;
mod prune;
use std::collections::HashMap;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use chrono::TimeDelta;
use futures_util::FutureExt;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::sync::Notify;
pub use self::cron::Cron;
pub use self::prune::{Prunable, prune};
use crate::db::migration::Schema;
use crate::db::{self, Repo, Sql, Timestamp, Value};
use crate::error::{Error, Result};
const TABLE: &str = "glacier_jobs";
const SCHEDULES: &str = "glacier_job_schedules";
const OLD_CHANNEL: &str = "glacier_jobs";
const HEARTBEAT: Duration = Duration::from_secs(15);
const STALE_AFTER: TimeDelta = TimeDelta::seconds(60);
const SCHEDULE_GRACE: TimeDelta = TimeDelta::minutes(5);
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 fn upgrade_table(s: &mut Schema) {
s.alter_table(TABLE, |t| {
t.integer("priority").not_null().default(0);
t.text("unique_key");
t.timestamp("expires_at");
});
s.drop_index(TABLE, &["run_at"]);
s.add_index(TABLE, &["queue", "priority", "run_at"]);
s.execute(&format!(
"CREATE UNIQUE INDEX index_{TABLE}_on_unique_key ON {TABLE} (unique_key) WHERE failed_at IS NULL"
));
s.create_table(SCHEDULES, |t| {
t.string("name").not_null().unique();
t.timestamp("last_run_at").not_null();
});
}
pub trait Delay {
fn delay(self) -> TimeDelta;
}
impl Delay for TimeDelta {
fn delay(self) -> TimeDelta {
self
}
}
impl Delay for Duration {
fn delay(self) -> TimeDelta {
TimeDelta::from_std(self).unwrap_or(TimeDelta::MAX)
}
}
pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
const NAME: &'static str;
const QUEUE: &'static str = "default";
const MAX_ATTEMPTS: i32 = 5;
const PRIORITY: i32 = 0;
fn perform(self) -> impl Future<Output = Result<()>> + Send;
fn unique_key(&self) -> Option<String> {
None
}
fn expires_in(&self) -> Option<TimeDelta> {
None
}
fn schedule(jobs: Jobs) -> Jobs
where
Self: Sized,
{
jobs
}
fn enqueue(&self) -> impl Future<Output = Result<i64>> + Send {
self.enqueue_at(crate::time::now())
}
fn enqueue_in(&self, delay: impl Delay) -> impl Future<Output = Result<i64>> + Send {
self.enqueue_at(crate::time::now() + delay.delay())
}
fn enqueue_at(&self, at: Timestamp) -> impl Future<Output = Result<i64>> + Send {
let reference = crate::access::current().and_then(|access| access.reference());
queue_one(Queued::of_for(self, at, reference))
}
fn enqueue_for(
&self,
access: &dyn crate::access::Access,
) -> impl Future<Output = Result<i64>> + Send {
queue_one(Queued::of_for(self, crate::time::now(), access.reference()))
}
fn enqueue_unscoped(&self) -> impl Future<Output = Result<i64>> + Send {
queue_one(Queued::of_for(self, crate::time::now(), None))
}
fn enqueue_all(jobs: &[Self]) -> impl Future<Output = Result<usize>> + Send {
let now = crate::time::now();
let rows: Result<Vec<Queued>> = jobs.iter().map(|job| Queued::of(job, now)).collect();
async move {
let rows = rows?;
if rows.is_empty() {
return Ok(0);
}
Ok(insert(rows).await?.len())
}
}
}
async fn queue_one(row: Result<Queued>) -> Result<i64> {
let row = row?;
let key = row.unique_key.clone();
match insert(vec![row]).await?.first() {
Some(id) => Ok(*id),
None => existing(key.as_deref().unwrap_or_default()).await,
}
}
const ACCESS_KEY: &str = "__access";
const ARGS_KEY: &str = "__args";
struct Queued {
name: &'static str,
queue: &'static str,
args: String,
priority: i32,
max_attempts: i32,
run_at: Timestamp,
unique_key: Option<String>,
expires_at: Option<Timestamp>,
}
impl Queued {
fn of<J: Job>(job: &J, run_at: Timestamp) -> Result<Self> {
let reference = crate::access::current().and_then(|access| access.reference());
Self::of_for(job, run_at, reference)
}
fn of_for<J: Job>(
job: &J,
run_at: Timestamp,
reference: Option<serde_json::Value>,
) -> Result<Self> {
let mut args = serde_json::to_value(job)
.map_err(|e| Error::internal(format!("job arguments: {e}")))?;
if let Some(reference) = reference {
match args.as_object_mut() {
Some(fields) => {
fields.insert(ACCESS_KEY.to_owned(), reference);
}
None => {
args = serde_json::json!({ ARGS_KEY: args, ACCESS_KEY: reference });
}
}
}
let args = args.to_string();
Ok(Self {
name: J::NAME,
queue: J::QUEUE,
args,
priority: J::PRIORITY,
max_attempts: J::MAX_ATTEMPTS,
run_at,
unique_key: job.unique_key().map(|key| format!("{}:{key}", J::NAME)),
expires_at: job.expires_in().map(|within| run_at + within),
})
}
}
async fn insert(rows: Vec<Queued>) -> Result<Vec<i64>> {
let conn = db::current()?;
let postgres = conn.dialect() == db::Dialect::Postgres;
let now = crate::time::now();
let unique = rows.iter().any(|row| row.unique_key.is_some());
let mut sql = Sql::new();
if postgres {
sql.push("WITH queued AS (");
}
sql.push(&format!(
"INSERT INTO {TABLE} (name, queue, args, priority, attempts, max_attempts, run_at, \
unique_key, expires_at, inserted_at, updated_at) VALUES "
));
for (i, row) in rows.into_iter().enumerate() {
if i > 0 {
sql.push(", ");
}
sql.push("(");
let values = [
Value::Text(row.name.to_owned()),
Value::Text(row.queue.to_owned()),
Value::Text(row.args),
Value::Int(i64::from(row.priority)),
Value::Int(0),
Value::Int(i64::from(row.max_attempts)),
Value::Timestamp(row.run_at),
row.unique_key.map_or(Value::Null, Value::Text),
row.expires_at.map_or(Value::Null, Value::Timestamp),
Value::Timestamp(now),
Value::Timestamp(now),
];
for (j, value) in values.into_iter().enumerate() {
if j > 0 {
sql.push(", ");
}
sql.push_value(value);
}
sql.push(")");
}
if unique {
sql.push(" ON CONFLICT (unique_key) WHERE failed_at IS NULL DO NOTHING");
}
sql.push(" RETURNING id, queue");
if postgres {
sql.push(&format!(
") SELECT id, {}::text AS notified FROM queued",
crate::notify::pg_notify_sql("jobs", "queued", "id")
));
}
let rows = conn.fetch_all(&sql).await.map_err(upgrade_hint)?;
rows.iter().map(id_of).collect()
}
fn upgrade_hint(err: sqlx::Error) -> Error {
let message = err.to_string();
let old_table = ["priority", "unique_key", "expires_at", SCHEDULES]
.iter()
.any(|name| message.contains(name));
if old_table {
Error::internal(format!(
"{message}: the jobs table is from before Glacier 0.3; add a migration \
whose `up` calls `glacier::jobs::upgrade_table(s)`"
))
} else {
err.into()
}
}
async fn existing(key: &str) -> Result<i64> {
let mut sql = Sql::new();
sql.push(&format!(
"SELECT id FROM {TABLE} WHERE failed_at IS NULL AND unique_key = "
));
sql.push_value(Value::Text(key.to_owned()));
let rows = db::current()?.fetch_all(&sql).await?;
rows.first().map_or(Ok(0), id_of)
}
fn id_of(row: &db::Row) -> Result<i64> {
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)]
struct Recurring {
name: String,
when: When,
job: &'static str,
queue: &'static str,
args: String,
priority: i32,
max_attempts: i32,
}
#[derive(Clone)]
enum When {
Cron(Cron),
Every(TimeDelta),
}
impl When {
fn latest_due(&self, now: Timestamp) -> Option<Timestamp> {
match self {
When::Cron(cron) => cron.latest_at_or_before(now, SCHEDULE_GRACE),
When::Every(interval) => {
let step = interval.num_milliseconds().max(1);
let at = now.timestamp_millis().div_euclid(step) * step;
let due = chrono::DateTime::from_timestamp_millis(at)?;
(now - due <= SCHEDULE_GRACE).then_some(due)
}
}
}
}
pub trait IntoCron {
fn into_cron(self) -> Cron;
}
impl IntoCron for Cron {
fn into_cron(self) -> Cron {
self
}
}
impl IntoCron for &str {
fn into_cron(self) -> Cron {
Cron::parse(self).unwrap_or_else(|err| panic!("cron schedule: {}", err.message()))
}
}
#[derive(Clone)]
enum Queues {
Only(String),
Except(Vec<String>),
}
#[derive(Clone)]
pub struct Jobs {
handlers: Arc<HashMap<&'static str, Perform>>,
workers: usize,
queues: Vec<(String, usize)>,
poll: Option<Duration>,
recurring: Vec<Recurring>,
keep_failed: Option<TimeDelta>,
pruners: Vec<(String, Pruner)>,
}
type Pruner = Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<u64>> + Send>> + Send + Sync>;
impl Default for Jobs {
fn default() -> Self {
Self::new()
}
}
impl Jobs {
pub fn new() -> Self {
Self {
handlers: Arc::new(HashMap::new()),
workers: 2,
queues: Vec::new(),
poll: None,
recurring: Vec::new(),
keep_failed: None,
pruners: Vec::new(),
}
.register::<crate::mail::DeliverMail>()
.register::<crate::webhooks::HandleWebhook>()
}
#[must_use]
pub fn register<J: Job>(mut self) -> Self {
let perform: Perform = Arc::new(|args: &str| {
let mut value = serde_json::from_str::<serde_json::Value>(args).unwrap_or_default();
let reference = value.get_mut(ACCESS_KEY).map(serde_json::Value::take);
let job = match value.get_mut(ARGS_KEY) {
Some(inner) => serde_json::from_value::<J>(inner.take()),
None => serde_json::from_str::<J>(args),
};
Box::pin(async move {
let job = job.map_err(|e| Error::internal(format!("job arguments: {e}")))?;
match reference {
Some(reference) => {
let access = crate::access::rebuild(reference)
.await
.map_err(|e| Error::internal(format!("rebuilding its access: {e}")))?;
tracing::Span::current().record("glacier.access", access.describe());
crate::access::with_shared(access, job.perform()).await
}
None => job.perform().await,
}
})
});
Arc::make_mut(&mut self.handlers).insert(J::NAME, perform);
J::schedule(self)
}
#[must_use]
pub fn workers(mut self, workers: usize) -> Self {
self.workers = workers.max(1);
self
}
#[must_use]
pub fn queue(mut self, queue: &str, workers: usize) -> Self {
self.queues.retain(|(name, _)| name != queue);
self.queues.push((queue.to_owned(), workers.max(1)));
self
}
#[must_use]
pub fn poll_every(mut self, interval: Duration) -> Self {
self.poll = Some(interval);
self
}
#[must_use]
pub fn cron<J: Job>(self, name: &str, schedule: impl IntoCron, job: J) -> Self {
self.recurring(name, When::Cron(schedule.into_cron()), &job)
}
#[must_use]
pub fn every<J: Job>(self, name: &str, interval: impl Delay, job: J) -> Self {
self.recurring(name, When::Every(interval.delay()), &job)
}
fn recurring<J: Job>(mut self, name: &str, when: When, job: &J) -> Self {
let args = serde_json::to_string(job)
.unwrap_or_else(|e| panic!("recurring job `{name}`: arguments: {e}"));
let register = !self.handlers.contains_key(J::NAME);
self.recurring.retain(|r| r.name != name);
self.recurring.push(Recurring {
name: name.to_owned(),
when,
job: J::NAME,
queue: J::QUEUE,
args,
priority: J::PRIORITY,
max_attempts: J::MAX_ATTEMPTS,
});
if register { self.register::<J>() } else { self }
}
#[must_use]
pub fn keep_failed_for(mut self, age: impl Delay) -> Self {
self.keep_failed = Some(age.delay());
self
}
#[must_use]
pub fn prune_records<M: Prunable>(self) -> Self {
self.prune_with(M::TABLE, || prune::<M>())
}
#[must_use]
pub fn prune_with<F, Fut>(mut self, name: &str, prune: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<u64>> + Send + 'static,
{
let pruner: Pruner = Arc::new(move || Box::pin(prune()));
self.pruners.retain(|(existing, _)| existing != name);
self.pruners.push((name.to_owned(), pruner));
self
}
pub fn start(&self, repo: Repo) {
let wake = Arc::new(Notify::new());
let listening = match repo.postgres_pool() {
Some(pool) => {
listen(pool.clone(), wake.clone());
true
}
None => false,
};
let poll = self.poll.unwrap_or(if listening {
Duration::from_secs(10)
} else {
Duration::from_secs(1)
});
let own: Vec<String> = self.queues.iter().map(|(name, _)| name.clone()).collect();
let mut groups = vec![(Queues::Except(own), self.workers)];
groups.extend(
self.queues
.iter()
.map(|(name, n)| (Queues::Only(name.clone()), *n)),
);
for (queues, workers) in groups {
for _ in 0..workers {
let jobs = self.clone();
let repo = repo.clone();
let wake = wake.clone();
let queues = queues.clone();
tokio::spawn(async move {
loop {
let woken = wake.notified();
tokio::pin!(woken);
woken.as_mut().enable();
match db::with(&repo, jobs.run_next(&queues, Some(&repo))).await {
Ok(true) => {}
Ok(false) => {
tokio::select! {
() = woken => {}
() = tokio::time::sleep(poll) => {}
}
}
Err(err) => {
tracing::error!(target: "glacier::jobs", "job queue: {err}");
tokio::time::sleep(poll).await;
}
}
}
});
}
}
if !self.recurring.is_empty() || self.keep_failed.is_some() || !self.pruners.is_empty() {
let jobs = self.clone();
tokio::spawn(async move {
let mut pruned_at: Option<std::time::Instant> = None;
loop {
if let Err(err) = db::with(&repo, jobs.enqueue_recurring()).await {
tracing::error!(target: "glacier::jobs", "recurring jobs: {err}");
}
if pruned_at.is_none_or(|at| at.elapsed() > Duration::from_secs(3600)) {
if let Err(err) = db::with(&repo, jobs.prune()).await {
tracing::error!(target: "glacier::jobs", "pruning jobs: {err}");
}
pruned_at = Some(std::time::Instant::now());
}
tokio::time::sleep(jobs.until_next_recurring()).await;
}
});
}
}
pub async fn perform_due(&self) -> Result<usize> {
let mut count = 0;
while self.run_next(&Queues::Except(Vec::new()), None).await? {
count += 1;
}
Ok(count)
}
pub async fn enqueue_recurring(&self) -> Result<usize> {
let now = crate::time::now();
let mut queued = 0;
for recurring in &self.recurring {
let Some(due) = recurring.when.latest_due(now) else {
continue;
};
let claimed = db::transaction(async {
let mut sql = Sql::new();
sql.push(&format!(
"INSERT INTO {SCHEDULES} (name, last_run_at) VALUES ("
));
sql.push_value(Value::Text(recurring.name.clone()));
sql.push(", ");
sql.push_value(Value::Timestamp(due));
sql.push(&format!(
") ON CONFLICT (name) DO UPDATE SET last_run_at = excluded.last_run_at \
WHERE {SCHEDULES}.last_run_at < excluded.last_run_at RETURNING name"
));
if db::current()?
.fetch_all(&sql)
.await
.map_err(upgrade_hint)?
.is_empty()
{
return Ok(false);
}
insert(vec![Queued {
name: recurring.job,
queue: recurring.queue,
args: recurring.args.clone(),
priority: recurring.priority,
max_attempts: recurring.max_attempts,
run_at: now,
unique_key: None,
expires_at: None,
}])
.await?;
Ok(true)
})
.await?;
queued += usize::from(claimed);
}
Ok(queued)
}
fn until_next_recurring(&self) -> Duration {
let now = chrono::Utc::now();
self.recurring
.iter()
.filter_map(|r| match &r.when {
When::Cron(cron) => cron.next_after(now),
When::Every(interval) => {
let step = interval.num_milliseconds().max(1);
let next = (now.timestamp_millis().div_euclid(step) + 1) * step;
chrono::DateTime::from_timestamp_millis(next)
}
})
.map(|next| (next - now).to_std().unwrap_or_default())
.min()
.unwrap_or(Duration::MAX)
.min(Duration::from_secs(60))
+ Duration::from_millis(50)
}
pub async fn prune(&self) -> Result<u64> {
let mut deleted = 0;
if let Some(age) = self.keep_failed {
let mut sql = Sql::new();
sql.push(&format!("DELETE FROM {TABLE} WHERE failed_at < "));
sql.push_value(Value::Timestamp(crate::time::now() - age));
deleted += db::current()?.execute(&sql).await?;
}
for (name, prune) in &self.pruners {
let pruned = crate::access::unscoped("pruning", prune()).await?;
if pruned > 0 {
tracing::info!(target: "glacier::jobs", "pruned {pruned} from {name}");
}
deleted += pruned;
}
Ok(deleted)
}
pub async fn failed() -> Result<Vec<FailedJob>> {
let rows = db::sql(&format!(
"SELECT id, name, queue, args, attempts, last_error, failed_at FROM {TABLE} \
WHERE failed_at IS NOT NULL ORDER BY failed_at DESC, id DESC"
))
.fetch_all()
.await?;
rows.iter()
.map(|row| {
Ok(FailedJob {
id: id_of(row)?,
name: row.get("name")?,
queue: row.get("queue")?,
args: row.get("args")?,
attempts: row.get("attempts")?,
last_error: row.get::<Option<String>>("last_error")?.unwrap_or_default(),
failed_at: row.get("failed_at")?,
})
})
.collect()
}
pub async fn retry(id: i64) -> Result<bool> {
let now = crate::time::now();
let mut sql = Sql::new();
sql.push(&format!(
"UPDATE {TABLE} SET failed_at = NULL, locked_at = NULL, expires_at = NULL, \
attempts = 0, run_at = "
));
sql.push_value(Value::Timestamp(now));
sql.push(", updated_at = ");
sql.push_value(Value::Timestamp(now));
sql.push(" WHERE failed_at IS NOT NULL AND id = ");
sql.push_value(Value::Int(id));
sql.push(&format!(
" AND (unique_key IS NULL OR NOT EXISTS (SELECT 1 FROM {TABLE} waiting \
WHERE waiting.unique_key = {TABLE}.unique_key AND waiting.failed_at IS NULL))"
));
Ok(db::current()?.execute(&sql).await? > 0)
}
async fn run_next(&self, queues: &Queues, heartbeat: Option<&Repo>) -> Result<bool> {
let conn = db::current()?;
let now = crate::time::now();
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(now - STALE_AFTER));
sql.push(")");
match queues {
Queues::Only(queue) => {
sql.push(" AND queue = ");
sql.push_value(Value::Text(queue.clone()));
}
Queues::Except(others) if !others.is_empty() => {
sql.push(" AND queue NOT IN (");
for (i, queue) in others.iter().enumerate() {
if i > 0 {
sql.push(", ");
}
sql.push_value(Value::Text(queue.clone()));
}
sql.push(")");
}
Queues::Except(_) => {}
}
sql.push(&format!(
" ORDER BY priority, run_at, id LIMIT 1{skip_locked}) \
RETURNING id, name, args, attempts, max_attempts, expires_at"
));
let rows = conn.fetch_all(&sql).await.map_err(upgrade_hint)?;
let Some(row) = rows.first() else {
return Ok(false);
};
let id = id_of(row)?;
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 expires_at: Option<Timestamp> = row.get("expires_at")?;
if expires_at.is_some_and(|at| at < now) {
give_up(id, "expired before it could run").await?;
return Ok(true);
}
if attempts > max_attempts {
give_up(id, "its worker stopped while running it, too many times").await?;
return Ok(true);
}
let outcome = match self.handlers.get(name.as_str()) {
Some(perform) => {
let span = tracing::info_span!(
target: "glacier::jobs",
"glacier.job",
otel.name = %name,
otel.kind = "consumer",
job.name = %name,
job.id = id,
job.attempt = attempts,
glacier.access = tracing::field::Empty,
);
let run = async {
match AssertUnwindSafe(perform(&args)).catch_unwind().await {
Ok(outcome) => outcome,
Err(panic) => Err(Error::internal(format!(
"panicked: {}",
panic_text(&*panic)
))),
}
};
let run = tracing::Instrument::instrument(run, span);
let _alive = heartbeat.map(|repo| AbortOnDrop(keep_alive(repo.clone(), id)));
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}");
let now = crate::time::now();
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(now));
if attempts >= max_attempts {
sql.push(", failed_at = ");
sql.push_value(Value::Timestamp(now));
} else {
sql.push(", run_at = ");
sql.push_value(Value::Timestamp(now + backoff(attempts)));
}
sql.push(" WHERE id = ");
sql.push_value(Value::Int(id));
}
}
conn.execute(&sql).await?;
Ok(true)
}
}
#[derive(Debug, Clone)]
pub struct FailedJob {
pub id: i64,
pub name: String,
pub queue: String,
pub args: String,
pub attempts: i32,
pub last_error: String,
pub failed_at: Timestamp,
}
async fn give_up(id: i64, why: &str) -> Result<()> {
let now = crate::time::now();
let mut sql = Sql::new();
sql.push(&format!(
"UPDATE {TABLE} SET locked_at = NULL, failed_at = "
));
sql.push_value(Value::Timestamp(now));
sql.push(", updated_at = ");
sql.push_value(Value::Timestamp(now));
sql.push(", last_error = ");
sql.push_value(Value::Text(why.to_owned()));
sql.push(" WHERE id = ");
sql.push_value(Value::Int(id));
db::current()?.execute(&sql).await?;
tracing::warn!(target: "glacier::jobs", "job #{id} {why}");
Ok(())
}
struct AbortOnDrop(tokio::task::JoinHandle<()>);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}
fn panic_text(panic: &(dyn std::any::Any + Send)) -> String {
panic
.downcast_ref::<&str>()
.map(|s| (*s).to_owned())
.or_else(|| panic.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "a panic".to_owned())
}
fn keep_alive(repo: Repo, id: i64) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
tokio::time::sleep(HEARTBEAT).await;
let mut sql = Sql::new();
sql.push(&format!("UPDATE {TABLE} SET locked_at = "));
sql.push_value(Value::Timestamp(chrono::Utc::now()));
sql.push(" WHERE id = ");
sql.push_value(Value::Int(id));
let beat: Result<u64> =
db::with(&repo, async { Ok(db::current()?.execute(&sql).await?) }).await;
if let Err(err) = beat {
tracing::warn!(target: "glacier::jobs", "job #{id} heartbeat: {err}");
}
}
})
}
fn listen(pool: sqlx::PgPool, wake: Arc<Notify>) {
tokio::spawn(async move {
loop {
let mut listener = match sqlx::postgres::PgListener::connect_with(&pool).await {
Ok(listener) => listener,
Err(err) => {
tracing::warn!(target: "glacier::jobs", "listening for jobs: {err}");
tokio::time::sleep(Duration::from_secs(5)).await;
continue;
}
};
if let Err(err) = listener
.listen_all([crate::notify::CHANNEL, OLD_CHANNEL])
.await
{
tracing::warn!(target: "glacier::jobs", "listening for jobs: {err}");
tokio::time::sleep(Duration::from_secs(5)).await;
continue;
}
while let Ok(notification) = listener.recv().await {
let for_jobs = notification.channel() == OLD_CHANNEL
|| crate::notify::Envelope::parse(notification.payload())
.is_some_and(|envelope| envelope.topic == "jobs");
if for_jobs {
wake.notify_waiters();
}
}
wake.notify_waiters();
}
});
}
fn backoff(attempts: i32) -> TimeDelta {
let n = i64::from(attempts.max(1));
TimeDelta::seconds(n.pow(4) + 2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backs_off_polynomially() {
let seconds: Vec<i64> = (1..=4).map(|n| backoff(n).num_seconds()).collect();
assert_eq!(seconds, [3, 18, 83, 258]);
}
#[test]
fn intervals_fall_on_whole_multiples() {
let at = |s: &str| chrono::DateTime::parse_from_rfc3339(s).unwrap().to_utc();
let hourly = When::Every(TimeDelta::hours(1));
assert_eq!(
hourly.latest_due(at("2026-10-04T10:03:00Z")),
Some(at("2026-10-04T10:00:00Z"))
);
assert_eq!(hourly.latest_due(at("2026-10-04T10:20:00Z")), None);
let quarter = When::Every(TimeDelta::minutes(15));
assert_eq!(
quarter.latest_due(at("2026-10-04T10:20:00Z")),
Some(at("2026-10-04T10:15:00Z"))
);
}
}