125 lines
3.4 KiB
Rust
125 lines
3.4 KiB
Rust
use std::{
|
|
path::PathBuf,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use crate::{AtomicFile, PersistedState, PersistenceError};
|
|
|
|
const DEBOUNCE: Duration = Duration::from_millis(500);
|
|
const MAX_DIRTY_AGE: Duration = Duration::from_secs(2);
|
|
|
|
/// Monotonic time source used by checkpoint scheduling.
|
|
pub trait Clock {
|
|
/// Elapsed monotonic time in an arbitrary clock-local epoch.
|
|
fn now(&self) -> Duration;
|
|
}
|
|
|
|
/// Production monotonic clock.
|
|
pub struct SystemClock {
|
|
origin: Instant,
|
|
}
|
|
|
|
impl Default for SystemClock {
|
|
fn default() -> Self {
|
|
Self {
|
|
origin: Instant::now(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Clock for SystemClock {
|
|
fn now(&self) -> Duration {
|
|
self.origin.elapsed()
|
|
}
|
|
}
|
|
|
|
/// Destination for validated checkpoint snapshots.
|
|
pub trait CheckpointSink {
|
|
/// Durably writes one complete snapshot.
|
|
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError>;
|
|
}
|
|
|
|
/// Atomic state-file checkpoint destination.
|
|
pub struct StateFileSink {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl StateFileSink {
|
|
/// Creates a sink for an already initialized private state directory.
|
|
pub fn new(path: impl Into<PathBuf>) -> Self {
|
|
Self { path: path.into() }
|
|
}
|
|
}
|
|
|
|
impl CheckpointSink for StateFileSink {
|
|
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError> {
|
|
let document = state
|
|
.to_toml()
|
|
.map_err(|error| PersistenceError::serialization(&self.path, error.to_string()))?;
|
|
AtomicFile::write(&self.path, document.as_bytes())
|
|
}
|
|
}
|
|
|
|
/// Pure debounce/max-latency coordinator retaining the newest complete state.
|
|
pub struct CheckpointCoordinator<C, S> {
|
|
clock: C,
|
|
sink: S,
|
|
pending: Option<PersistedState>,
|
|
dirty_since: Option<Duration>,
|
|
last_change: Option<Duration>,
|
|
}
|
|
|
|
impl<C: Clock, S: CheckpointSink> CheckpointCoordinator<C, S> {
|
|
/// Starts clean with the documented 500ms debounce and 2s maximum delay.
|
|
pub fn new(clock: C, sink: S) -> Self {
|
|
Self {
|
|
clock,
|
|
sink,
|
|
pending: None,
|
|
dirty_since: None,
|
|
last_change: None,
|
|
}
|
|
}
|
|
|
|
/// Replaces any pending snapshot with the newest validated state.
|
|
pub fn mark_dirty(&mut self, state: PersistedState) {
|
|
let now = self.clock.now();
|
|
self.dirty_since.get_or_insert(now);
|
|
self.last_change = Some(now);
|
|
self.pending = Some(state);
|
|
}
|
|
|
|
/// Flushes after a quiet debounce or once continuous changes reach 2s.
|
|
pub fn poll(&mut self) -> Result<bool, PersistenceError> {
|
|
let now = self.clock.now();
|
|
let due = self
|
|
.last_change
|
|
.is_some_and(|last| now.saturating_sub(last) >= DEBOUNCE)
|
|
|| self
|
|
.dirty_since
|
|
.is_some_and(|first| now.saturating_sub(first) >= MAX_DIRTY_AGE);
|
|
if due { self.flush() } else { Ok(false) }
|
|
}
|
|
|
|
/// Flushes the final dirty snapshot during orderly shutdown.
|
|
pub fn shutdown(&mut self) -> Result<bool, PersistenceError> {
|
|
self.flush()
|
|
}
|
|
|
|
/// Exposes the sink for diagnostics and deterministic tests.
|
|
pub const fn sink(&self) -> &S {
|
|
&self.sink
|
|
}
|
|
|
|
fn flush(&mut self) -> Result<bool, PersistenceError> {
|
|
let Some(state) = self.pending.as_ref() else {
|
|
return Ok(false);
|
|
};
|
|
self.sink.write(state)?;
|
|
self.pending = None;
|
|
self.dirty_since = None;
|
|
self.last_change = None;
|
|
Ok(true)
|
|
}
|
|
}
|