Skip to main content

link_cli/engine/
checkpoint.rs

1//! Checkpoint construction and optional publication share the commit mutex.
2use super::{
3    changes, error, journal, Engine, LinkReference, Rows, Snapshot, State, StateStructure,
4};
5use crate::{LinkError, ReplaceableTransitionLogStore, TransitionLogStore};
6
7/// The records of one retained revision, for a copy that ends at that revision.
8fn retained_records<T: LinkReference, L>(
9    state: &State<T, L>,
10    revision: u64,
11) -> Result<Vec<String>, LinkError> {
12    if revision != state.current.revision && !state.history.contains_key(&revision) {
13        return Err(error("revision is not retained"));
14    }
15    Ok(records_through(state, revision))
16}
17fn records<T: LinkReference, L>(state: &State<T, L>) -> Vec<String> {
18    records_through(state, state.current.revision)
19}
20fn records_through<T: LinkReference, L>(state: &State<T, L>, revision: u64) -> Vec<String> {
21    let snapshots: Vec<_> = if state.history.is_empty() {
22        vec![(&state.current, state.committed_next)]
23    } else {
24        state
25            .history
26            .range(..=revision)
27            .map(|(_, (snapshot, next))| (snapshot, *next))
28            .collect()
29    };
30    snapshots
31        .into_iter()
32        .enumerate()
33        .map(|(index, (snapshot, next))| {
34            // Saved branch descriptors require exact committed metadata. Private
35            // reservations remain reserved in this owner but never enter the log.
36            journal::encode_format(
37                snapshot,
38                next,
39                if index == 0 { "engine3" } else { "engine1" },
40            )
41        })
42        .collect()
43}
44fn empty<T: LinkReference>(structure: StateStructure) -> Snapshot<T> {
45    Snapshot {
46        revision: 0,
47        rows: std::sync::Arc::new(Rows::new(structure)),
48    }
49}
50/// One record of a journal, after the state its predecessors left. Only a first
51/// record may be a checkpoint.
52fn replay_record<T: LinkReference>(
53    index: usize,
54    record: &str,
55    last: &Snapshot<T>,
56    last_next: u128,
57    structure: StateStructure,
58) -> Result<(Snapshot<T>, u128), LinkError> {
59    if index == 0 && record.starts_with("engine3|") {
60        journal::decode_checkpoint(record, structure)
61    } else {
62        journal::decode_after(record, last, last_next, structure)
63    }
64}
65/// Copy an archived journal to an empty log, stopping at one revision, and return
66/// the revision the copy ends at. `None` copies the whole archive. Opening the
67/// destination gives the engine as it was at that revision, on a new timeline.
68///
69/// Records are copied unchanged, so an incremental chain restores to any revision
70/// it holds, and so does a live journal. Records after the selected revision are
71/// not decoded, so a copy can end just before damage. Everything up to it is decoded
72/// before the first write, so a refused restore leaves the destination unchanged.
73/// After a later failure the destination may hold a shorter copy, so discard it.
74/// See `docs/ENGINE-BACKUP.md`.
75pub fn restore_backup<T: LinkReference, S: TransitionLogStore, D: TransitionLogStore>(
76    source: &mut S,
77    destination: &mut D,
78    revision: Option<u64>,
79) -> Result<u64, LinkError> {
80    if !destination.read_log_entries()?.is_empty() {
81        return Err(error("restore destination must be empty"));
82    }
83    let mut entries = source.read_log_entries()?;
84    let structure = StateStructure::Flat;
85    let (mut last, mut last_next) = (empty::<T>(structure), 1);
86    // A journal without a checkpoint starts from the empty revision 0.
87    let mut reached = revision == Some(0)
88        && !entries
89            .first()
90            .is_some_and(|record| record.starts_with("engine3|"));
91    let mut kept = 0;
92    for (index, record) in entries.iter().enumerate() {
93        if reached {
94            break;
95        }
96        (last, last_next) = replay_record(index, record, &last, last_next, structure)?;
97        kept = index + 1;
98        reached = Some(last.revision) == revision;
99    }
100    if revision.is_some() && !reached {
101        return Err(error("revision is not in the backup"));
102    }
103    entries.truncate(kept);
104    for entry in &entries {
105        destination.append_log_entry(entry)?;
106    }
107    destination.flush_log()?;
108    if destination.read_log_entries()? != entries {
109        return Err(error(
110            "restore verification failed: destination differs from the copied records",
111        ));
112    }
113    Ok(last.revision)
114}
115impl<T: LinkReference, L: TransitionLogStore> Engine<T, L> {
116    /// Export retained committed snapshots without rewriting the live log.
117    /// The caller owns atomic publication and synchronization of these records.
118    pub fn export_checkpoint(&self) -> Result<Vec<String>, LinkError> {
119        let state = self.lock()?;
120        Ok(records(&state))
121    }
122    /// Export the retained snapshots up to one retained revision, as a journal
123    /// whose reopened head is that revision.
124    pub fn export_checkpoint_at(&self, revision: u64) -> Result<Vec<String>, LinkError> {
125        retained_records(&*self.lock()?, revision)
126    }
127    /// Copy a consistent cut to an empty log while commits continue, and return
128    /// the revision it ends at. `None` selects the current revision; a retained
129    /// earlier revision gives a point-in-time copy.
130    ///
131    /// The commit mutex is held only while the cut is encoded, never during
132    /// destination I/O, so a slow or failing destination cannot delay or fence
133    /// this engine. After a failure the destination may hold a shorter copy, so
134    /// discard it. See `docs/ENGINE-BACKUP.md`.
135    pub fn backup_to<D: TransitionLogStore>(
136        &self,
137        destination: &mut D,
138        revision: Option<u64>,
139    ) -> Result<u64, LinkError> {
140        if !destination.read_log_entries()?.is_empty() {
141            return Err(error("backup destination must be empty"));
142        }
143        let (revision, entries) = {
144            let state = self.lock()?;
145            let revision = revision.unwrap_or(state.current.revision);
146            (revision, retained_records(&state, revision)?)
147        };
148        for entry in &entries {
149            destination.append_log_entry(entry)?;
150        }
151        destination.flush_log()?;
152        if destination.read_log_entries()? != entries {
153            return Err(error(
154                "backup verification failed: destination differs from the copied records",
155            ));
156        }
157        Ok(revision)
158    }
159    /// Bring an earlier backup of this engine up to the current revision by
160    /// appending only the revisions it lacks, each as the rows that changed, and
161    /// return the revision it now ends at. An empty destination gets a full copy.
162    ///
163    /// The destination's last revision must still be retained here and hold the
164    /// same rows, otherwise it is refused and left alone: take a full backup. The
165    /// commit mutex is held only to select the snapshots. After a failure the
166    /// destination may end at an earlier revision, and calling again continues
167    /// from there. See `docs/ENGINE-BACKUP.md`.
168    pub fn backup_incremental_to<D: TransitionLogStore>(
169        &self,
170        destination: &mut D,
171    ) -> Result<u64, LinkError> {
172        let existing = destination.read_log_entries()?;
173        if existing.is_empty() {
174            return self.backup_to(destination, None);
175        }
176        let structure = self.lock()?.options.state_structure;
177        let (mut last, mut last_next) = (empty::<T>(structure), 1);
178        for (index, record) in existing.iter().enumerate() {
179            (last, last_next) = replay_record(index, record, &last, last_next, structure)?;
180        }
181        let chain: Vec<(Snapshot<T>, u128)> = {
182            let state = self.lock()?;
183            if state.history.is_empty() {
184                (last.revision == state.current.revision)
185                    .then(|| (state.current.clone(), state.committed_next))
186                    .into_iter()
187                    .collect()
188            } else {
189                state
190                    .history
191                    .range(last.revision..)
192                    .map(|(_, entry)| entry.clone())
193                    .collect()
194            }
195        };
196        let Some((same, same_next)) = chain.first().filter(|(s, _)| s.revision == last.revision)
197        else {
198            return Err(error("revision is not retained"));
199        };
200        if same.rows != last.rows || *same_next != last_next {
201            return Err(error("backup destination is not a copy of this engine"));
202        }
203        let entries: Vec<String> = chain
204            .windows(2)
205            .map(|pair| {
206                let (previous, (snapshot, next)) = (&pair[0].0, &pair[1]);
207                let ids: Vec<T> = previous
208                    .rows
209                    .keys()
210                    .chain(snapshot.rows.keys())
211                    .copied()
212                    .collect();
213                changes::encode(snapshot, *next, previous, &ids)
214            })
215            .collect();
216        for entry in &entries {
217            destination.append_log_entry(entry)?;
218        }
219        destination.flush_log()?;
220        if destination.read_log_entries()? != [existing, entries].concat() {
221            return Err(error(
222                "backup verification failed: destination differs from the copied records",
223            ));
224        }
225        Ok(chain.last().map_or(last.revision, |(s, _)| s.revision))
226    }
227}
228impl<T: LinkReference, L: ReplaceableTransitionLogStore> Engine<T, L> {
229    /// Atomically replace the journal while holding the commit mutex. Identical
230    /// records return false. Any replacement error fences this owner until reopen.
231    /// Unsupported capability leaves the engine available for ordinary commits.
232    pub fn compact_journal(&self) -> Result<bool, LinkError> {
233        self.compact_journal_when(|_| true)
234    }
235    /// Compact once at least `commits` revisions have landed since the last
236    /// compaction by this owner, and otherwise do nothing and return false. A log
237    /// that cannot be replaced is refused either way, so a wrong selection shows at
238    /// once. The first call after opening counts from revision 0, which also
239    /// compacts a journal left long by an earlier owner. See
240    /// `docs/ENGINE-CHECKPOINTS.md`.
241    pub fn compact_journal_after(&self, commits: u64) -> Result<bool, LinkError> {
242        if commits == 0 {
243            return Err(error("compaction needs at least one commit"));
244        }
245        self.compact_journal_when(|landed| landed >= commits)
246    }
247    fn compact_journal_when(&self, due: impl FnOnce(u64) -> bool) -> Result<bool, LinkError> {
248        let mut state = self.lock()?;
249        if !state.log.supports_replacement() {
250            return Err(error("selected log does not support journal replacement"));
251        }
252        let revision = state.current.revision;
253        if !due(revision - state.compacted_revision) {
254            return Ok(false);
255        }
256        let entries = records(&state);
257        match state.log.replace_log_entries(&entries) {
258            Ok(changed) => {
259                state.compacted_revision = revision;
260                Ok(changed)
261            }
262            Err(cause) => {
263                state.poisoned = true;
264                Err(cause)
265            }
266        }
267    }
268}