Skip to main content

subspace_core/
run_day_log.rs

1//! Bounded JSON Lines chunks for the most recent local dates with writes.
2//! The dated file is canonical; the stable live file mirrors its current chunk.
3
4mod files;
5mod lock;
6mod marker;
7mod migration;
8mod retention;
9
10use std::io;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14use chrono::{Local, NaiveDate};
15
16pub use marker::generation;
17
18const DEFAULT_MAX_BYTES: u64 = 5 << 20;
19const DEFAULT_MAX_DATES: usize = 5;
20
21/// A date's chunk bound and the number of dates retained, including the active date.
22#[derive(Clone, Copy, Debug)]
23pub struct Limits {
24    max_bytes: u64,
25    max_dates: usize,
26}
27
28impl Limits {
29    pub fn new(max_file_bytes: u64, max_dates: usize) -> Self {
30        Self {
31            max_bytes: max_file_bytes,
32            max_dates: max_dates.max(1),
33        }
34    }
35}
36
37impl Default for Limits {
38    fn default() -> Self {
39        Self {
40            max_bytes: DEFAULT_MAX_BYTES,
41            max_dates: DEFAULT_MAX_DATES,
42        }
43    }
44}
45
46/// One writer, externally synchronized when shared between recorders.
47pub struct RunDayLog {
48    live: PathBuf,
49    limits: Limits,
50    clock: Arc<dyn Fn() -> NaiveDate + Send + Sync>,
51    active: Option<NaiveDate>,
52    generation: Option<String>,
53}
54
55impl RunDayLog {
56    pub fn open(live_path: &Path, limits: Limits) -> io::Result<Self> {
57        Self::open_with_clock(live_path, limits, Arc::new(|| Local::now().date_naive()))
58    }
59
60    /// Supplies date selection without changing callers' serialized timestamps.
61    pub fn open_with_clock(
62        live_path: &Path,
63        limits: Limits,
64        clock: Arc<dyn Fn() -> NaiveDate + Send + Sync>,
65    ) -> io::Result<Self> {
66        files::prepare(live_path, limits.max_bytes)?;
67        let _guard = lock::acquire(live_path)?;
68        migration::once(live_path, limits);
69        retention::prune(live_path, limits.max_dates, None)?;
70        files::bound_existing(live_path, limits.max_bytes)?;
71        Ok(Self {
72            live: live_path.to_path_buf(),
73            limits,
74            clock,
75            active: None,
76            generation: None,
77        })
78    }
79
80    /// Appends one complete line, rejecting oversized input before any rollover.
81    /// A filesystem failure drops this write; it never enables unbounded appends.
82    pub fn append(&mut self, complete_line: &[u8]) -> io::Result<()> {
83        validate_line(complete_line, self.limits.max_bytes)?;
84        let _guard = lock::acquire(&self.live)?;
85        let date = (self.clock)();
86        let dated = retention::dated_path(&self.live, date);
87        files::regular(&dated)?;
88        retention::prune(&self.live, self.limits.max_dates, Some(date))?;
89        self.prepare_chunk(date, &dated, complete_line.len() as u64)?;
90        files::append(&dated, complete_line, self.limits.max_bytes)?;
91        files::append(&self.live, complete_line, self.limits.max_bytes)
92    }
93
94    pub fn live_path(&self) -> &Path {
95        &self.live
96    }
97
98    fn prepare_chunk(&mut self, date: NaiveDate, dated: &Path, bytes: u64) -> io::Result<()> {
99        let size = files::size(dated)?;
100        let rollover = exceeds_chunk(size, bytes, self.limits.max_bytes);
101        truncate_if_full(dated, rollover)?;
102        let current = generation(&self.live)?;
103        let state = ChunkState {
104            date,
105            generation: current,
106            sizes: (files::size(&self.live)?, files::size(dated)?),
107            rollover,
108        };
109        self.restore_if_changed(state, dated)
110    }
111
112    fn restore_if_changed(&mut self, state: ChunkState, dated: &Path) -> io::Result<()> {
113        if state.needs_restore(self.active, self.generation.as_deref()) {
114            self.restore(state.date, dated)?;
115        }
116        Ok(())
117    }
118
119    fn restore(&mut self, date: NaiveDate, dated: &Path) -> io::Result<()> {
120        let chunk = files::read_chunk(dated, self.limits.max_bytes)?;
121        let token = marker::reset(&self.live, || files::replace(&self.live, &chunk))?;
122        self.active = Some(date);
123        self.generation = Some(token);
124        Ok(())
125    }
126}
127
128struct ChunkState {
129    date: NaiveDate,
130    generation: Option<String>,
131    sizes: (u64, u64),
132    rollover: bool,
133}
134
135impl ChunkState {
136    fn needs_restore(&self, active: Option<NaiveDate>, generation: Option<&str>) -> bool {
137        active != Some(self.date)
138            || generation != self.generation.as_deref()
139            || self.rollover
140            || self.sizes.0 != self.sizes.1
141    }
142}
143
144fn exceeds_chunk(size: u64, bytes: u64, limit: u64) -> bool {
145    size > limit.saturating_sub(bytes)
146}
147
148fn truncate_if_full(path: &Path, full: bool) -> io::Result<()> {
149    if full {
150        files::truncate(path)?;
151    }
152    Ok(())
153}
154
155fn validate_line(line: &[u8], limit: u64) -> io::Result<()> {
156    if line.len() as u64 > limit
157        || !line.ends_with(b"\n")
158        || line[..line.len().saturating_sub(1)].contains(&b'\n')
159    {
160        return Err(io::Error::new(
161            io::ErrorKind::InvalidInput,
162            "log record must be one complete line within the byte limit",
163        ));
164    }
165    Ok(())
166}
167
168/// Clears managed history without unlinking live or allowing legacy reimport.
169/// Writers reopen the dated path on every append, so an open writer can resume.
170pub fn clear(live_path: &Path) -> io::Result<()> {
171    if !files::directory(live_path)?.exists() {
172        return Ok(());
173    }
174    let _guard = lock::acquire(live_path)?;
175    let dates = retention::dates(live_path)?;
176    marker::reset(live_path, || clear_files(live_path, dates)).map(drop)
177}
178
179fn clear_files(live_path: &Path, dates: Vec<(NaiveDate, PathBuf)>) -> io::Result<()> {
180    files::truncate(live_path)?;
181    for (_, path) in dates {
182        files::remove(&path)?;
183    }
184    Ok(())
185}
186
187#[cfg(test)]
188mod tests;