atomr_distributed_data/traits.rs
1/// Convergent replicated data type merge semantics.
2///
3/// Implementations form a join-semilattice: `merge` must be commutative,
4/// associative, and idempotent.
5///
6/// **Sealed** as part of Phase 13 (idiomatic-rust sweep): only the
7/// CRDTs in this crate may implement `CrdtMerge` directly. Downstream
8/// users compose CRDTs via `ORMap<K, V>` / `LWWMap<K, V>` (where the
9/// value is a CRDT) or wrap them in domain-specific structs.
10pub trait CrdtMerge: Clone + private::Sealed {
11 fn merge(&mut self, other: &Self);
12}
13
14/// Optional delta-CRDT layer: emit a small "delta" describing the
15/// last local change and merge incoming deltas into the full state.
16///
17/// Phase 8.C of `docs/full-port-plan.md`. CRDTs that implement
18/// [`DeltaCrdt`] participate in delta-gossip — the Replicator ships
19/// `Self::Delta` to peers instead of the full state, dramatically
20/// reducing wire traffic for hot keys.
21///
22/// CRDTs whose state is small (counters, flags) can implement this
23/// trivially with `Delta = Self`. Sets / maps emit a sub-state
24/// containing only the keys / tags that changed.
25pub trait DeltaCrdt: CrdtMerge {
26 /// Per-CRDT delta type — typically `Self` for small CRDTs, a
27 /// sub-state for set / map shapes.
28 type Delta: Clone + Send + 'static;
29
30 /// Take and clear the accumulated local delta. Returns `None` if
31 /// no local change has happened since the last call.
32 fn take_delta(&mut self) -> Option<Self::Delta>;
33
34 /// Merge an incoming delta into local state.
35 fn merge_delta(&mut self, delta: &Self::Delta);
36}
37
38mod private {
39 pub trait Sealed {}
40
41 impl Sealed for crate::counters::GCounter {}
42 impl Sealed for crate::counters::PNCounter {}
43 impl Sealed for crate::flag::Flag {}
44 impl<T: Eq + std::hash::Hash + Clone> Sealed for crate::sets::GSet<T> {}
45 impl<T: Eq + std::hash::Hash + Clone> Sealed for crate::sets::OrSet<T> {}
46 impl<T: Clone> Sealed for crate::register::LwwRegister<T> {}
47 impl<K, V> Sealed for crate::maps::ORMap<K, V>
48 where
49 K: Eq + std::hash::Hash + Clone,
50 V: super::CrdtMerge,
51 {
52 }
53 impl<K, V> Sealed for crate::maps::LWWMap<K, V>
54 where
55 K: Eq + std::hash::Hash + Clone,
56 V: Clone,
57 {
58 }
59 impl<K> Sealed for crate::maps::PNCounterMap<K> where K: Eq + std::hash::Hash + Clone {}
60 impl<K, V> Sealed for crate::maps::ORMultiMap<K, V>
61 where
62 K: Eq + std::hash::Hash + Clone,
63 V: Eq + std::hash::Hash + Clone,
64 {
65 }
66}