use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex, PoisonError, TryLockError};
use std::time::Duration;
use rusqlite::Connection;
use super::Config;
use super::capture::{CHECKPOINT_AT, hook_wal, take_wal_end};
use super::connection::{self, Role};
use super::given::own;
pub(super) const SOFT: u32 = CHECKPOINT_AT;
pub(super) const HARD: u32 = 32 * SOFT;
const RESTART_WAIT: Duration = Duration::from_millis(100);
const CHECKPOINT: &str = own!("pragma wal_checkpoint(passive)");
const RESTART: &str = own!("pragma wal_checkpoint(restart)");
pub(crate) struct Checkpoints {
path: PathBuf,
config: Arc<Config>,
on: AtomicBool,
due: AtomicBool,
restart_from: AtomicU32,
connection: Mutex<Option<Connection>>,
}
impl Checkpoints {
pub(crate) fn of(path: &Path, config: &Arc<Config>, writer: &Connection) -> Checkpoints {
hook_wal(writer);
Checkpoints::new(path, config, true)
}
pub(crate) fn none(path: &Path, config: &Arc<Config>) -> Checkpoints {
Checkpoints::new(path, config, false)
}
fn new(path: &Path, config: &Arc<Config>, on: bool) -> Checkpoints {
Checkpoints {
path: path.to_owned(),
config: Arc::clone(config),
on: AtomicBool::new(on),
due: AtomicBool::new(false),
restart_from: AtomicU32::new(0),
connection: Mutex::new(None),
}
}
pub(crate) fn arm(&self) {
take_wal_end();
}
pub(crate) fn committed(&self, writer: &Connection) {
let Some(end) = take_wal_end() else { return };
if !self.on.load(Ordering::SeqCst) {
return;
}
if end >= HARD {
return self.at_the_bound(writer, end);
}
self.restart_from.store(0, Ordering::Relaxed);
if end >= SOFT {
self.due.store(true, Ordering::SeqCst);
}
}
fn at_the_bound(&self, writer: &Connection, end: u32) {
if end < self.restart_from.load(Ordering::Relaxed) {
return passive(writer);
}
let started_over = matches!(restart(writer, self.config.busy_timeout), Ok((0, _, _)));
let next = if started_over { 0 } else { restart_again_at(end) };
self.restart_from.store(next, Ordering::Relaxed);
}
pub(crate) fn run_due(&self) {
if !self.due.load(Ordering::Relaxed) {
return;
}
let mut connection = match self.connection.try_lock() {
Ok(connection) => connection,
Err(TryLockError::WouldBlock) => return,
Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
};
if !self.due.swap(false, Ordering::SeqCst) || !self.on.load(Ordering::SeqCst) {
return;
}
if connection.is_none() {
*connection = connection::open(&self.path, &self.config, Role::Reader).ok();
}
if let Some(connection) = connection.as_ref() {
passive(connection);
}
}
pub(crate) fn stop(&self) {
self.on.store(false, Ordering::SeqCst);
self.due.store(false, Ordering::SeqCst);
self.connection.lock().unwrap_or_else(PoisonError::into_inner).take();
}
}
fn passive(connection: &Connection) {
let _ = connection.query_row(CHECKPOINT, [], |_| Ok(()));
}
pub(super) fn restart(writer: &Connection, busy_timeout: Duration) -> rusqlite::Result<(i64, i64, i64)> {
writer.busy_timeout(RESTART_WAIT)?;
let restarted = writer.query_row(RESTART, [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)));
writer.busy_timeout(busy_timeout)?;
restarted
}
pub(super) fn restart_again_at(end: u32) -> u32 {
end.saturating_add(end.saturating_sub(HARD).max(SOFT))
}
#[cfg(test)]
#[path = "checkpoint_tests.rs"]
mod tests;