use rusqlite::{Connection, OptionalExtension, Params, params};
use super::values::Kept;
use crate::Result;
use crate::limits::Limit;
use crate::sqlite::sql_error;
pub(crate) const PARKED_BY: i64 = 1 << 60;
pub(crate) const PARKED_FROM: i64 = 1 << 59;
macro_rules! parked_from {
() => {
"576460752303423488"
};
}
pub(crate) fn due_of(next: i64) -> i64 {
if next >= PARKED_FROM { next - PARKED_BY } else { next }
}
const REGISTER_QUEUE: &str =
"insert into _tinystore_jobs_queues (name, kind) values (?1, ?2) on conflict (name) do nothing";
const QUEUE_NAMED: &str = "select id, kind, in_group from _tinystore_jobs_queues where name = ?1";
const COUNT_WAITING: &str = "select waiting from _tinystore_jobs_queues where id = ?1";
const KEEP_IN_GROUP: &str = "update _tinystore_jobs_queues set in_group = ?2 where id = ?1";
const UNPARK_JOBS: &str =
concat!("update _tinystore_jobs set next = next - ?2 where queue = ?1 and next >= ", parked_from!());
const UNPARK_KEYS: &str =
concat!("update _tinystore_jobs_keys set next = next - ?2 where queue = ?1 and next >= ", parked_from!());
const NEXT_ID: &str = "update _tinystore_jobs_meta set value = value + 1 where name = 'ids'";
const IDS: &str = "select value from _tinystore_jobs_meta where name = 'ids'";
const COUNT_DEAD_ATTEMPTS: &str = "update _tinystore_jobs set attempt = l.attempt from _tinystore_jobs_leases l
where _tinystore_jobs.queue = l.queue and _tinystore_jobs.next = l.next and _tinystore_jobs.id = l.id";
const DROP_DEAD_LEASES: &str = "delete from _tinystore_jobs_leases";
const COUNT_ENDED_ATTEMPT: &str = "update _tinystore_jobs set attempt = l.attempt from _tinystore_jobs_leases l
where l.id = ?1 and _tinystore_jobs.queue = l.queue and _tinystore_jobs.next = l.next and _tinystore_jobs.id = l.id";
const JOB_BY_KEY: &str = "select j.next, j.id, j.again, j.repeat, j.spill, j.expires
from _tinystore_jobs_keys k join _tinystore_jobs j on j.queue = k.queue and j.next = k.next and j.id = k.id
where k.queue = ?1 and k.key = ?2";
const LEASE_HELD: &str = "select 1 from _tinystore_jobs_leases where id = ?1 and until > ?2";
const DONE_KEY: &str = "select 1 from _tinystore_jobs_done where queue = ?1 and key = ?2 and until > ?3";
const INSERT_JOB: &str =
"insert into _tinystore_jobs (queue, next, id, key, at, attempt, repeat, value, spill, grp, error, dedupe, keep,
expires)
values (?1, ?2, ?3, ?4, ?2, 0, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)";
const INSERT_SPILLED: &str = "insert into _tinystore_jobs_spilled (id, value) values (?1, ?2)";
const DELETE_SPILLED: &str = "delete from _tinystore_jobs_spilled where id = ?1";
const INSERT_KEY: &str = "insert into _tinystore_jobs_keys (queue, key, next, id) values (?1, ?2, ?3, ?4)
on conflict (queue, key) do update set next = excluded.next, id = excluded.id";
const MOVE_KEY: &str = "update _tinystore_jobs_keys set next = ?3 where queue = ?1 and key = ?2";
const DROP_KEY: &str = "delete from _tinystore_jobs_keys where queue = ?1 and key = ?2";
const RENEW_JOB: &str = "update _tinystore_jobs
set next = ?4, at = ?4, attempt = 0, again = null, error = null, value = ?5, spill = ?6,
repeat = coalesce(?7, repeat), grp = coalesce(?8, grp),
dedupe = coalesce(?9, dedupe), keep = coalesce(?10, keep), expires = coalesce(?11, expires)
where queue = ?1 and next = ?2 and id = ?3";
const UPDATE_JOB: &str = "update _tinystore_jobs
set next = ?4, at = ?4, value = ?5, spill = ?6, repeat = coalesce(?7, repeat), grp = coalesce(?8, grp),
dedupe = coalesce(?9, dedupe), keep = coalesce(?10, keep), expires = coalesce(?11, expires)
where queue = ?1 and next = ?2 and id = ?3";
const ASK_AGAIN: &str = "update _tinystore_jobs
set again = ?4, value = ?5, spill = ?6, repeat = coalesce(?7, repeat), grp = coalesce(?8, grp),
dedupe = coalesce(?9, dedupe), keep = coalesce(?10, keep), expires = coalesce(?11, expires)
where queue = ?1 and next = ?2 and id = ?3";
const SHAPE_OF: &str = "select
coalesce(j.value, (select s.value from _tinystore_jobs_spilled s where s.id = j.spill)) is ?4,
j.grp, j.dedupe, j.keep, j.expires
from _tinystore_jobs j where j.queue = ?1 and j.next = ?2 and j.id = ?3";
const RENEW_TERM: &str = "update _tinystore_jobs set expires = ?4 where queue = ?1 and next = ?2 and id = ?3";
const END_TERM: &str = "delete from _tinystore_jobs where queue = ?1 and next = ?2 and id = ?3 returning spill";
const RESHAPE_JOB: &str = "update _tinystore_jobs
set at = case when next = ?4 then at else ?4 end, next = ?4, value = ?5, spill = ?6,
repeat = coalesce(?7, repeat), grp = coalesce(?8, grp),
dedupe = coalesce(?9, dedupe), keep = coalesce(?10, keep), expires = coalesce(?11, expires)
where queue = ?1 and next = ?2 and id = ?3";
const RUN_AFTER: &str = "update _tinystore_jobs set again = min(coalesce(again, ?4), ?4)
where queue = ?1 and next = ?2 and id = ?3";
const DUE_NOW: &str = "update _tinystore_jobs set next = ?4, at = case when attempt = 0 then ?4 else at end
where queue = ?1 and next = ?2 and id = ?3";
const DROP_FAILED: &str =
"delete from _tinystore_jobs_failed where queue = ?1 and key = ?2 returning spill, grp, error";
const CANCEL_JOB: &str = "delete from _tinystore_jobs where (queue, next, id) in (
select k.queue, k.next, k.id from _tinystore_jobs_keys k where k.queue = ?1 and k.key = ?2)
returning id, spill, next, grp";
const CANCEL_ROW: &str = "delete from _tinystore_jobs
where queue = ?1 and next in (?2, ?3) and id = ?4 and key is null
returning id, spill, next, grp";
const DROP_FAILED_ROW: &str = "delete from _tinystore_jobs_failed
where queue = ?1 and id = ?2 and failed = ?3 and key is null
returning spill";
const DROP_LEASE: &str = "delete from _tinystore_jobs_leases where id = ?1";
const DROP_STEPS: &str = "delete from _tinystore_jobs_steps where job = ?1";
const FIRST_PARKED: &str = concat!(
"select next, id, key from _tinystore_jobs indexed by _tinystore_jobs_parked
where queue = ?1 and grp = ?2 and next >= ",
parked_from!(),
" order by next, id limit 1"
);
const MOVE_ROW: &str = "update _tinystore_jobs set next = ?4 where queue = ?1 and next = ?2 and id = ?3";
const MOVE_LEASE: &str = "update _tinystore_jobs_leases set next = ?2 where id = ?1";
#[derive(Clone, Debug)]
pub(crate) struct Row {
pub(crate) next: i64,
pub(crate) id: i64,
pub(crate) again: Option<i64>,
pub(crate) repeat: Option<String>,
pub(crate) spill: Option<i64>,
pub(crate) expires: Option<i64>,
}
#[derive(Debug)]
pub(crate) struct NewJob<'a> {
pub(crate) queue: i64,
pub(crate) id: i64,
pub(crate) key: Option<&'a str>,
pub(crate) at: i64,
pub(crate) repeat: Option<&'a str>,
pub(crate) group: Option<&'a str>,
pub(crate) error: Option<&'a str>,
pub(crate) own: Own<'a>,
pub(crate) value: &'a Kept,
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Own<'a> {
pub(crate) dedupe: Option<&'a str>,
pub(crate) keep: Option<i64>,
pub(crate) expires: Option<i64>,
}
#[derive(Debug)]
pub(crate) struct Shape {
pub(crate) same_value: bool,
pub(crate) group: Option<String>,
pub(crate) dedupe: Option<String>,
pub(crate) keep: Option<i64>,
pub(crate) expires: Option<i64>,
}
#[derive(Debug)]
pub(crate) struct Failed {
pub(crate) group: Option<String>,
pub(crate) error: Option<String>,
}
#[derive(Debug)]
pub(crate) struct Change<'a> {
pub(crate) next: i64,
pub(crate) repeat: Option<&'a str>,
pub(crate) group: Option<&'a str>,
pub(crate) own: Own<'a>,
pub(crate) value: &'a Kept,
}
#[cfg(feature = "replication")]
pub(crate) fn find_queue(c: &Connection, name: &str) -> Result<Option<(i64, String)>> {
c.prepare_cached(QUEUE_NAMED)
.and_then(|mut select| select.query_row([name], |row| Ok((row.get(0)?, row.get(1)?))).optional())
.map_err(|error| sql_error("a queue's registration", error))
}
pub(crate) fn queue(c: &Connection, name: &str, kind: &str) -> Result<(i64, String, i64)> {
let named = || {
c.prepare_cached(QUEUE_NAMED)
.and_then(|mut select| {
select.query_row([name], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))).optional()
})
.map_err(|error| sql_error("a queue's registration", error))
};
if let Some(found) = named()? {
return Ok(found);
}
execute(c, REGISTER_QUEUE, params![name, kind], "a queue's registration")?;
named()?.ok_or_else(|| crate::Error::internal("a queue registered and not found"))
}
pub(crate) fn keep_group_bound(c: &Connection, queue: i64, was: i64, is: i64) -> Result<()> {
if was == is {
return Ok(());
}
execute(c, UNPARK_JOBS, params![queue, PARKED_BY], "the jobs another group bound parked")?;
execute(c, UNPARK_KEYS, params![queue, PARKED_BY], "the jobs another group bound parked")?;
execute(c, KEEP_IN_GROUP, params![queue, is], "a queue's group bound").map(drop)
}
pub(crate) fn next_id(c: &Connection) -> Result<i64> {
execute(c, NEXT_ID, [], "the next job id")?;
c.prepare_cached(IDS)
.and_then(|mut select| select.query_row([], |row| row.get(0)))
.map_err(|error| sql_error("the next job id", error))
}
pub(crate) fn end_dead_leases(c: &Connection) -> Result<()> {
execute(c, COUNT_DEAD_ATTEMPTS, [], "the leases of a process that died")?;
execute(c, DROP_DEAD_LEASES, [], "the leases of a process that died").map(drop)
}
pub(crate) fn job_by_key(c: &Connection, queue: i64, key: &str) -> Result<Option<Row>> {
c.prepare_cached(JOB_BY_KEY)
.and_then(|mut select| {
select
.query_row(params![queue, key], |row| {
Ok(Row {
next: row.get(0)?,
id: row.get(1)?,
again: row.get(2)?,
repeat: row.get(3)?,
spill: row.get(4)?,
expires: row.get(5)?,
})
})
.optional()
})
.map_err(|error| sql_error("the job under an id", error))
}
pub(crate) fn lease_held(c: &Connection, id: i64, now: i64) -> Result<bool> {
exists(c, LEASE_HELD, params![id, now])
}
pub(crate) fn done_key(c: &Connection, queue: i64, key: &str, now: i64) -> Result<bool> {
exists(c, DONE_KEY, params![queue, key, now])
}
pub(crate) fn check_room(c: &Connection, queue: i64, max_waiting: u64) -> Result<()> {
let waiting: i64 = c
.prepare_cached(COUNT_WAITING)
.and_then(|mut select| select.query_row([queue], |row| row.get(0)))
.map_err(|error| sql_error("the jobs a queue holds", error))?;
let waiting = u64::try_from(waiting).unwrap_or(0);
if waiting >= max_waiting {
let held = Limit { name: "waiting jobs", bound: max_waiting };
return Err(held.refuse(waiting + 1, format!("the queue holds {waiting} jobs, its max_waiting")));
}
Ok(())
}
pub(crate) fn insert(c: &Connection, job: &NewJob<'_>) -> Result<()> {
let spill = spill(c, job.id, job.value)?;
let (inline, own) = (job.value.inline(), job.own);
let params = params![
job.queue,
job.at,
job.id,
job.key,
job.repeat,
inline,
spill,
job.group,
job.error,
own.dedupe,
own.keep,
own.expires
];
execute(c, INSERT_JOB, params, "a job's row")?;
if let Some(key) = job.key {
execute(c, INSERT_KEY, params![job.queue, key, job.at, job.id], "a job's id")?;
}
Ok(())
}
pub(crate) fn renew(c: &Connection, queue: i64, key: &str, there: &Row, change: &Change<'_>) -> Result<()> {
end_lease(c, there.id)?;
rewrite(c, queue, there, (Some(change.next), change), (RENEW_JOB, "a set's job"))?;
execute(c, DROP_STEPS, [there.id], "a set's job: the steps of its last run")?;
follow(c, queue, key, there.next, change.next)
}
pub(crate) fn update(c: &Connection, queue: i64, key: &str, there: &Row, change: &Change<'_>) -> Result<()> {
end_lease(c, there.id)?;
rewrite(c, queue, there, (Some(change.next), change), (UPDATE_JOB, "an update's job"))?;
execute(c, DROP_STEPS, [there.id], "an update's job: the steps kept for its old value")?;
follow(c, queue, key, there.next, change.next)
}
pub(crate) fn shape(c: &Connection, queue: i64, there: &Row, value: &Kept) -> Result<Shape> {
c.prepare_cached(SHAPE_OF)
.and_then(|mut select| {
select.query_row(params![queue, there.next, there.id, value.bytes()], |row| {
let (same_value, group, dedupe) = (row.get(0)?, row.get(1)?, row.get(2)?);
Ok(Shape { same_value, group, dedupe, keep: row.get(3)?, expires: row.get(4)? })
})
})
.map_err(|error| sql_error("an upsert's job", error))
}
pub(crate) fn reshape(
c: &Connection,
(queue, key): (i64, &str),
there: &Row,
change: &Change<'_>,
value_changed: bool,
) -> Result<()> {
end_lease(c, there.id)?;
rewrite(c, queue, there, (Some(change.next), change), (RESHAPE_JOB, "an upsert's job"))?;
if value_changed {
execute(c, DROP_STEPS, [there.id], "an upsert's job: the steps kept for its old value")?;
}
follow(c, queue, key, there.next, change.next)
}
fn end_lease(c: &Connection, id: i64) -> Result<()> {
execute(c, COUNT_ENDED_ATTEMPT, [id], "the lease a changed job outlived")?;
execute(c, DROP_LEASE, [id], "the lease a changed job outlived").map(drop)
}
fn rewrite(
c: &Connection,
queue: i64,
there: &Row,
(time, change): (Option<i64>, &Change<'_>),
(statement, what): (&str, &str),
) -> Result<()> {
drop_spill(c, there.spill)?;
let (spill, own) = (spill(c, there.id, change.value)?, change.own);
let (inline, repeat, group) = (change.value.inline(), change.repeat, change.group);
let own = (own.dedupe, own.keep, own.expires);
let params = params![queue, there.next, there.id, time, inline, spill, repeat, group, own.0, own.1, own.2];
execute(c, statement, params, what).map(drop)
}
pub(crate) fn ask_again(
c: &Connection,
queue: i64,
there: &Row,
again: Option<i64>,
change: &Change<'_>,
) -> Result<()> {
rewrite(c, queue, there, (again, change), (ASK_AGAIN, "a set of a running job"))
}
pub(crate) fn renew_term(c: &Connection, queue: i64, there: &Row, expires: i64) -> Result<()> {
execute(c, RENEW_TERM, params![queue, there.next, there.id, expires], "a job's renewed term").map(drop)
}
pub(crate) fn end_term(c: &Connection, queue: i64, there: &Row) -> Result<()> {
end_job(c, queue, (there.next, there.id))
}
pub(crate) fn end_job(c: &Connection, queue: i64, (next, id): (i64, i64)) -> Result<()> {
let spilled: Option<Option<i64>> = c
.prepare_cached(END_TERM)
.and_then(|mut delete| delete.query_row(params![queue, next, id], |row| row.get(0)).optional())
.map_err(|error| sql_error("a job its term ended", error))?;
execute(c, DROP_LEASE, [id], "a job its term ended: its lease")?;
drop_spill(c, spilled.flatten())
}
pub(crate) fn run_after(c: &Connection, queue: i64, there: &Row, at: i64) -> Result<()> {
execute(c, RUN_AFTER, params![queue, there.next, there.id, at], "a run asked of a running job").map(drop)
}
pub(crate) fn due_now(c: &Connection, queue: i64, key: &str, there: &Row, now: i64) -> Result<()> {
end_lease(c, there.id)?;
execute(c, DUE_NOW, params![queue, there.next, there.id, now], "a job made due now")?;
follow(c, queue, key, there.next, now)
}
pub(crate) fn drop_failed(c: &Connection, queue: i64, key: &str) -> Result<Option<Failed>> {
let dropped: Option<(Option<i64>, Failed)> = c
.prepare_cached(DROP_FAILED)
.and_then(|mut delete| {
let failed = |row: &rusqlite::Row<'_>| Ok((row.get(0)?, Failed { group: row.get(1)?, error: row.get(2)? }));
delete.query_row(params![queue, key], failed).optional()
})
.map_err(|error| sql_error("a failed job", error))?;
let Some((spilled, failed)) = dropped else {
return Ok(None);
};
drop_spill(c, spilled)?;
Ok(Some(failed))
}
#[derive(Debug)]
pub(crate) struct Taken {
pub(crate) id: i64,
pub(crate) group: Option<String>,
pub(crate) placed: bool,
}
pub(crate) fn cancel(c: &Connection, queue: i64, key: &str) -> Result<Option<Taken>> {
let Some(taken) = take(c, CANCEL_JOB, params![queue, key])? else {
return Ok(None);
};
execute(c, DROP_KEY, params![queue, key], "a cancel: the job's id")?;
Ok(Some(taken))
}
pub(crate) fn cancel_row(c: &Connection, queue: i64, due: i64, number: i64) -> Result<Option<Taken>> {
take(c, CANCEL_ROW, params![queue, due, due.saturating_add(PARKED_BY), number])
}
fn take(c: &Connection, delete: &str, params: impl Params) -> Result<Option<Taken>> {
let taken: Option<(i64, Option<i64>, i64, Option<String>)> = c
.prepare_cached(delete)
.and_then(|mut delete| {
delete.query_row(params, |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))).optional()
})
.map_err(|error| sql_error("a cancel", error))?;
let Some((id, spilled, next, group)) = taken else {
return Ok(None);
};
execute(c, DROP_LEASE, [id], "a cancel: the job's lease")?;
drop_spill(c, spilled)?;
Ok(Some(Taken { id, group, placed: next < PARKED_FROM }))
}
pub(crate) fn drop_failed_row(c: &Connection, queue: i64, failed: i64, number: i64) -> Result<bool> {
let dropped: Option<Option<i64>> = c
.prepare_cached(DROP_FAILED_ROW)
.and_then(|mut delete| delete.query_row(params![queue, number, failed], |row| row.get(0)).optional())
.map_err(|error| sql_error("a failed job", error))?;
let Some(spilled) = dropped else {
return Ok(false);
};
drop_spill(c, spilled)?;
Ok(true)
}
pub(crate) fn unpark_one(c: &Connection, queue: i64, group: &str) -> Result<()> {
let first: Option<(i64, i64, Option<String>)> = c
.prepare_cached(FIRST_PARKED)
.and_then(|mut select| {
select.query_row(params![queue, group], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))).optional()
})
.map_err(|error| sql_error("a group's first parked job", error))?;
let Some((next, id, key)) = first else {
return Ok(());
};
move_to(c, queue, (next, id, key.as_deref()), next - PARKED_BY)
}
pub(crate) fn move_to(c: &Connection, queue: i64, (next, id, key): (i64, i64, Option<&str>), to: i64) -> Result<()> {
execute(c, MOVE_ROW, params![queue, next, id, to], "a job's move")?;
execute(c, MOVE_LEASE, params![id, to], "a job's move: its lease")?;
match key {
Some(key) => follow(c, queue, key, next, to),
None => Ok(()),
}
}
pub(crate) fn follow(c: &Connection, queue: i64, key: &str, from: i64, to: i64) -> Result<()> {
if from == to {
return Ok(());
}
execute(c, MOVE_KEY, params![queue, key, to], "a job's id").map(drop)
}
pub(crate) fn drop_spill(c: &Connection, spilled: Option<i64>) -> Result<()> {
match spilled {
Some(id) => execute(c, DELETE_SPILLED, [id], "a large value").map(drop),
None => Ok(()),
}
}
pub(crate) fn drop_steps(c: &Connection, job: i64) -> Result<()> {
execute(c, DROP_STEPS, [job], "the steps of a run that ended").map(drop)
}
fn spill(c: &Connection, id: i64, value: &Kept) -> Result<Option<i64>> {
match value {
Kept::Inline(_) => Ok(None),
Kept::Spilled(bytes) => {
execute(c, INSERT_SPILLED, params![id, bytes], "a large value")?;
Ok(Some(id))
}
}
}
pub(crate) use crate::sqlite::execute_cached as execute;
pub(crate) fn exists(c: &Connection, sql: &str, params: impl Params) -> Result<bool> {
c.prepare_cached(sql).and_then(|mut select| select.exists(params)).map_err(|error| sql_error("a read", error))
}