1use super::{error, journal::checksum, MemoryLog};
4use crate::{LinkError, ReplaceableTransitionLogStore, TransitionLogStore};
5
6#[derive(PartialEq, Eq)]
7enum Kind {
8 Snapshot,
9 Changes,
10 Checkpoint,
11}
12struct Frame {
13 kind: Kind,
14 revision: u64,
15 next: String,
16 rows: String,
17 hash: String,
18}
19fn decimal(text: &str, max: u128) -> Result<u128, LinkError> {
20 if text.is_empty()
21 || text.len() > 39
22 || (text.len() > 1 && text.starts_with('0'))
23 || !text.bytes().all(|byte| byte.is_ascii_digit())
24 {
25 return Err(error("invalid delta journal decimal"));
26 }
27 text.parse::<u128>()
28 .ok()
29 .filter(|value| *value <= max)
30 .ok_or_else(|| error("delta journal decimal out of range"))
31}
32fn checked(text: &str) -> String {
33 format!("{text}|{:016x}", checksum(text))
34}
35fn verified(entry: &str) -> Result<Vec<&str>, LinkError> {
36 if !entry.bytes().all(|byte| (0x20..=0x7e).contains(&byte)) {
37 return Err(error("delta journal requires printable ASCII records"));
38 }
39 let (text, hash) = entry
40 .rsplit_once('|')
41 .ok_or_else(|| error("missing delta journal checksum"))?;
42 if hash.len() != 16 || hash != format!("{:016x}", checksum(text)) {
43 return Err(error("delta journal checksum mismatch"));
44 }
45 Ok(entry.split('|').collect())
46}
47fn frame(entry: &str) -> Result<Frame, LinkError> {
48 let fields = verified(entry)?;
49 let kind = match (fields[0], fields.len()) {
50 ("engine1", 5) => Kind::Snapshot,
51 ("engine2", 6) => Kind::Changes,
52 ("engine3", 5) => Kind::Checkpoint,
53 _ => return Err(error("expected an engine revision")),
54 };
55 let offset = usize::from(kind == Kind::Changes);
56 let revision = decimal(fields[1], u128::from(u64::MAX))? as u64;
57 let next = decimal(fields[2 + offset], u128::MAX)?;
58 if next == 0 || (revision == 0 && kind != Kind::Checkpoint) {
59 return Err(error("invalid delta journal revision or allocator"));
60 }
61 if revision == 0 && (next != 1 || !fields[3].is_empty()) {
62 return Err(error("invalid revision-zero checkpoint"));
63 }
64 if kind == Kind::Changes
65 && decimal(fields[2], u128::from(u64::MAX))? != u128::from(revision - 1)
66 {
67 return Err(error("invalid logical change base"));
68 }
69 Ok(Frame {
70 kind,
71 revision,
72 next: fields[2 + offset].into(),
73 rows: fields[3 + offset].into(),
74 hash: fields[4 + offset].into(),
75 })
76}
77fn contiguous(before: Option<&Frame>, after: &Frame) -> Result<(), LinkError> {
78 if after.kind == Kind::Checkpoint {
79 return if before.is_none() {
80 Ok(())
81 } else {
82 Err(error("checkpoint must be the first delta journal record"))
83 };
84 }
85 let expected = match before {
86 Some(before) => before.revision.checked_add(1),
87 None => Some(1),
88 };
89 if expected != Some(after.revision) {
90 return Err(error("delta journal revisions are not contiguous"));
91 }
92 Ok(())
93}
94fn expand(before: Option<&Frame>, entry: &str) -> Result<String, LinkError> {
95 if !entry.starts_with("delta1|") {
96 return Ok(entry.into());
97 }
98 let fields = verified(entry)?;
99 if fields.len() != 9 {
100 return Err(error("invalid delta journal envelope"));
101 }
102 let before = before.ok_or_else(|| error("delta journal base is missing"))?;
103 if before.kind == Kind::Changes {
104 return Err(error("delta requires a complete snapshot base"));
105 }
106 if fields[1] != before.hash {
107 return Err(error("delta journal base checksum mismatch"));
108 }
109 let prefix = decimal(fields[4], u128::from(u32::MAX))? as usize;
110 let suffix = decimal(fields[5], u128::from(u32::MAX))? as usize;
111 if prefix > before.rows.len() || suffix > before.rows.len() - prefix {
112 return Err(error("delta journal span outside base"));
113 }
114 Ok(format!(
115 "engine1|{}|{}|{}{}{}|{}",
116 fields[2],
117 fields[3],
118 &before.rows[..prefix],
119 fields[6],
120 &before.rows[before.rows.len() - suffix..],
121 fields[7]
122 ))
123}
124fn compress(a: &Frame, b: &Frame, full: &str) -> String {
125 let prefix = a
126 .rows
127 .bytes()
128 .zip(b.rows.bytes())
129 .take(u32::MAX as usize)
130 .take_while(|(x, y)| x == y)
131 .count();
132 let suffix = a.rows.as_bytes()[prefix..]
133 .iter()
134 .rev()
135 .zip(b.rows.as_bytes()[prefix..].iter().rev())
136 .take(u32::MAX as usize)
137 .take_while(|(x, y)| x == y)
138 .count();
139 let delta = checked(&format!(
140 "delta1|{}|{}|{}|{prefix}|{suffix}|{}|{}",
141 a.hash,
142 b.revision,
143 b.next,
144 &b.rows[prefix..b.rows.len() - suffix],
145 b.hash
146 ));
147 if delta.len() < full.len() {
148 delta
149 } else {
150 full.into()
151 }
152}
153
154pub struct DeltaLog<L> {
158 inner: L,
159 codec: Codec,
160}
161struct Codec {
164 interval: u32,
165 previous: Option<Frame>,
166 streak: u64,
167 ready: bool,
168 poisoned: bool,
169}
170impl<L: TransitionLogStore> DeltaLog<L> {
171 pub fn new(inner: L, checkpoint_interval: u32) -> Result<Self, LinkError> {
172 Ok(Self {
173 inner,
174 codec: Codec::new(checkpoint_interval)?,
175 })
176 }
177 pub fn into_inner(self) -> L {
178 self.inner
179 }
180}
181impl Codec {
182 fn new(checkpoint_interval: u32) -> Result<Self, LinkError> {
183 if checkpoint_interval == 0 {
184 return Err(error("checkpoint interval must be positive"));
185 }
186 Ok(Self {
187 interval: checkpoint_interval,
188 previous: None,
189 streak: 0,
190 ready: false,
191 poisoned: false,
192 })
193 }
194 fn check(&self) -> Result<(), LinkError> {
195 if self.poisoned {
196 Err(error(
197 "indeterminate delta journal outcome; reopen the decorator",
198 ))
199 } else {
200 Ok(())
201 }
202 }
203 fn read(&mut self, inner: &mut dyn TransitionLogStore) -> Result<Vec<String>, LinkError> {
204 self.check()?;
205 self.ready = false;
206 let mut logical = Vec::<String>::new();
207 let mut previous = None;
208 let mut streak = 0_u64;
209 for entry in inner.read_log_entries()? {
210 let full = expand(previous.as_ref(), &entry)?;
211 let parsed = frame(&full)?;
212 contiguous(previous.as_ref(), &parsed)?;
213 previous = Some(parsed);
214 streak = if entry.starts_with("delta1|") {
215 streak + 1
216 } else {
217 0
218 };
219 logical.push(full);
220 }
221 self.previous = previous;
222 self.streak = streak;
223 self.ready = true;
224 Ok(logical)
225 }
226 fn append(&mut self, inner: &mut dyn TransitionLogStore, entry: &str) -> Result<(), LinkError> {
227 self.check()?;
228 if !self.ready {
229 self.read(inner)?;
230 }
231 let parsed = frame(entry)?;
232 contiguous(self.previous.as_ref(), &parsed)?;
233 let physical = match &self.previous {
234 Some(before)
235 if before.kind != Kind::Changes
236 && parsed.kind != Kind::Changes
237 && self.streak + 1 < u64::from(self.interval) =>
238 {
239 compress(before, &parsed, entry)
240 }
241 _ => entry.into(),
242 };
243 if let Err(cause) = inner.append_log_entry(&physical) {
244 self.poisoned = true;
245 return Err(cause);
246 }
247 self.streak = if physical.starts_with("delta1|") {
248 self.streak + 1
249 } else {
250 0
251 };
252 self.previous = Some(parsed);
253 Ok(())
254 }
255 fn flush(&mut self, inner: &mut dyn TransitionLogStore) -> Result<(), LinkError> {
256 self.check()?;
257 if let Err(cause) = inner.flush_log() {
258 self.poisoned = true;
259 return Err(cause);
260 }
261 Ok(())
262 }
263}
264impl<L: TransitionLogStore> TransitionLogStore for DeltaLog<L> {
265 fn supports_durable_flush(&self) -> bool {
266 self.inner.supports_durable_flush()
267 }
268 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
269 self.codec.read(&mut self.inner)
270 }
271 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
272 self.codec.append(&mut self.inner, entry)
273 }
274 fn flush_log(&mut self) -> Result<(), LinkError> {
275 self.codec.flush(&mut self.inner)
276 }
277}
278
279impl<L: ReplaceableTransitionLogStore> ReplaceableTransitionLogStore for DeltaLog<L> {
280 fn supports_replacement(&self) -> bool {
281 self.inner.supports_replacement()
282 }
283 fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError> {
284 self.codec.check()?;
285 if !self.supports_replacement() {
286 return Err(error("selected log does not support journal replacement"));
287 }
288 let mut prepared = Codec::new(self.codec.interval)?;
290 let mut memory = MemoryLog::default();
291 prepared.read(&mut memory)?;
292 for entry in entries {
293 prepared.append(&mut memory, entry)?;
294 }
295 match self.inner.replace_log_entries(&memory.entries) {
296 Ok(changed) => {
297 self.codec = prepared;
298 Ok(changed)
299 }
300 Err(cause) => {
301 self.codec.poisoned = true;
302 Err(cause)
303 }
304 }
305 }
306}