use std::ops::ControlFlow;
use std::panic;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tokio::time::{Instant, timeout_at};
use crate::db::{Inner, OPTIMIZE_SQL, blocking};
use crate::gate::Priority;
use crate::writer::Writer;
pub const OPTIMIZE_INTERVAL: Duration = Duration::from_secs(3600);
const SWEEP_FLOOR: Duration = Duration::from_secs(1);
#[derive(Clone, Copy)]
enum Job {
Sweep,
Checkpoint,
Optimize,
}
struct Timer {
job: Job,
every: Duration,
next: Option<Instant>,
}
pub struct Background {
stop: Arc<Notify>,
task: JoinHandle<()>,
}
impl Background {
pub fn start(inner: &Arc<Inner>, owner: bool) -> Self {
let stop = Arc::new(Notify::new());
let timers = timers(inner, owner);
let task = tokio::spawn(run(Arc::downgrade(inner), Arc::clone(&stop), timers));
Self { stop, task }
}
pub async fn stop(self) {
self.stop.notify_one();
if let Err(error) = self.task.await
&& let Ok(payload) = error.try_into_panic()
{
panic::resume_unwind(payload);
}
}
pub fn abort(&self) {
self.task.abort();
}
}
impl Job {
const fn name(self) -> &'static str {
match self {
Self::Sweep => "idle connection sweep",
Self::Checkpoint => "wal checkpoint",
Self::Optimize => "optimize",
}
}
}
impl Timer {
fn new(job: Job, every: Duration, now: Instant) -> Self {
Self {
job,
every,
next: now.checked_add(every),
}
}
}
fn timers(inner: &Inner, owner: bool) -> Vec<Timer> {
let now = Instant::now();
let options = inner.options();
let mut timers = vec![Timer::new(
Job::Sweep,
options.connection_max_idle.max(SWEEP_FLOOR),
now,
)];
if owner {
timers.push(Timer::new(
Job::Checkpoint,
options.checkpoint_interval,
now,
));
timers.push(Timer::new(Job::Optimize, OPTIMIZE_INTERVAL, now));
}
timers
}
async fn run(inner: Weak<Inner>, stop: Arc<Notify>, mut timers: Vec<Timer>) {
while let Some(next) = timers.iter().filter_map(|timer| timer.next).min() {
if timeout_at(next, stop.notified()).await.is_ok() {
return;
}
let Some(inner) = inner.upgrade() else {
return;
};
let now = Instant::now();
for timer in timers
.iter_mut()
.filter(|timer| timer.next.is_some_and(|next| next <= now))
{
timer.next = now.checked_add(timer.every);
if run_job(&inner, &stop, timer.job).await.is_break() {
return;
}
}
}
}
async fn run_job(inner: &Arc<Inner>, stop: &Notify, job: Job) -> ControlFlow<()> {
match job {
Job::Sweep => maintain(inner, job).await,
Job::Checkpoint | Job::Optimize => tokio::select! {
biased;
() = stop.notified() => return ControlFlow::Break(()),
() = maintain(inner, job) => {}
},
}
ControlFlow::Continue(())
}
async fn maintain(inner: &Arc<Inner>, job: Job) {
let result = match job {
Job::Sweep => {
let inner = Arc::clone(inner);
blocking(move || inner.sweep()).await
}
Job::Checkpoint => {
inner
.exclusive(Priority::Normal, Writer::checkpoint_passive)
.await
}
Job::Optimize => {
inner
.exclusive(Priority::Normal, |writer| writer.optimize(OPTIMIZE_SQL))
.await
}
};
if let Err(error) = result {
tracing::warn!(%error, job = job.name(), "sqlitedb: periodic maintenance failed");
}
}