Skip to main content

link_cli/engine/
background_compaction.rs

1//! An optional worker that compacts a journal while commits continue.
2use super::{error, Engine, LinkReference};
3use crate::{LinkError, ReplaceableTransitionLogStore};
4use std::{
5    sync::{Arc, Condvar, Mutex, PoisonError},
6    thread::JoinHandle,
7    time::Duration,
8};
9
10/// Calls `compact_journal_after` every `period` on its own thread. Each pass that
11/// compacts holds the commit lock while the journal is replaced, so commits wait
12/// for it. The first failure ends the worker and `stop` returns it; a failed
13/// replacement also fences the engine until reopen, as with a manual compaction.
14/// Dropping the handle stops the worker and discards any failure.
15pub struct BackgroundCompaction {
16    stop: Arc<(Mutex<bool>, Condvar)>,
17    worker: Option<JoinHandle<Result<(), LinkError>>>,
18}
19
20impl BackgroundCompaction {
21    /// Refuses a zero `commits` or `period` and a log that cannot be replaced
22    /// before starting a thread.
23    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        // Nothing is due yet at this distance; this only checks the selection.
38        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    /// Waits for a running pass, then returns the failure that ended the worker.
73    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}