use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard, PoisonError};
use rusqlite::{Connection, OptionalExtension, params};
use super::call::{LONGEST_SPAN, in_years};
use super::dedupe::Dedupe;
use super::policy::Policy;
use super::repeat::Repeat;
use super::rows::{self, PARKED_BY, execute};
use super::state::QueueState;
use crate::sqlite::{query_cached, sql_error};
use crate::text::fnv1a;
use crate::{Error, ErrorKind, Result};
pub(crate) const CLAIM_BATCH: usize = 1000;
const PARK_AT_MOST: usize = 1000;
const MAX_ERROR: usize = 4096;
const CLAIM_JOBS: &str = "select next, id, key, at, attempt, value, spill, grp, expires
from _tinystore_jobs j
where queue = ?1 and next <= ?2
and not exists (select 1 from _tinystore_jobs_leases l where l.id = j.id and l.until > ?2)
order by next, id limit cast(?3 as integer)";
const TAKE_LEASE: &str =
"insert into _tinystore_jobs_leases (id, queue, next, attempt, until) values (?1, ?2, ?3, ?4, ?5)
on conflict (id) do update set next = excluded.next, until = excluded.until,
attempt = max(_tinystore_jobs_leases.attempt, excluded.attempt - 1) + 1";
const LEASE_ATTEMPT: &str = "select attempt from _tinystore_jobs_leases where id = ?1";
const LIVE_LEASES: &str = "select count(*) from _tinystore_jobs_leases where queue = ?1 and until > ?2";
const RUNNING_IN_GROUPS: &str = "select j.grp, count(*) from _tinystore_jobs_leases l
join _tinystore_jobs j on j.queue = l.queue and j.next = l.next and j.id = l.id
where l.queue = ?1 and l.until > ?2 and j.grp is not null
group by j.grp";
const NEXT_DUE: &str = "select next from _tinystore_jobs j where queue = ?1 and next < 576460752303423488
and not exists (select 1 from _tinystore_jobs_leases l where l.id = j.id and l.until > ?2)
order by next, id limit 1";
const EARLIEST_LEASE: &str = "select min(until) from _tinystore_jobs_leases where queue = ?1 and until > ?2";
const DROP_LEASE: &str = "delete from _tinystore_jobs_leases where id = ?1 and attempt = ?2 and next = ?3";
const DROP_ANY_LEASE: &str = "delete from _tinystore_jobs_leases where id = ?1";
const EXTEND_LEASE: &str = "update _tinystore_jobs_leases set until = ?3 where id = ?1 and attempt = ?2 and next = ?4";
const JOB_HELD: &str = "select again, repeat, error, attempt, dedupe, keep, expires from _tinystore_jobs
where queue = ?1 and next = ?2 and id = ?3";
const JOB_SPILL: &str = "select spill from _tinystore_jobs where queue = ?1 and next = ?2 and id = ?3";
const DONE_SPILL: &str = "select spill, dedupe from _tinystore_jobs where queue = ?1 and next = ?2 and id = ?3
and again is null and repeat is null";
const MOVE_JOB: &str = "update _tinystore_jobs set next = ?4, at = ?5, attempt = ?6, again = null, error = ?7,
ran = coalesce(?8, ran), took = coalesce(?9, took)
where queue = ?1 and next = ?2 and id = ?3";
const FAIL_JOB: &str = "insert into _tinystore_jobs_failed (queue, id, key, at, attempt, failed, error, value, spill,
ran, took, grp, until)
select queue, id, key, at, ?4, ?5, ?6, value, spill, coalesce(?7, ran), coalesce(?8, took), grp, ?9
from _tinystore_jobs where queue = ?1 and next = ?2 and id = ?3";
const DONE_ID_SPILL: &str = "select spill from _tinystore_jobs_done where queue = ?1 and key = ?2";
const FORGET_DONE: &str = "delete from _tinystore_jobs_done where queue = ?1 and key = ?2";
const KEEP_DONE: &str =
"insert into _tinystore_jobs_done (queue, key, until, at, attempt, value, spill, ran, took, grp)
select queue, key, ?4, at, ?5, value, spill, coalesce(?6, ran), coalesce(?7, took), grp
from _tinystore_jobs where queue = ?1 and next = ?2 and id = ?3";
const DROP_JOB_ROW: &str = "delete from _tinystore_jobs where queue = ?1 and next = ?2 and id = ?3";
#[derive(Debug)]
pub(crate) struct Lease {
pub(crate) next: i64,
pub(crate) id: i64,
pub(crate) attempt: i64,
pub(crate) at: i64,
pub(crate) key: Option<String>,
pub(crate) spill: Option<i64>,
pub(crate) group: Option<String>,
pub(crate) inline: Option<Vec<u8>>,
state: Mutex<LeaseState>,
on_cancel: CancelHook,
}
#[derive(Default)]
struct CancelHook(Mutex<Option<Box<dyn FnOnce() + Send>>>);
impl std::fmt::Debug for CancelHook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("CancelHook")
}
}
#[derive(Debug, Default)]
struct LeaseState {
until: i64,
began: Option<i64>,
settled: bool,
lost: bool,
cancelled: bool,
progress: Option<serde_json::Value>,
}
type Place<'a> = (i64, i64, Option<&'a str>);
impl Lease {
pub(crate) fn until(&self) -> i64 {
self.lock().until
}
fn place(&self) -> Place<'_> {
(self.next, self.id, self.key.as_deref())
}
pub(crate) fn begin(&self, now: i64) -> bool {
let mut state = self.lock();
if state.cancelled {
return false;
}
state.began = Some(now);
true
}
pub(crate) fn running(&self, now: i64) -> bool {
let state = self.lock();
state.began.is_some() && !state.settled && state.until > now
}
pub(crate) fn started(&self) -> bool {
self.lock().began.is_some()
}
pub(crate) fn cancel(&self) {
let mut state = self.lock();
(state.settled, state.lost, state.cancelled) = (true, true, true);
drop(state);
let hook = self.on_cancel.0.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(hook) = hook {
hook();
}
}
#[cfg(feature = "wire")]
pub(crate) fn when_cancelled(&self, hook: Box<dyn FnOnce() + Send>) {
if self.cancelled() {
return hook();
}
*self.on_cancel.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(hook);
if self.cancelled()
&& let Some(hook) = self.on_cancel.0.lock().unwrap_or_else(PoisonError::into_inner).take()
{
hook();
}
}
pub(crate) fn cancelled(&self) -> bool {
self.lock().cancelled
}
pub(crate) fn settled(&self) -> bool {
self.lock().settled
}
pub(crate) fn progress(&self) -> Option<serde_json::Value> {
self.lock().progress.clone()
}
pub(crate) fn set_progress(&self, progress: serde_json::Value) {
self.lock().progress = Some(progress);
}
pub(crate) fn last_run(&self, now: i64) -> (Option<i64>, Option<i64>) {
let began = self.lock().began;
(began, began.map(|began| (now - began).max(0)))
}
pub(crate) fn apply(&self, settled: &Settled, extension: bool) {
let mut state = self.lock();
if let Some(until) = settled.until {
state.until = until;
}
if settled.lost {
(state.settled, state.lost) = (true, true);
} else if !extension {
state.settled = true;
}
}
fn lock(&self) -> MutexGuard<'_, LeaseState> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Claiming<'a> {
pub(crate) queue: &'a QueueState,
pub(crate) now: i64,
pub(crate) until: i64,
pub(crate) limit: usize,
}
#[derive(Debug, Default)]
pub(crate) struct Claimed {
pub(crate) leases: Vec<Lease>,
pub(crate) abandoned: Vec<i64>,
pub(crate) failed: usize,
pub(crate) more: bool,
}
pub(crate) fn claim(c: &Connection, claiming: Claiming<'_>) -> Result<Claimed> {
let room = room(c, &claiming)?;
let limit = match &claiming.queue.rate {
Some(rate) => rate.take(claiming.now, room),
None => room,
};
if limit == 0 {
return Ok(Claimed::default());
}
let claiming = Claiming { limit, ..claiming };
let grouped = claiming.queue.policy.concurrency.group.is_some() || claiming.queue.group_rates.is_some();
let claimed = if grouped { by_group(c, claiming) } else { in_order(c, claiming) };
if let Some(rate) = &claiming.queue.rate {
rate.give_back(limit - claimed.as_ref().map_or(0, |claimed| claimed.leases.len()));
}
claimed
}
fn room(c: &Connection, claiming: &Claiming<'_>) -> Result<usize> {
let Some(total) = claiming.queue.policy.concurrency.total else {
return Ok(claiming.limit);
};
let held: i64 = c
.prepare_cached(LIVE_LEASES)
.and_then(|mut select| select.query_row(params![claiming.queue.id, claiming.now], |row| row.get(0)))
.map_err(|error| sql_error("a claim: the jobs running", error))?;
let free = i64::from(total).saturating_sub(held).max(0);
Ok(claiming.limit.min(usize::try_from(free).unwrap_or(0)))
}
fn in_order(c: &Connection, claiming: Claiming<'_>) -> Result<Claimed> {
let mut claimed = Claimed::default();
for row in due(c, &claiming, claiming.limit)? {
claimed.lease(c, &claiming, row)?;
}
Ok(claimed)
}
fn by_group(c: &Connection, claiming: Claiming<'_>) -> Result<Claimed> {
let mut running = running_by_group(c, &claiming)?;
let mut claimed = Claimed::default();
let (mut moved, mut counted) = (0, Vec::new());
let walked = walk_by_group(c, &claiming, (&mut claimed, &mut counted), (&mut running, &mut moved));
match walked {
Ok(()) => Ok(claimed),
Err(error) => {
given_back(&claiming, &counted);
Err(error)
}
}
}
fn given_back(claiming: &Claiming<'_>, counted: &[String]) {
if let Some(rates) = &claiming.queue.group_rates {
counted.iter().for_each(|group| rates.give_back(group));
}
}
fn walk_by_group(
c: &Connection,
claiming: &Claiming<'_>,
(claimed, counted): (&mut Claimed, &mut Vec<String>),
(running, moved): (&mut HashMap<String, i64>, &mut usize),
) -> Result<()> {
let bound = i64::from(claiming.queue.policy.concurrency.group.unwrap_or(u32::MAX));
while claimed.leases.len() < claiming.limit {
let asked = claiming.limit - claimed.leases.len();
let due_now = due(c, claiming, asked)?;
let found = due_now.len();
for row in due_now {
let full = row.group.as_ref().is_some_and(|group| running.get(group).copied().unwrap_or(0) >= bound);
let to = match (&row.group, &claiming.queue.group_rates) {
_ if full => Some(row.next + PARKED_BY),
(Some(group), Some(rates)) => match rates.take(group, claiming.now) {
Ok(()) => {
counted.push(group.clone());
None
}
Err(turn) => Some(turn),
},
_ => None,
};
let rated = to.is_none() && row.group.is_some() && claiming.queue.group_rates.is_some();
if let Some(to) = to {
if *moved == PARK_AT_MOST {
claimed.more = true;
return Ok(());
}
*moved += 1;
rows::move_to(c, claiming.queue.id, (row.next, row.id, row.key.as_deref()), to)?;
continue;
}
let leased = claimed.lease_in_group(c, claiming, row, running)?;
if rated && !leased {
let group = counted.pop();
given_back(claiming, group.as_slice());
}
}
if found < asked {
break;
}
}
Ok(())
}
fn running_by_group(c: &Connection, claiming: &Claiming<'_>) -> Result<HashMap<String, i64>> {
let read = (RUNNING_IN_GROUPS, "a claim: the jobs each group runs");
query_cached(c, read, params![claiming.queue.id, claiming.now], |row| Ok((row.get(0)?, row.get(1)?)))
}
#[derive(Debug)]
struct DueRow {
next: i64,
id: i64,
key: Option<String>,
at: i64,
attempt: i64,
value: Option<Vec<u8>>,
spill: Option<i64>,
group: Option<String>,
expires: Option<i64>,
}
fn due(c: &Connection, claiming: &Claiming<'_>, limit: usize) -> Result<Vec<DueRow>> {
let read = (CLAIM_JOBS, "a claim: the jobs due");
query_cached(c, read, params![claiming.queue.id, claiming.now, limit as i64], |row| {
Ok(DueRow {
next: row.get(0)?,
id: row.get(1)?,
key: row.get(2)?,
at: row.get(3)?,
attempt: row.get(4)?,
value: row.get(5)?,
spill: row.get(6)?,
group: row.get(7)?,
expires: row.get(8)?,
})
})
}
impl Claimed {
fn lease(&mut self, c: &Connection, claiming: &Claiming<'_>, row: DueRow) -> Result<bool> {
let queue = claiming.queue;
if row.expires.is_some_and(|expires| expires <= claiming.now) {
end_term(c, queue, (row.next, row.id, row.key.as_deref()))?;
self.abandoned.push(row.id);
return Ok(false);
}
let lease = params![row.id, queue.id, row.next, row.attempt + 1, claiming.until];
execute(c, TAKE_LEASE, lease, "a claim: a job's lease")?;
let attempt: i64 = c
.prepare_cached(LEASE_ATTEMPT)
.and_then(|mut select| select.query_row([row.id], |found| found.get(0)))
.map_err(|error| sql_error("a claim: a job's lease", error))?;
if attempt > i64::from(queue.policy.attempts) {
if abandon(c, claiming, &row, attempt - 1)? {
self.failed += 1;
}
self.abandoned.push(row.id);
if let (Some(group), Some(_)) = (&row.group, queue.policy.concurrency.group) {
rows::unpark_one(c, queue.id, group)?;
}
return Ok(false);
}
let state = LeaseState { until: claiming.until, ..LeaseState::default() };
self.leases.push(Lease {
next: row.next,
id: row.id,
attempt,
at: row.at,
key: row.key,
spill: row.spill,
group: row.group,
inline: row.value,
state: Mutex::new(state),
on_cancel: CancelHook::default(),
});
Ok(true)
}
fn lease_in_group(
&mut self,
c: &Connection,
claiming: &Claiming<'_>,
row: DueRow,
running: &mut HashMap<String, i64>,
) -> Result<bool> {
let group = row.group.clone();
let leased = self.lease(c, claiming, row)?;
if leased && let Some(group) = group {
*running.entry(group).or_default() += 1;
}
Ok(leased)
}
}
fn abandon(c: &Connection, claiming: &Claiming<'_>, row: &DueRow, attempts: i64) -> Result<bool> {
let cause = format!(
"each of its {attempts} attempts ended without a settlement: its process died or its worker vanished while it ran"
);
let (queue, place) = (claiming.queue, (row.next, row.id, row.key.as_deref()));
execute(c, DROP_ANY_LEASE, [row.id], "an abandoned job's lease")?;
let held = held(c, queue, place)?;
if let Some(next) = next_run(row.at, &held, claiming.now) {
run_again(c, queue, (place, &held), (next, Some(cause)), (None, None))?;
return Ok(false);
}
let ending = Ending { attempts, cause: &cause, ran: (None, None), now: claiming.now };
failed_for_good(c, queue, (place, &held), &ending)?;
Ok(true)
}
struct Ending<'a> {
attempts: i64,
cause: &'a str,
ran: (Option<i64>, Option<i64>),
now: i64,
}
fn failed_for_good(
c: &Connection,
queue: &QueueState,
(place, held): (Place<'_>, &HeldRow),
ending: &Ending<'_>,
) -> Result<()> {
let (next, id, key) = place;
let keep = held.keep.unwrap_or_else(|| crate::clock::millis(queue.policy.keep));
if keep == 0 {
let spilled: Option<i64> = c
.prepare_cached(JOB_SPILL)
.and_then(|mut select| select.query_row(params![queue.id, next, id], |row| row.get(0)))
.map_err(|error| sql_error("a job failed for good", error))?;
execute(c, DROP_JOB_ROW, params![queue.id, next, id], "a job failed for good")?;
rows::drop_spill(c, spilled)?;
if let Some(key) = key {
queue.watchers.failed(key, ending.cause);
}
return Ok(());
}
let until = held.keep.map(|keep| ending.now.saturating_add(keep));
let (ran, took) = ending.ran;
let failed = params![queue.id, next, id, ending.attempts, ending.now, ending.cause, ran, took, until];
execute(c, FAIL_JOB, failed, "a job failed for good")?;
execute(c, DROP_JOB_ROW, params![queue.id, next, id], "a job failed for good").map(drop)
}
pub(crate) fn next_claim(c: &Connection, claiming: &Claiming<'_>) -> Result<Option<i64>> {
let full = claiming.queue.policy.concurrency.total.is_some() && room(c, &Claiming { limit: 1, ..*claiming })? == 0;
let earliest_lease: Option<i64> = c
.prepare_cached(EARLIEST_LEASE)
.and_then(|mut select| select.query_row(params![claiming.queue.id, claiming.now], |row| row.get(0)))
.map_err(|error| sql_error("a claim: the next lease to end", error))?;
if full {
return Ok(earliest_lease);
}
let due: Option<i64> = c
.prepare_cached(NEXT_DUE)
.and_then(|mut select| select.query_row(params![claiming.queue.id, claiming.now], |row| row.get(0)).optional())
.map_err(|error| sql_error("a claim: the next job due", error))?;
Ok(match (due, earliest_lease) {
(Some(due), Some(lease)) => Some(due.min(lease)),
(due, lease) => due.or(lease),
})
}
#[derive(Clone, Debug)]
pub(crate) enum How {
Done,
Retry {
at: Option<i64>,
cause: String,
},
Fail {
cause: String,
},
Snooze {
at: i64,
},
GiveBack,
Extend {
until: i64,
},
}
impl How {
pub(crate) fn outside_years(&self) -> Option<i64> {
match self {
How::Retry { at: Some(at), .. } | How::Snooze { at } if !in_years(*at) => Some(*at),
_ => None,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Settled {
pub(crate) failed: Option<String>,
pub(crate) due: Option<i64>,
pub(crate) lost: bool,
pub(crate) until: Option<i64>,
}
pub(crate) fn settle(c: &Connection, queue: &QueueState, lease: &Lease, how: &How, now: i64) -> Result<Settled> {
match write(c, queue, lease, how, now) {
Err(error) if error.kind() == ErrorKind::Conflict => Ok(Settled { lost: true, ..Settled::default() }),
settled => settled,
}
}
fn write(c: &Connection, queue: &QueueState, lease: &Lease, how: &How, now: i64) -> Result<Settled> {
if let How::Extend { until } = how {
changed_one(c, EXTEND_LEASE, params![lease.id, lease.attempt, until, lease.next])?;
return Ok(Settled { until: Some(*until), ..Settled::default() });
}
changed_one(c, DROP_LEASE, params![lease.id, lease.attempt, lease.next])?;
if !matches!(how, How::GiveBack)
&& let (Some(group), Some(_)) = (&lease.group, queue.policy.concurrency.group)
{
rows::unpark_one(c, queue.id, group)?;
}
if matches!(how, How::Done)
&& let Some(settled) = done_alone(c, queue, lease)?
{
return Ok(settled);
}
let held = held(c, queue, lease.place())?;
if let Some(settled) = superseded(c, queue, lease, (&held, how), now)? {
return Ok(settled);
}
let ran = lease.last_run(now);
match how {
How::Done => done(c, queue, lease, &held, now),
How::Retry { at, cause } => retry(c, queue, lease, &held, (*at, cause), now),
How::Fail { cause } => fail(c, queue, lease, &held, cause, now),
How::Snooze { at } if past_term(&held, *at) => {
end_term(c, queue, lease.place())?;
Ok(Settled::default())
}
How::Snooze { at } => {
let to = Moved { next: *at, at: lease.at, attempt: held.attempt, error: held.error.clone(), ran };
move_job(c, queue, lease.place(), &to)?;
Ok(Settled { due: Some(*at), ..Settled::default() })
}
How::GiveBack => {
let to = Moved {
next: lease.next,
at: lease.at,
attempt: held.attempt,
error: held.error.clone(),
ran: (None, None),
};
move_job(c, queue, lease.place(), &to)?;
Ok(Settled { due: Some(now), ..Settled::default() })
}
How::Extend { .. } => unreachable!("an extension returned above"),
}
}
fn superseded(
c: &Connection,
queue: &QueueState,
lease: &Lease,
(held, how): (&HeldRow, &How),
now: i64,
) -> Result<Option<Settled>> {
let error = match how {
How::Retry { cause, .. } => Some(bounded(cause)),
How::Snooze { .. } | How::GiveBack => None,
How::Done | How::Fail { .. } | How::Extend { .. } => return Ok(None),
};
match (held.again, next_run(lease.at, held, now)) {
(Some(_), Some(next)) => {
run_again(c, queue, (lease.place(), held), (next, error), lease.last_run(now)).map(Some)
}
_ => Ok(None),
}
}
fn done_alone(c: &Connection, queue: &QueueState, lease: &Lease) -> Result<Option<Settled>> {
let place = params![queue.id, lease.next, lease.id];
let found: Option<(Option<i64>, Option<String>)> = c
.prepare_cached(DONE_SPILL)
.and_then(|mut select| select.query_row(place, |row| Ok((row.get(0)?, row.get(1)?))).optional())
.map_err(|error| sql_error("a done job", error))?;
let Some((spilled, dedupe)) = found else {
return Ok(None);
};
if lease.key.is_some() && (dedupe.is_some() || queue.policy.dedupe.is_some()) {
return Ok(None);
}
execute(c, DROP_JOB_ROW, place, "a done job")?;
rows::drop_spill(c, spilled)?;
Ok(Some(Settled::default()))
}
#[derive(Debug)]
struct HeldRow {
again: Option<i64>,
repeat: Option<String>,
error: Option<String>,
attempt: i64,
dedupe: Option<String>,
keep: Option<i64>,
expires: Option<i64>,
}
fn held(c: &Connection, queue: &QueueState, (next, id, _): Place<'_>) -> Result<HeldRow> {
c.prepare_cached(JOB_HELD)
.and_then(|mut select| {
select
.query_row(params![queue.id, next, id], |row| {
Ok(HeldRow {
again: row.get(0)?,
repeat: row.get(1)?,
error: row.get(2)?,
attempt: row.get(3)?,
dedupe: row.get(4)?,
keep: row.get(5)?,
expires: row.get(6)?,
})
})
.optional()
})
.map_err(|error| sql_error("a settled job's row", error))?
.ok_or_else(lost)
}
fn done(c: &Connection, queue: &QueueState, lease: &Lease, held: &HeldRow, now: i64) -> Result<Settled> {
if let Some(next) = next_run(lease.at, held, now) {
return run_again(c, queue, (lease.place(), held), (next, None), lease.last_run(now));
}
let dedupe = match &held.dedupe {
Some(text) => Some(Dedupe::parse(text)?),
None => queue.policy.dedupe.clone(),
};
if let (Some(dedupe), Some(key)) = (dedupe, &lease.key) {
let forgotten: Option<Option<i64>> = c
.prepare_cached(DONE_ID_SPILL)
.and_then(|mut select| select.query_row(params![queue.id, key], |row| row.get(0)).optional())
.map_err(|error| sql_error("a done job's id", error))?;
if forgotten.is_some() {
execute(c, FORGET_DONE, params![queue.id, key], "a done job's id")?;
}
rows::drop_spill(c, forgotten.flatten())?;
let until = dedupe.until(now)?;
let (ran, took) = lease.last_run(now);
let keep = params![queue.id, lease.next, lease.id, until, lease.attempt, ran, took];
execute(c, KEEP_DONE, keep, "a done job's id")?;
execute(c, DROP_JOB_ROW, params![queue.id, lease.next, lease.id], "a done job")?;
return Ok(Settled::default());
}
let place = params![queue.id, lease.next, lease.id];
let spilled: Option<i64> = c
.prepare_cached(JOB_SPILL)
.and_then(|mut select| select.query_row(place, |row| row.get(0)))
.map_err(|error| sql_error("a done job", error))?;
execute(c, DROP_JOB_ROW, place, "a done job")?;
rows::drop_spill(c, spilled)?;
Ok(Settled::default())
}
fn retry(
c: &Connection,
queue: &QueueState,
lease: &Lease,
held: &HeldRow,
(at, cause): (Option<i64>, &str),
now: i64,
) -> Result<Settled> {
if lease.attempt >= i64::from(queue.policy.attempts) {
return fail(c, queue, lease, held, cause, now);
}
let mut due = at.unwrap_or_else(|| now.saturating_add(backoff(&queue.policy, lease.attempt, lease.id)));
if let Some(next) = next_run(lease.at, held, now) {
due = due.min(next);
}
if past_term(held, due) {
end_term(c, queue, lease.place())?;
return Ok(Settled::default());
}
let to = Moved {
next: due,
at: lease.at,
attempt: lease.attempt,
error: Some(bounded(cause)),
ran: lease.last_run(now),
};
move_job(c, queue, lease.place(), &to)?;
Ok(Settled { due: Some(due), ..Settled::default() })
}
fn fail(c: &Connection, queue: &QueueState, lease: &Lease, held: &HeldRow, cause: &str, now: i64) -> Result<Settled> {
let cause = bounded(cause);
if let Some(next) = next_run(lease.at, held, now) {
return run_again(c, queue, (lease.place(), held), (next, Some(cause)), lease.last_run(now));
}
let ending = Ending { attempts: lease.attempt, cause: &cause, ran: lease.last_run(now), now };
failed_for_good(c, queue, (lease.place(), held), &ending)?;
Ok(Settled { failed: Some(cause), ..Settled::default() })
}
fn next_run(at: i64, held: &HeldRow, now: i64) -> Option<i64> {
let repeated = held.repeat.as_deref().and_then(|text| match Repeat::parse(text) {
Ok(repeat) => repeat.next(at.max(now)),
Err(error) => {
tracing::error!(target: "tinystore", %error, "a repeating job's repeat does not read");
None
}
});
match (repeated, held.again) {
(Some(repeated), Some(again)) => Some(repeated.min(again)),
(repeated, again) => repeated.or(again),
}
}
struct Moved {
next: i64,
at: i64,
attempt: i64,
error: Option<String>,
ran: (Option<i64>, Option<i64>),
}
fn move_job(c: &Connection, queue: &QueueState, (next, id, key): Place<'_>, to: &Moved) -> Result<()> {
let (ran, took) = to.ran;
let moved = params![queue.id, next, id, to.next, to.at, to.attempt, to.error, ran, took];
execute(c, MOVE_JOB, moved, "a settled job")?;
match key {
Some(key) => rows::follow(c, queue.id, key, next, to.next),
None => Ok(()),
}
}
pub(crate) fn backoff(policy: &Policy, attempt: i64, id: i64) -> i64 {
let (initial, most) = (crate::clock::millis(policy.backoff.0), crate::clock::millis(policy.backoff.1));
let (initial, most) = (initial.min(LONGEST_SPAN), most.min(LONGEST_SPAN));
let mut wait = initial;
for _ in 1..attempt {
if wait >= most {
break;
}
wait = wait.saturating_mul(2);
}
let wait = wait.min(most);
let spread = wait / 5 + 1;
let jitter = i64::try_from(mix(id, attempt) % u64::try_from(spread).unwrap_or(1)).unwrap_or(0) - wait / 10;
(wait + jitter).max(1)
}
fn past_term(held: &HeldRow, at: i64) -> bool {
held.expires.is_some_and(|expires| at >= expires)
}
fn end_term(c: &Connection, queue: &QueueState, (next, id, key): Place<'_>) -> Result<()> {
rows::end_job(c, queue.id, (next, id))?;
if let Some(key) = key {
queue.watchers.cancelled(key, true);
}
Ok(())
}
fn run_again(
c: &Connection,
queue: &QueueState,
(place, held): (Place<'_>, &HeldRow),
(next, error): (i64, Option<String>),
ran: (Option<i64>, Option<i64>),
) -> Result<Settled> {
if past_term(held, next) {
end_term(c, queue, place)?;
return Ok(Settled::default());
}
rows::drop_steps(c, place.1)?;
let to = Moved { next, at: next, attempt: 0, error, ran };
move_job(c, queue, place, &to)?;
Ok(Settled { due: Some(next), ..Settled::default() })
}
fn mix(id: i64, attempt: i64) -> u64 {
fnv1a(id.to_le_bytes().into_iter().chain(attempt.to_le_bytes()))
}
fn bounded(cause: &str) -> String {
if cause.len() <= MAX_ERROR {
return cause.to_owned();
}
let mut end = MAX_ERROR;
while !cause.is_char_boundary(end) {
end -= 1;
}
format!("{}…", &cause[..end])
}
fn changed_one(c: &Connection, sql: &str, params: impl rusqlite::Params) -> Result<()> {
let changed = c
.prepare_cached(sql)
.and_then(|mut statement| statement.execute(params))
.map_err(|error| sql_error("a settlement: the job's lease", error))?;
if changed == 0 {
return Err(lost());
}
Ok(())
}
fn lost() -> Error {
Error::new(ErrorKind::Conflict, "the job's lease ended and another claim or a change took it")
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn a_retry_waits_longer_each_time_within_a_tenth_either_way() {
let policy = Policy { backoff: (Duration::from_secs(1), Duration::from_secs(60)), ..Policy::default() };
let waits: Vec<i64> = (1..=8).map(|attempt| backoff(&policy, attempt, 42)).collect();
for (attempt, wait) in (1..).zip(&waits) {
let expected = (1000i64 << (attempt - 1)).min(60_000);
assert!((expected * 9 / 10..=expected * 11 / 10 + 1).contains(wait), "attempt {attempt}: {wait}");
}
assert_ne!(backoff(&policy, 3, 42), backoff(&policy, 3, 43), "two jobs, two waits");
}
#[test]
fn a_backoff_with_no_most_waits_no_longer_than_a_job_may_and_never_overflows() {
let policy = Policy { backoff: (Duration::from_secs(1), Duration::MAX), ..Policy::default() };
for id in 0..100 {
let wait = backoff(&policy, 100, id);
assert!((1..=LONGEST_SPAN + LONGEST_SPAN / 10 + 1).contains(&wait), "job {id}: {wait}");
}
}
#[test]
fn a_kept_error_is_bounded_on_a_character() {
let long = "é".repeat(MAX_ERROR);
let kept = bounded(&long);
assert!(kept.len() <= MAX_ERROR + '…'.len_utf8());
assert!(kept.ends_with('…'));
}
}