use rusqlite::params;
use super::engine::Jobs;
use super::rows;
use crate::clock::millis;
use crate::sqlite::sql_error;
use crate::{Result, Store};
use crate::engine::{BATCH, BATCHES, in_batches};
const EXPIRE_FAILED: &str = "delete from _tinystore_jobs_failed where (queue, id) in (
select queue, id from _tinystore_jobs_failed where queue = ?1 and failed <= ?2
order by failed limit cast(?3 as integer))
returning spill";
const EXPIRE_DONE: &str = "delete from _tinystore_jobs_done where (queue, key) in (
select queue, key from _tinystore_jobs_done where until <= ?1 order by until limit cast(?2 as integer))
returning spill";
const KEYS_SLICE: &str = "select count(*), coalesce(max(key), '') from (
select key from _tinystore_jobs_keys where queue = ?1 and key > ?2 order by key limit cast(?3 as integer))";
const DROP_KEYS_LEFT: &str = "delete from _tinystore_jobs_keys where queue = ?1 and key > ?2 and key <= ?3
and not exists (select 1 from _tinystore_jobs j where j.queue = _tinystore_jobs_keys.queue
and j.next = _tinystore_jobs_keys.next and j.id = _tinystore_jobs_keys.id)";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Maintenance {
pub failed: usize,
pub done: usize,
pub ids: usize,
}
pub fn maintain(store: &Store) -> Result<Maintenance> {
let jobs = Jobs::of(store)?;
crate::sqlite::own_work(|| run(&jobs))
}
pub(crate) fn run(jobs: &Jobs) -> Result<Maintenance> {
let _one_at_a_time = jobs.hold_maintenance();
let now = jobs.now();
let mut done = Maintenance::default();
for queue in jobs.open_queues() {
let (id, cutoff) = (queue.id, now - millis(queue.policy.keep));
done.failed += batches(jobs, move |tx| expire(tx, EXPIRE_FAILED, params![id, cutoff, BATCH as i64]))?;
done.ids += drop_keys_left(jobs, id, &queue.keys_after)?;
}
done.done += batches(jobs, move |tx| expire(tx, EXPIRE_DONE, params![now, BATCH as i64]))?;
jobs.file().sweep();
Ok(done)
}
fn batches(
jobs: &Jobs,
batch: impl Fn(&crate::sqlite::Tx<'_>) -> Result<usize> + Clone + Send + 'static,
) -> Result<usize> {
in_batches(|| jobs.file().write(0, batch.clone()))
}
fn expire(c: &rusqlite::Connection, sql: &str, params: impl rusqlite::Params) -> Result<usize> {
let spilled: Vec<Option<i64>> = crate::sqlite::query_cached(c, (sql, "maintenance"), params, |row| row.get(0))?;
for spill in &spilled {
rows::drop_spill(c, *spill)?;
}
Ok(spilled.len())
}
fn drop_keys_left(jobs: &Jobs, queue: i64, after: &std::sync::Mutex<String>) -> Result<usize> {
let mut dropped = 0;
for _ in 0..BATCHES {
let from = after.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
let (examined, last, removed) = jobs.file().write(0, move |tx| {
let (examined, last): (i64, String) = tx
.prepare_cached(KEYS_SLICE)
.and_then(|mut select| {
select.query_row(params![queue, from, BATCH as i64], |row| Ok((row.get(0)?, row.get(1)?)))
})
.map_err(|error| sql_error("maintenance: ids", error))?;
if examined == 0 {
return Ok((0, last, 0));
}
let removed = tx
.prepare_cached(DROP_KEYS_LEFT)
.and_then(|mut delete| delete.execute(params![queue, from, last]))
.map_err(|error| sql_error("maintenance: ids left behind", error))?;
Ok((examined, last, removed))
})?;
dropped += removed;
let finished = usize::try_from(examined).unwrap_or(0) < BATCH;
*after.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = if finished { String::new() } else { last };
if finished {
break;
}
}
Ok(dropped)
}