link_cli/engine/
background_compaction.rs1use super::{error, Engine, LinkReference};
3use crate::{LinkError, ReplaceableTransitionLogStore};
4use std::{
5 sync::{Arc, Condvar, Mutex, PoisonError},
6 thread::JoinHandle,
7 time::Duration,
8};
9
10pub struct BackgroundCompaction {
16 stop: Arc<(Mutex<bool>, Condvar)>,
17 worker: Option<JoinHandle<Result<(), LinkError>>>,
18}
19
20impl BackgroundCompaction {
21 pub fn start<T, L>(
24 engine: Engine<T, L>,
25 commits: u64,
26 period: Duration,
27 ) -> Result<Self, LinkError>
28 where
29 T: LinkReference + Send + 'static,
30 L: ReplaceableTransitionLogStore + Send + 'static,
31 {
32 if commits == 0 || period.is_zero() {
33 return Err(error(
34 "compaction needs a commit count and a period above zero",
35 ));
36 }
37 engine.compact_journal_after(u64::MAX)?;
39 let stop = Arc::new((Mutex::new(false), Condvar::new()));
40 let signal = stop.clone();
41 let worker = std::thread::spawn(move || {
42 let (stopped, wake) = &*signal;
43 let mut guard = stopped.lock().unwrap_or_else(PoisonError::into_inner);
44 loop {
45 guard = wake
46 .wait_timeout_while(guard, period, |stopped| !*stopped)
47 .unwrap_or_else(PoisonError::into_inner)
48 .0;
49 if *guard {
50 return Ok(());
51 }
52 engine.compact_journal_after(commits)?;
53 }
54 });
55 Ok(Self {
56 stop,
57 worker: Some(worker),
58 })
59 }
60
61 fn join(&mut self) -> Result<(), LinkError> {
62 let Some(worker) = self.worker.take() else {
63 return Ok(());
64 };
65 *self.stop.0.lock().unwrap_or_else(PoisonError::into_inner) = true;
66 self.stop.1.notify_all();
67 worker
68 .join()
69 .unwrap_or_else(|_| Err(error("the compaction worker panicked")))
70 }
71
72 pub fn stop(mut self) -> Result<(), LinkError> {
74 self.join()
75 }
76}
77
78impl Drop for BackgroundCompaction {
79 fn drop(&mut self) {
80 let _ = self.join();
81 }
82}