Skip to main content

link_cli/engine/
journal.rs

1//! Portable full-revision journal. The checksum detects accidental corruption;
2//! it is not authentication. FileTransitionLog handles newline framing/torn tails.
3use super::{changes, error, Row, Rows, Snapshot, StateStructure};
4use crate::{GenericLink, LinkError, TransitionLogStore};
5use doublets::data::LinkReference;
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9#[derive(Default, Debug, Clone)]
10pub struct MemoryLog {
11    pub entries: Vec<String>,
12}
13impl TransitionLogStore for MemoryLog {
14    fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
15        self.entries.push(entry.into());
16        Ok(())
17    }
18    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
19        Ok(self.entries.clone())
20    }
21    fn flush_log(&mut self) -> Result<(), LinkError> {
22        Ok(())
23    }
24}
25pub(super) fn checksum(text: &str) -> u64 {
26    text.bytes().fold(0xcbf29ce484222325, |hash, byte| {
27        (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3)
28    })
29}
30pub(super) fn hex(bytes: &[u8]) -> String {
31    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
32}
33pub(super) fn unhex(text: &str) -> Result<String, LinkError> {
34    if !text.len().is_multiple_of(2) || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
35        return Err(error("invalid journal name encoding"));
36    }
37    let bytes = (0..text.len())
38        .step_by(2)
39        .map(|i| {
40            u8::from_str_radix(&text[i..i + 2], 16)
41                .map_err(|_| error("invalid journal name encoding"))
42        })
43        .collect::<Result<Vec<_>, _>>()?;
44    String::from_utf8(bytes).map_err(|_| error("invalid UTF-8 in journal name"))
45}
46pub(super) fn encode<T: LinkReference>(snapshot: &Snapshot<T>, next: u128) -> String {
47    encode_format(snapshot, next, "engine1")
48}
49pub(super) fn encode_format<T: LinkReference>(
50    snapshot: &Snapshot<T>,
51    next: u128,
52    format: &str,
53) -> String {
54    let payload = snapshot
55        .rows
56        .values()
57        .map(|row| {
58            format!(
59                "{},{},{},{}",
60                row.link.index,
61                row.link.source,
62                row.link.target,
63                row.name
64                    .as_ref()
65                    .map_or_else(|| "-".into(), |name| hex(name.as_bytes()))
66            )
67        })
68        .collect::<Vec<_>>()
69        .join(";");
70    let text = format!("{format}|{}|{next}|{payload}", snapshot.revision);
71    format!("{text}|{:016x}", checksum(&text))
72}
73pub(super) fn address<T: LinkReference>(text: &str) -> Result<T, LinkError> {
74    if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
75        return Err(error("invalid journal address"));
76    }
77    let value = text
78        .parse::<u128>()
79        .map_err(|_| error("invalid journal address"))?;
80    T::try_from(value).map_err(|_| LinkError::AddressOutOfRange(value))
81}
82
83pub(super) fn checked_text(entry: &str) -> Result<&str, LinkError> {
84    let (text, hash) = entry
85        .rsplit_once('|')
86        .ok_or_else(|| error("missing journal checksum"))?;
87    // Only the exact lowercase form the encoder writes: a parser that accepted
88    // `B` for `b` would let a flip of the case bit pass unnoticed.
89    if hash != format!("{:016x}", checksum(text)) {
90        return Err(error("journal checksum mismatch"));
91    }
92    Ok(text)
93}
94
95/// Replays either format against its exact predecessor. Merge-base exports use
96/// standalone decode instead, so a dependent record cannot masquerade as a base.
97pub(super) fn decode_after<T: LinkReference>(
98    entry: &str,
99    previous: &Snapshot<T>,
100    previous_next: u128,
101    structure: StateStructure,
102) -> Result<(Snapshot<T>, u128), LinkError> {
103    let (mut snapshot, next) = if entry.starts_with("engine2|") {
104        changes::decode(entry, previous)?
105    } else {
106        decode(entry)?
107    };
108    if snapshot.revision
109        != previous
110            .revision
111            .checked_add(1)
112            .ok_or_else(|| error("revision overflow"))?
113    {
114        return Err(error("journal revisions are not contiguous"));
115    }
116    if next < previous_next {
117        return Err(error("journal allocator moved backwards"));
118    }
119    snapshot.rows =
120        Arc::new(Arc::unwrap_or_clone(snapshot.rows).adapt(structure, Some(&previous.rows)));
121    Ok((snapshot, next))
122}
123
124pub(super) fn decode<T: LinkReference>(entry: &str) -> Result<(Snapshot<T>, u128), LinkError> {
125    decode_format(entry, "engine1")
126}
127pub(super) fn decode_checkpoint<T: LinkReference>(
128    entry: &str,
129    structure: StateStructure,
130) -> Result<(Snapshot<T>, u128), LinkError> {
131    let (mut snapshot, next) = decode_format(entry, "engine3")?;
132    if snapshot.revision == 0 && next != 1 {
133        return Err(error("invalid initial checkpoint"));
134    }
135    snapshot.rows = Arc::new(Arc::unwrap_or_clone(snapshot.rows).adapt(structure, None));
136    Ok((snapshot, next))
137}
138fn decode_format<T: LinkReference>(
139    entry: &str,
140    format: &str,
141) -> Result<(Snapshot<T>, u128), LinkError> {
142    let text = checked_text(entry)?;
143    let parts = text.split('|').collect::<Vec<_>>();
144    if parts.len() != 4 || parts[0] != format {
145        return Err(error("unsupported journal format"));
146    }
147    if parts[1..=2]
148        .iter()
149        .any(|part| part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()))
150    {
151        return Err(error("invalid journal revision or allocator"));
152    }
153    let revision = parts[1]
154        .parse::<u64>()
155        .map_err(|_| error("invalid journal revision"))?;
156    let next = parts[2]
157        .parse::<u128>()
158        .map_err(|_| error("invalid journal allocator"))?;
159    if next == 0 {
160        return Err(error("invalid journal allocator"));
161    }
162    let mut rows = BTreeMap::new();
163    if !parts[3].is_empty() {
164        for text in parts[3].split(';') {
165            let fields = text.split(',').collect::<Vec<_>>();
166            if fields.len() != 4 {
167                return Err(error("invalid journal row"));
168            }
169            let id = address::<T>(fields[0])?;
170            let value: u128 = id
171                .try_into()
172                .map_err(|_| error("address conversion failed"))?;
173            if value == 0 || value >= next {
174                return Err(error("journal address outside allocator range"));
175            }
176            let row = Row {
177                link: GenericLink::new(id, address::<T>(fields[1])?, address::<T>(fields[2])?),
178                name: if fields[3] == "-" {
179                    None
180                } else {
181                    Some(unhex(fields[3])?)
182                },
183            };
184            if rows.insert(id, row).is_some() {
185                return Err(error("duplicate journal address"));
186            }
187        }
188    }
189    Ok((
190        Snapshot {
191            revision,
192            rows: Arc::new(Rows::Flat(rows)),
193        },
194        next,
195    ))
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    #[test]
202    fn portable_wire_vectors() {
203        let vectors: serde_json::Value = serde_json::from_str(include_str!(
204            "../../../docs/protocol/engine-revision-vectors.json"
205        ))
206        .unwrap();
207        for value in vectors["valid"].as_array().unwrap() {
208            let text = value.as_str().unwrap();
209            let (snapshot, next) = decode::<u32>(text).unwrap();
210            assert_eq!(encode(&snapshot, next), text);
211        }
212        for value in vectors["invalidU32"].as_array().unwrap() {
213            let text = value.as_str().unwrap();
214            assert!(decode::<u32>(text).is_err(), "accepted {text}");
215        }
216    }
217}