Skip to main content

link_cli/engine/
causal_replica.rs

1//! Selected bounded local causal ownership; no global atomicity claim.
2use super::{
3    causal::{CausalDot, CausalPayload, CausalVersion},
4    cluster::{AtomicJournalStore, JournalVersion},
5};
6use crate::LinkError;
7use serde_json::{json, Value};
8use std::collections::BTreeMap;
9
10fn invalid() -> LinkError {
11    LinkError::InvalidFormat("invalid causal replica state".into())
12}
13fn identity(value: &str) -> Result<(), LinkError> {
14    if value.len() != 32
15        || value.bytes().all(|b| b == b'0')
16        || !value
17            .bytes()
18            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
19    {
20        return Err(invalid());
21    }
22    Ok(())
23}
24fn raw(value: &CausalVersion) -> Result<Value, LinkError> {
25    serde_json::from_str(&value.encode()?).map_err(|_| invalid())
26}
27fn parsed(value: &Value) -> Result<CausalVersion, LinkError> {
28    CausalVersion::decode(&value.to_string())
29}
30fn values(value: &Value) -> Result<Vec<CausalVersion>, LinkError> {
31    value
32        .as_array()
33        .filter(|v| v.len() <= 64)
34        .ok_or_else(invalid)?
35        .iter()
36        .map(parsed)
37        .collect()
38}
39fn compare(a: &CausalVersion, b: &CausalVersion) -> std::cmp::Ordering {
40    a.address.cmp(&b.address).then_with(|| a.dot.cmp(&b.dot))
41}
42fn evidence(values: &[CausalVersion]) -> Result<Vec<CausalVersion>, LinkError> {
43    CausalVersion::merge(values, &[])?;
44    let mut result = values.to_vec();
45    result.sort_by(compare);
46    result.dedup();
47    Ok(result)
48}
49fn descriptor(
50    address: u64,
51    context: &[CausalVersion],
52    payload: Option<CausalPayload>,
53) -> Result<String, LinkError> {
54    let dummy =
55        CausalVersion::advance(address, "00000000000000000000000000000001", 0, &[], payload)?;
56    Ok(json!([
57        address.to_string(),
58        context.iter().map(raw).collect::<Result<Vec<_>, _>>()?,
59        raw(&dummy)?[4]
60    ])
61    .to_string())
62}
63
64#[derive(Clone, Copy, Debug)]
65pub struct CausalReplicaOptions {
66    pub max_entries: usize,
67    pub max_bytes: usize,
68    pub require_durable_flush: bool,
69}
70impl Default for CausalReplicaOptions {
71    fn default() -> Self {
72        Self {
73            max_entries: 4096,
74            max_bytes: 8_388_608,
75            require_durable_flush: false,
76        }
77    }
78}
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub struct CausalSnapshot {
81    pub author: String,
82    pub last_counter: u64,
83    pub versions: Vec<CausalVersion>,
84}
85struct State {
86    author: String,
87    counter: u64,
88    history: BTreeMap<CausalDot, (String, CausalVersion)>,
89    rows: BTreeMap<u64, Vec<CausalVersion>>,
90    tokens: BTreeMap<String, (String, CausalVersion)>,
91}
92impl State {
93    fn new(author: &str) -> Self {
94        Self {
95            author: author.into(),
96            counter: 0,
97            history: BTreeMap::new(),
98            rows: BTreeMap::new(),
99            tokens: BTreeMap::new(),
100        }
101    }
102    fn remember(
103        &mut self,
104        items: &[CausalVersion],
105        local: bool,
106        update: bool,
107    ) -> Result<(), LinkError> {
108        let mut groups: BTreeMap<u64, Vec<CausalVersion>> = BTreeMap::new();
109        for value in items {
110            let wire = value.encode()?;
111            if let Some((prior, _)) = self.history.get(&value.dot) {
112                if prior != &wire {
113                    return Err(invalid());
114                }
115            } else if !local && value.dot.author == self.author {
116                return Err(invalid());
117            }
118            if value
119                .clock
120                .iter()
121                .any(|v| v.author == self.author && v.counter > self.counter)
122            {
123                return Err(invalid());
124            }
125            for (prior, previous) in self.history.values() {
126                if previous.address == value.address
127                    && previous.clock == value.clock
128                    && prior != &wire
129                {
130                    return Err(invalid());
131                }
132            }
133            self.history
134                .insert(value.dot.clone(), (wire, value.clone()));
135            groups.entry(value.address).or_default().push(value.clone());
136        }
137        if update {
138            for (address, group) in groups {
139                let merged = CausalVersion::merge(
140                    self.rows.get(&address).map_or(&[], Vec::as_slice),
141                    &group,
142                )?;
143                self.rows.insert(address, merged);
144            }
145        }
146        Ok(())
147    }
148    fn apply(&mut self, entry: &Value) -> Result<(), LinkError> {
149        let entry = entry.as_array().ok_or_else(invalid)?;
150        if entry.first() == Some(&json!("causal-receive1")) {
151            if entry.len() != 2 {
152                return Err(invalid());
153            }
154            let received = values(&entry[1])?;
155            if received.is_empty()
156                || received
157                    .windows(2)
158                    .any(|v| compare(&v[0], &v[1]) != std::cmp::Ordering::Less)
159            {
160                return Err(invalid());
161            }
162            return self.remember(&received, false, true);
163        }
164        if entry.len() != 4 || entry[0] != "causal-write1" {
165            return Err(invalid());
166        }
167        let token = entry[1].as_str().ok_or_else(invalid)?;
168        identity(token)?;
169        if self.tokens.contains_key(token) {
170            return Err(invalid());
171        }
172        let seen = evidence(&values(&entry[2])?)?;
173        if json!(seen.iter().map(raw).collect::<Result<Vec<_>, _>>()?) != entry[2] {
174            return Err(invalid());
175        }
176        let mutation = parsed(&entry[3])?;
177        let context = CausalVersion::merge(&seen, &[])?;
178        self.remember(&seen, false, false)?;
179        let expected = CausalVersion::advance(
180            mutation.address,
181            &self.author,
182            self.counter,
183            &context,
184            mutation.payload.clone(),
185        )?;
186        if expected != mutation {
187            return Err(invalid());
188        }
189        self.counter = mutation.dot.counter;
190        self.remember(std::slice::from_ref(&mutation), true, true)?;
191        self.tokens.insert(
192            token.into(),
193            (
194                descriptor(mutation.address, &context, mutation.payload.clone())?,
195                mutation,
196            ),
197        );
198        Ok(())
199    }
200    fn snapshot(&self) -> CausalSnapshot {
201        let mut versions: Vec<_> = self.rows.values().flatten().cloned().collect();
202        versions.sort_by(compare);
203        CausalSnapshot {
204            author: self.author.clone(),
205            last_counter: self.counter,
206            versions,
207        }
208    }
209}
210
211pub struct CausalReplica<S> {
212    store: S,
213    key: String,
214    author: String,
215    options: CausalReplicaOptions,
216}
217impl<S: AtomicJournalStore> CausalReplica<S> {
218    pub fn new(
219        store: S,
220        key: &str,
221        author: &str,
222        options: CausalReplicaOptions,
223    ) -> Result<Self, LinkError> {
224        identity(author)?;
225        if key.is_empty()
226            || key.len() > 128
227            || !key
228                .bytes()
229                .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
230            || !(2..=4096).contains(&options.max_entries)
231            || !(1..=8_388_608).contains(&options.max_bytes)
232            || (options.require_durable_flush && !store.supports_durable_flush())
233        {
234            return Err(invalid());
235        }
236        Ok(Self {
237            store,
238            key: key.into(),
239            author: author.into(),
240            options,
241        })
242    }
243    pub fn into_store(self) -> S {
244        self.store
245    }
246    fn admit(&self, entries: &[String]) -> Result<(), LinkError> {
247        if entries.len() > self.options.max_entries {
248            return Err(invalid());
249        }
250        let mut bytes: usize = 0;
251        for entry in entries {
252            bytes = bytes.checked_add(entry.len()).ok_or_else(invalid)?;
253            if entry.len() > 1_048_576 || bytes > self.options.max_bytes {
254                return Err(invalid());
255            }
256            let (mut depth, mut separators, mut quoted) = (0i32, 0usize, false);
257            // Canonical fields have no escapes; bound shape before JSON allocation.
258            for item in entry.bytes() {
259                if !(b' '..=b'~').contains(&item) || item == b'\\' {
260                    return Err(invalid());
261                }
262                if item == b'"' {
263                    quoted = !quoted;
264                    continue;
265                }
266                if quoted {
267                    continue;
268                }
269                match item {
270                    b'{' | b'}' => return Err(invalid()),
271                    b'[' => {
272                        depth += 1;
273                        if depth > 5 {
274                            return Err(invalid());
275                        }
276                    }
277                    b']' => {
278                        depth -= 1;
279                        if depth < 0 {
280                            return Err(invalid());
281                        }
282                    }
283                    b',' => {
284                        separators += 1;
285                        if separators > 32768 {
286                            return Err(invalid());
287                        }
288                    }
289                    _ => {}
290                }
291            }
292            if quoted || depth != 0 {
293                return Err(invalid());
294            }
295        }
296        Ok(())
297    }
298    fn load(&mut self) -> Result<(JournalVersion, State), LinkError> {
299        let mut result = self.store.read(std::slice::from_ref(&self.key))?;
300        if result.len() != 1 {
301            return Err(invalid());
302        }
303        let expected = result.remove(0);
304        self.admit(&expected.entries)?;
305        let mut state = State::new(&self.author);
306        if expected.generation == 0 {
307            if !expected.entries.is_empty() {
308                return Err(invalid());
309            }
310            return Ok((expected, state));
311        }
312        if expected.entries.first() != Some(&json!(["causal-replica1", self.author]).to_string()) {
313            return Err(invalid());
314        }
315        for entry in &expected.entries[1..] {
316            let value: Value = serde_json::from_str(entry).map_err(|_| invalid())?;
317            let canonical = value.to_string();
318            if canonical != *entry {
319                return Err(invalid());
320            }
321            state.apply(&value)?;
322        }
323        Ok((expected, state))
324    }
325    fn publish(&mut self, expected: JournalVersion, entry: Value) -> Result<(), LinkError> {
326        let mut entries = expected.entries.clone();
327        if entries.is_empty() {
328            entries.push(json!(["causal-replica1", self.author]).to_string());
329        }
330        entries.push(entry.to_string());
331        self.admit(&entries)?;
332        match self.store.compare_exchange(std::slice::from_ref(&self.key), &[expected], &[Some(entries)]) {
333            Ok(true) => Ok(()),
334            Ok(false) => Err(LinkError::Transaction("conflict: causal state changed; reread and retry the same token".into())),
335            Err(cause) => Err(LinkError::Transaction(format!("indeterminate causal publication; retry the same token after a fresh read: {cause}"))),
336        }
337    }
338    pub fn snapshot(&mut self) -> Result<CausalSnapshot, LinkError> {
339        Ok(self.load()?.1.snapshot())
340    }
341    pub fn read(&mut self, address: u64) -> Result<Vec<CausalVersion>, LinkError> {
342        if address == 0 {
343            return Err(invalid());
344        }
345        Ok(self.load()?.1.rows.remove(&address).unwrap_or_default())
346    }
347    pub fn write(
348        &mut self,
349        token: &str,
350        address: u64,
351        context: &[CausalVersion],
352        payload: Option<CausalPayload>,
353    ) -> Result<CausalVersion, LinkError> {
354        identity(token)?;
355        let admitted = evidence(context)?;
356        let context = CausalVersion::merge(&admitted, &[])?;
357        let input = descriptor(address, &context, payload.clone())?;
358        let (expected, mut state) = self.load()?;
359        state.remember(&admitted, false, false)?;
360        if let Some((prior, value)) = state.tokens.get(token) {
361            if *prior != input {
362                return Err(invalid());
363            }
364            return Ok(value.clone());
365        }
366        let mutation =
367            CausalVersion::advance(address, &self.author, state.counter, &context, payload)?;
368        let entry = json!([
369            "causal-write1",
370            token,
371            admitted.iter().map(raw).collect::<Result<Vec<_>, _>>()?,
372            raw(&mutation)?
373        ]);
374        state.apply(&entry)?;
375        self.publish(expected, entry)?;
376        Ok(mutation)
377    }
378    pub fn receive(&mut self, incoming: &[CausalVersion]) -> Result<bool, LinkError> {
379        if incoming.len() > 64 {
380            return Err(invalid());
381        }
382        for value in incoming {
383            value.encode()?;
384        }
385        let (expected, mut state) = self.load()?;
386        let mut new_values = BTreeMap::new();
387        for value in incoming {
388            if !state.history.contains_key(&value.dot) {
389                new_values.insert(value.dot.clone(), value.clone());
390            }
391        }
392        state.remember(incoming, false, true)?;
393        if new_values.is_empty() {
394            return Ok(false);
395        }
396        let mut new_values: Vec<_> = new_values.into_values().collect();
397        new_values.sort_by(compare);
398        self.publish(
399            expected,
400            json!([
401                "causal-receive1",
402                new_values.iter().map(raw).collect::<Result<Vec<_>, _>>()?
403            ]),
404        )?;
405        Ok(true)
406    }
407}