Skip to main content

link_cli/transactions/
record.rs

1//! Complete journal records. The original `Copy` row transition remains v1.
2use std::ops::Deref;
3
4use doublets::data::LinkReference;
5
6use super::{GenericDoubletLink, GenericTransition, TransitionKind};
7use crate::LinkError;
8
9/// Logical name state for one address, including names of absent rows.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct NameChange<T> {
12    pub index: T,
13    pub before: Option<String>,
14    pub after: Option<String>,
15}
16
17/// A row transition plus optional name state, or an independent name write.
18/// Use this complete value for recovery, archives and version movement.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct JournalRecord<T> {
21    pub transition: GenericTransition<T>,
22    pub name_only: bool,
23    pub names: Vec<NameChange<T>>,
24}
25
26impl<T> Deref for JournalRecord<T> {
27    type Target = GenericTransition<T>;
28    fn deref(&self) -> &Self::Target {
29        &self.transition
30    }
31}
32
33impl<T> From<GenericTransition<T>> for JournalRecord<T> {
34    fn from(transition: GenericTransition<T>) -> Self {
35        Self {
36            transition,
37            name_only: false,
38            names: Vec::new(),
39        }
40    }
41}
42
43impl<T: LinkReference> JournalRecord<T> {
44    /// Row-only records retain the exact existing v1 encoding. Complete v2
45    /// records append an explicit replay mode and sorted name changes. Names
46    /// are UTF-16 hex, `-` is absent, and empty hex is a present empty name.
47    pub fn serialize(&self) -> String {
48        let row = self.transition.serialize();
49        if !self.name_only && self.names.is_empty() {
50            return row;
51        }
52        let names = self
53            .names
54            .iter()
55            .map(|name| {
56                format!(
57                    "{},{},{}",
58                    name.index,
59                    encode_name(name.before.as_deref()),
60                    encode_name(name.after.as_deref())
61                )
62            })
63            .collect::<Vec<_>>()
64            .join(";");
65        format!(
66            "v2{}|{}|{}",
67            &row[2..],
68            if self.name_only { "n" } else { "r" },
69            names
70        )
71    }
72
73    pub fn parse(text: &str) -> Result<Self, LinkError> {
74        if !text.starts_with("v2|") {
75            return GenericTransition::parse(text).map(Into::into);
76        }
77        let invalid = || LinkError::InvalidFormat("malformed complete transaction record".into());
78        let parts: Vec<_> = text.split('|').collect();
79        if parts.len() != 9 {
80            return Err(invalid());
81        }
82        let transition = GenericTransition::parse(&format!("v1|{}", parts[1..7].join("|")))?;
83        // The complete cross-language codec uses .NET's representable time
84        // range. Preserve the original v1 parser's wider legacy contract.
85        if !(-62_135_596_800_000..=253_402_300_799_999).contains(&transition.timestamp_ms) {
86            return Err(invalid());
87        }
88        let name_only = match parts[7] {
89            "n" => true,
90            "r" => false,
91            _ => return Err(invalid()),
92        };
93        let mut names = Vec::new();
94        for change in parts[8].split(';') {
95            let fields: Vec<_> = change.split(',').collect();
96            if fields.len() != 3 {
97                return Err(invalid());
98            }
99            let value = fields[0].parse::<u128>().map_err(|_| invalid())?;
100            let index = T::try_from(value).map_err(|_| LinkError::AddressOutOfRange(value))?;
101            names.push(NameChange {
102                index,
103                before: decode_name(fields[1]).ok_or_else(invalid)?,
104                after: decode_name(fields[2]).ok_or_else(invalid)?,
105            });
106        }
107        let record = Self {
108            transition,
109            name_only,
110            names,
111        };
112        record.validate()?;
113        // New records use one canonical form; old row codecs remain lenient.
114        if record.serialize() != text {
115            return Err(invalid());
116        }
117        Ok(record)
118    }
119
120    pub(crate) fn validate(&self) -> Result<(), LinkError> {
121        let invalid =
122            || LinkError::InvalidFormat("invalid name state in transaction record".into());
123        if self
124            .names
125            .windows(2)
126            .any(|pair| pair[0].index >= pair[1].index)
127        {
128            return Err(invalid());
129        }
130        if self.name_only {
131            if self.names.is_empty()
132                || self.kind != TransitionKind::Update
133                || self.before != GenericDoubletLink::empty()
134                || self.after != GenericDoubletLink::empty()
135            {
136                return Err(invalid());
137            }
138        } else if !self.names.is_empty() {
139            let index = if self.after.index != T::from_byte(0) {
140                self.after.index
141            } else {
142                self.before.index
143            };
144            let zero = T::from_byte(0);
145            let shape = match self.kind {
146                TransitionKind::Create => {
147                    self.before == GenericDoubletLink::empty() && self.after.index != zero
148                }
149                TransitionKind::Update => {
150                    self.before.index != zero && self.before.index == self.after.index
151                }
152                TransitionKind::Delete => {
153                    self.before.index != zero && self.after == GenericDoubletLink::empty()
154                }
155            };
156            if !shape || self.names.len() != 1 || self.names[0].index != index || index == zero {
157                return Err(invalid());
158            }
159        }
160        Ok(())
161    }
162}
163
164pub(super) fn encode_name(name: Option<&str>) -> String {
165    name.map(|name| {
166        name.encode_utf16()
167            .map(|unit| format!("{unit:04X}"))
168            .collect()
169    })
170    .unwrap_or_else(|| "-".into())
171}
172
173pub(super) fn decode_name(text: &str) -> Option<Option<String>> {
174    if text == "-" {
175        return Some(None);
176    }
177    if !text.len().is_multiple_of(4) || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
178        return None;
179    }
180    let units = text
181        .as_bytes()
182        .as_chunks::<4>()
183        .0
184        .iter()
185        .map(|chunk| u16::from_str_radix(std::str::from_utf8(chunk).ok()?, 16).ok())
186        .collect::<Option<Vec<_>>>()?;
187    String::from_utf16(&units).ok().map(Some)
188}