Skip to main content

link_cli/transactions/
undo_image.rs

1//! Mandatory v3 undo metadata shares the transition namespace so old readers fail.
2use std::collections::BTreeMap;
3
4use doublets::data::LinkReference;
5
6use super::record::{decode_name, encode_name};
7use crate::{GenericLink, LinkError};
8
9/// Undo source for the ordinary, immediately mutating storage adapter.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum RowUndoPolicy {
12    /// Record post-effect observations. A crash before observation is not atomic.
13    #[default]
14    Observed,
15    /// Flush a complete logical row/name image before an owner's first write.
16    /// Costs O(N log N) capture and O(N + name bytes) memory/journal per owner.
17    /// Each write also scans rows/names and reconciles pending record effects.
18    WriteAheadImage,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub(super) struct UndoImage<T> {
23    pub(super) owner: u128,
24    pub(super) base: i64,
25    pub(super) rows: Vec<GenericLink<T>>,
26    pub(super) names: Option<BTreeMap<T, String>>,
27}
28
29impl<T: LinkReference> UndoImage<T> {
30    pub(super) fn serialize(&self) -> String {
31        let rows = self
32            .rows
33            .iter()
34            .map(|row| format!("{},{},{}", row.index, row.source, row.target))
35            .collect::<Vec<_>>()
36            .join(";");
37        let names = self
38            .names
39            .as_ref()
40            .map(|names| {
41                names
42                    .iter()
43                    .map(|(index, name)| format!("{index},{}", encode_name(Some(name))))
44                    .collect::<Vec<_>>()
45                    .join(";")
46            })
47            .unwrap_or_else(|| "-".into());
48        format!("v3|undo|{:032x}|{}|{rows}|{names}", self.owner, self.base)
49    }
50
51    pub(super) fn parse(text: &str) -> Result<Self, LinkError> {
52        let invalid = || LinkError::InvalidFormat("invalid write-ahead undo image".into());
53        let parts = text.split('|').collect::<Vec<_>>();
54        if parts.len() != 6 || parts[0] != "v3" || parts[1] != "undo" {
55            return Err(invalid());
56        }
57        let owner = u128::from_str_radix(parts[2], 16).map_err(|_| invalid())?;
58        let base = parts[3].parse::<i64>().map_err(|_| invalid())?;
59        if owner == 0 || base < 0 {
60            return Err(invalid());
61        }
62        let address = |value: &str| {
63            let number = value.parse::<u128>().map_err(|_| invalid())?;
64            T::try_from(number).map_err(|_| LinkError::AddressOutOfRange(number))
65        };
66        let mut rows: Vec<GenericLink<T>> = Vec::new();
67        if !parts[4].is_empty() {
68            for value in parts[4].split(';') {
69                let fields = value.split(',').collect::<Vec<_>>();
70                if fields.len() != 3 {
71                    return Err(invalid());
72                }
73                let row = GenericLink::new(
74                    address(fields[0])?,
75                    address(fields[1])?,
76                    address(fields[2])?,
77                );
78                if row.index == T::from_byte(0)
79                    || rows.last().is_some_and(|last| last.index >= row.index)
80                {
81                    return Err(invalid());
82                }
83                rows.push(row);
84            }
85        }
86        let names = if parts[5] == "-" {
87            None
88        } else {
89            let mut names = BTreeMap::new();
90            if !parts[5].is_empty() {
91                for value in parts[5].split(';') {
92                    let (index, encoded) = value.split_once(',').ok_or_else(invalid)?;
93                    let index = address(index)?;
94                    let name = decode_name(encoded).flatten().ok_or_else(invalid)?;
95                    if names
96                        .last_key_value()
97                        .is_some_and(|(last, _)| *last >= index)
98                    {
99                        return Err(invalid());
100                    }
101                    names.insert(index, name);
102                }
103            }
104            Some(names)
105        };
106        let image = Self {
107            owner,
108            base,
109            rows,
110            names,
111        };
112        if image.serialize() != text {
113            return Err(invalid());
114        }
115        Ok(image)
116    }
117}