use super::{error, Engine, LinkReference};
use crate::{LinkError, ReplaceableTransitionLogStore};
use std::{
sync::{Arc, Condvar, Mutex, PoisonError},
thread::JoinHandle,
time::Duration,
};
pub struct BackgroundCompaction {
stop: Arc<(Mutex<bool>, Condvar)>,
worker: Option<JoinHandle<Result<(), LinkError>>>,
}
impl BackgroundCompaction {
pub fn start<T, L>(
engine: Engine<T, L>,
commits: u64,
period: Duration,
) -> Result<Self, LinkError>
where
T: LinkReference + Send + 'static,
L: ReplaceableTransitionLogStore + Send + 'static,
{
if commits == 0 || period.is_zero() {
return Err(error(
"compaction needs a commit count and a period above zero",
));
}
engine.compact_journal_after(u64::MAX)?;
let stop = Arc::new((Mutex::new(false), Condvar::new()));
let signal = stop.clone();
let worker = std::thread::spawn(move || {
let (stopped, wake) = &*signal;
let mut guard = stopped.lock().unwrap_or_else(PoisonError::into_inner);
loop {
guard = wake
.wait_timeout_while(guard, period, |stopped| !*stopped)
.unwrap_or_else(PoisonError::into_inner)
.0;
if *guard {
return Ok(());
}
engine.compact_journal_after(commits)?;
}
});
Ok(Self {
stop,
worker: Some(worker),
})
}
fn join(&mut self) -> Result<(), LinkError> {
let Some(worker) = self.worker.take() else {
return Ok(());
};
*self.stop.0.lock().unwrap_or_else(PoisonError::into_inner) = true;
self.stop.1.notify_all();
worker
.join()
.unwrap_or_else(|_| Err(error("the compaction worker panicked")))
}
pub fn stop(mut self) -> Result<(), LinkError> {
self.join()
}
}
impl Drop for BackgroundCompaction {
fn drop(&mut self) {
let _ = self.join();
}
}