1use super::{
3 changes, error, journal, Engine, LinkReference, Rows, Snapshot, State, StateStructure,
4};
5use crate::{LinkError, ReplaceableTransitionLogStore, TransitionLogStore};
6
7fn 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 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}
50fn 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}
65pub 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 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 pub fn export_checkpoint(&self) -> Result<Vec<String>, LinkError> {
119 let state = self.lock()?;
120 Ok(records(&state))
121 }
122 pub fn export_checkpoint_at(&self, revision: u64) -> Result<Vec<String>, LinkError> {
125 retained_records(&*self.lock()?, revision)
126 }
127 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 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 pub fn compact_journal(&self) -> Result<bool, LinkError> {
233 self.compact_journal_when(|_| true)
234 }
235 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}