Skip to main content

link_cli/engine/
timed_log.rs

1//! An optional log decorator that remembers when each revision was written, so
2//! that a restore can name a time. See `docs/ENGINE-BACKUP.md`.
3use super::error;
4use crate::{LinkError, ReplaceableTransitionLogStore, TransitionLogStore};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7fn system_clock() -> u64 {
8    SystemTime::now()
9        .duration_since(UNIX_EPOCH)
10        .map_or(0, |elapsed| elapsed.as_millis() as u64)
11}
12
13fn revision_of(record: &str) -> Result<u64, LinkError> {
14    record
15        .strip_prefix("engine")
16        .and_then(|rest| rest.split('|').nth(1))
17        .and_then(|revision| revision.parse().ok())
18        .ok_or_else(|| error("cannot timestamp a record without a revision"))
19}
20
21/// What is still true of a timeline: `(revision, written)` oldest first. A revision
22/// written again after a crash lost it replaces what the lost one and its
23/// successors claimed.
24fn surviving<M: TransitionLogStore>(timeline: &mut M) -> Result<Vec<(u64, u64)>, LinkError> {
25    let mut entries: Vec<(u64, u64)> = Vec::new();
26    for entry in timeline.read_log_entries()? {
27        let parsed = entry
28            .split_once('|')
29            .and_then(|(revision, written)| Some((revision.parse().ok()?, written.parse().ok()?)))
30            .ok_or_else(|| error("malformed timeline record"))?;
31        while entries.last().is_some_and(|last| last.0 >= parsed.0) {
32            entries.pop();
33        }
34        entries.push(parsed);
35    }
36    Ok(entries)
37}
38
39/// Keeps `revision|unix milliseconds` in a second log for every record appended to
40/// `inner`. Records and their format are unchanged, so an engine or a backup never
41/// needs to know this decorator exists, and the cost is one more append and flush.
42///
43/// The record is written and flushed first, so a crash can lose a timestamp but
44/// never leave one for a record that is not there. A commit without a timestamp
45/// makes a restore pick an earlier revision. Time never runs backwards in a
46/// timeline: a clock that steps back repeats the latest time instead.
47pub struct TimedLog<L, M> {
48    inner: L,
49    timeline: M,
50    clock: Box<dyn FnMut() -> u64 + Send>,
51    latest: u64,
52}
53
54impl<L: TransitionLogStore, M: TransitionLogStore> TimedLog<L, M> {
55    /// Timestamps from the system clock.
56    pub fn new(inner: L, timeline: M) -> Result<Self, LinkError> {
57        Self::with_clock(inner, timeline, system_clock)
58    }
59
60    /// Timestamps from `clock`, in the milliseconds `revision_at` will be asked for.
61    pub fn with_clock(
62        inner: L,
63        mut timeline: M,
64        clock: impl FnMut() -> u64 + Send + 'static,
65    ) -> Result<Self, LinkError> {
66        let latest = surviving(&mut timeline)?.last().map_or(0, |entry| entry.1);
67        Ok(Self {
68            inner,
69            timeline,
70            clock: Box::new(clock),
71            latest,
72        })
73    }
74}
75
76impl<L: TransitionLogStore, M: TransitionLogStore> TransitionLogStore for TimedLog<L, M> {
77    fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
78        let revision = revision_of(entry)?;
79        self.inner.append_log_entry(entry)?;
80        self.latest = self.latest.max((self.clock)());
81        self.timeline
82            .append_log_entry(&format!("{revision}|{}", self.latest))
83    }
84
85    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
86        self.inner.read_log_entries()
87    }
88
89    fn flush_log(&mut self) -> Result<(), LinkError> {
90        self.inner.flush_log()?;
91        self.timeline.flush_log()
92    }
93
94    fn supports_durable_flush(&self) -> bool {
95        self.inner.supports_durable_flush() && self.timeline.supports_durable_flush()
96    }
97}
98
99/// Compaction does not touch the timeline: its checkpoint repeats a revision the
100/// timeline already holds, and revisions it dropped are then refused by a restore.
101impl<L: ReplaceableTransitionLogStore, M: TransitionLogStore> ReplaceableTransitionLogStore
102    for TimedLog<L, M>
103{
104    fn supports_replacement(&self) -> bool {
105        self.inner.supports_replacement()
106    }
107
108    fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError> {
109        self.inner.replace_log_entries(entries)
110    }
111}
112
113/// The latest revision written by `time`, for `restore_backup`. Refuses a time
114/// before the first timestamp, because the state then is not known.
115pub fn revision_at<M: TransitionLogStore>(timeline: &mut M, time: u64) -> Result<u64, LinkError> {
116    surviving(timeline)?
117        .iter()
118        .rev()
119        .find(|entry| entry.1 <= time)
120        .map(|entry| entry.0)
121        .ok_or_else(|| error("no revision was written by that time"))
122}