Skip to main content

logicaffeine_data/crdt/
ormap.rs

1//! OR-Map (Observed-Remove Map) CRDT.
2//!
3//! A key-value map where values are nested CRDTs.
4//! Keys use add-wins semantics, values are merged recursively.
5
6use super::causal::{Dot, DotContext, VClock};
7use super::delta::DeltaCrdt;
8use super::latest::LatestWrite;
9use super::replica::{generate_replica_id, ReplicaId};
10use super::Merge;
11use serde::de::DeserializeOwned;
12use serde::{Deserialize, Serialize};
13use std::collections::{HashMap, HashSet};
14use std::hash::Hash;
15
16/// Delta for ORMap synchronization.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[serde(
19    bound = "K: Serialize + serde::de::DeserializeOwned + Hash + Eq, V: Serialize + serde::de::DeserializeOwned"
20)]
21pub struct ORMapDelta<K, V> {
22    pub keys: HashMap<K, HashSet<Dot>>,
23    pub values: HashMap<K, V>,
24    pub context: DotContext,
25}
26
27/// An observed-remove map with nested CRDT values.
28///
29/// Keys are managed with OR-Set add-wins semantics.
30/// Values are merged using their CRDT merge function.
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(
33    bound = "K: Serialize + serde::de::DeserializeOwned + Hash + Eq, V: Serialize + serde::de::DeserializeOwned + Merge + Default + Clone"
34)]
35pub struct ORMap<K, V: Merge + Default + Clone> {
36    /// Map of active keys to their dots
37    keys: HashMap<K, HashSet<Dot>>,
38    /// Map of all values (including for removed keys, for resurrection)
39    values: HashMap<K, V>,
40    /// Tracks seen dots
41    context: DotContext,
42    /// This replica's ID
43    replica_id: ReplicaId,
44}
45
46impl<K: Hash + Eq + Clone, V: Merge + Default + Clone> ORMap<K, V> {
47    /// Create a new map with a specific replica ID.
48    pub fn new(replica_id: ReplicaId) -> Self {
49        Self {
50            keys: HashMap::new(),
51            values: HashMap::new(),
52            context: DotContext::new(),
53            replica_id,
54        }
55    }
56
57    /// Create a new map with a random replica ID.
58    pub fn new_random() -> Self {
59        Self::new(generate_replica_id())
60    }
61
62    /// Get a reference to a value if the key exists.
63    pub fn get(&self, key: &K) -> Option<&V> {
64        if self.contains_key(key) {
65            self.values.get(key)
66        } else {
67            None
68        }
69    }
70
71    /// Get a mutable reference to a value, creating the key if necessary.
72    /// Always creates a new dot to ensure add-wins semantics.
73    pub fn get_or_insert(&mut self, key: K) -> &mut V {
74        // Always create a new dot for add-wins semantics
75        let dot = self.context.next(self.replica_id);
76        self.keys.entry(key.clone()).or_default().insert(dot);
77
78        // Ensure value exists
79        self.values.entry(key).or_default()
80    }
81
82    /// Get a mutable reference to a value without creating a new dot.
83    /// Use this for read-heavy access patterns where add-wins isn't needed.
84    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
85        if self.contains_key(key) {
86            self.values.get_mut(key)
87        } else {
88            None
89        }
90    }
91
92    /// Check if a key exists in the map.
93    pub fn contains_key(&self, key: &K) -> bool {
94        self.keys.get(key).map_or(false, |dots| !dots.is_empty())
95    }
96
97    /// Remove a key from the map.
98    pub fn remove(&mut self, key: &K) {
99        self.keys.remove(key);
100    }
101
102    /// Get the number of keys.
103    pub fn len(&self) -> usize {
104        self.keys.values().filter(|dots| !dots.is_empty()).count()
105    }
106
107    /// Check if the map is empty.
108    pub fn is_empty(&self) -> bool {
109        self.len() == 0
110    }
111
112    /// Iterate over active keys.
113    pub fn keys(&self) -> impl Iterator<Item = &K> {
114        self.keys
115            .iter()
116            .filter(|(_, dots)| !dots.is_empty())
117            .map(|(k, _)| k)
118    }
119
120    /// Iterate over key-value pairs.
121    pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
122        self.keys
123            .iter()
124            .filter(|(_, dots)| !dots.is_empty())
125            .filter_map(|(k, _)| self.values.get(k).map(|v| (k, v)))
126    }
127}
128
129impl<K: Hash + Eq + Clone + Ord, V: Merge + Default + Clone> ORMap<K, V> {
130    /// The present entries sorted by key. A merged map has no global insertion order, so this is the
131    /// order every replica holding the same state renders and iterates in.
132    pub fn sorted_entries(&self) -> Vec<(&K, &V)> {
133        let mut entries: Vec<(&K, &V)> = self.iter().collect();
134        entries.sort_by(|a, b| a.0.cmp(b.0));
135        entries
136    }
137}
138
139/// A map to plain values: each value is a [`LatestWrite`] stamped with this map's Lamport time (the
140/// events its causal context has observed), so a write that has seen another beats it on every replica.
141impl<K: Hash + Eq + Clone, T: Ord + Clone + Default> ORMap<K, LatestWrite<T>> {
142    /// `Set m[key] to value`.
143    pub fn put(&mut self, key: K, value: T) {
144        self.get_or_insert(key.clone());
145        let stamp = self.context.observed();
146        self.values
147            .get_mut(&key)
148            .expect("get_or_insert created the entry")
149            .write(value, stamp);
150    }
151
152    /// The value under `key`, if the key is present.
153    pub fn value(&self, key: &K) -> Option<&T> {
154        self.get(key).map(LatestWrite::get)
155    }
156}
157
158impl<K: Hash + Eq + Clone, V: Merge + Default + Clone> Merge for ORMap<K, V> {
159    fn merge(&mut self, other: &Self) {
160        // First, merge all values (regardless of key presence)
161        // This ensures nested CRDTs are properly merged
162        for (key, other_value) in &other.values {
163            let my_value = self.values.entry(key.clone()).or_default();
164            my_value.merge(other_value);
165        }
166
167        // Merge keys with OR-Set add-wins semantics
168        for (key, other_dots) in &other.keys {
169            let my_dots = self.keys.entry(key.clone()).or_default();
170
171            // Keep dots from other that we haven't seen
172            for &dot in other_dots {
173                if !self.context.has_seen(&dot) {
174                    my_dots.insert(dot);
175                }
176            }
177        }
178
179        // Handle removals: if we have a key that other doesn't, check if they saw our dots
180        let my_keys: Vec<_> = self.keys.keys().cloned().collect();
181        for key in my_keys {
182            if !other.keys.contains_key(&key) {
183                // Other doesn't have this key
184                if let Some(my_dots) = self.keys.get_mut(&key) {
185                    // Only keep dots that other hasn't seen
186                    my_dots.retain(|dot| !other.context.has_seen(dot));
187                }
188            } else {
189                // Both have the key
190                let other_dots = other.keys.get(&key).unwrap();
191                if let Some(my_dots) = self.keys.get_mut(&key) {
192                    // Keep dots that other hasn't seen OR that other still has
193                    my_dots.retain(|dot| !other.context.has_seen(dot) || other_dots.contains(dot));
194                }
195            }
196        }
197
198        // Merge contexts
199        self.context.merge(&other.context);
200
201        // Clean up empty key entries
202        self.keys.retain(|_, dots| !dots.is_empty());
203    }
204}
205
206impl<
207        K: Hash + Eq + Clone + Serialize + DeserializeOwned + Send + 'static,
208        V: Merge + Default + Clone + Serialize + DeserializeOwned + Send + 'static,
209    > DeltaCrdt for ORMap<K, V>
210{
211    type Delta = ORMapDelta<K, V>;
212
213    fn delta_since(&self, since: &VClock) -> Option<Self::Delta> {
214        let current = self.version();
215        if since.dominates(&current) {
216            return None;
217        }
218
219        Some(ORMapDelta {
220            keys: self.keys.clone(),
221            values: self.values.clone(),
222            context: self.context.clone(),
223        })
224    }
225
226    fn apply_delta(&mut self, delta: &Self::Delta) {
227        // Merge values
228        for (key, other_value) in &delta.values {
229            let my_value = self.values.entry(key.clone()).or_default();
230            my_value.merge(other_value);
231        }
232
233        // Merge keys
234        for (key, other_dots) in &delta.keys {
235            let my_dots = self.keys.entry(key.clone()).or_default();
236            for &dot in other_dots {
237                if !self.context.has_seen(&dot) {
238                    my_dots.insert(dot);
239                }
240            }
241        }
242
243        // Merge context
244        self.context.merge(&delta.context);
245
246        // Clean up empty entries
247        self.keys.retain(|_, dots| !dots.is_empty());
248    }
249
250    fn version(&self) -> VClock {
251        self.context.version()
252    }
253}
254
255impl<K: Hash + Eq + Clone, V: Merge + Default + Clone> Default for ORMap<K, V> {
256    fn default() -> Self {
257        Self::new_random()
258    }
259}
260
261/// Owned iteration over a map to plain values visits `(key, value)` pairs by key.
262impl<K: Hash + Eq + Clone + Ord, T: Ord + Clone + Default> IntoIterator
263    for ORMap<K, LatestWrite<T>>
264{
265    type Item = (K, T);
266    type IntoIter = std::vec::IntoIter<(K, T)>;
267
268    fn into_iter(self) -> Self::IntoIter {
269        self.sorted_entries()
270            .into_iter()
271            .map(|(k, v)| (k.clone(), v.get().clone()))
272            .collect::<Vec<_>>()
273            .into_iter()
274    }
275}
276
277/// Two maps are equal when they hold the same convergent state (keys with their dots, values, and
278/// causal context) — the same rule as `ORSet`; the replica id is identity, not state.
279impl<K: Hash + Eq, V: Merge + Default + Clone + PartialEq> PartialEq for ORMap<K, V> {
280    fn eq(&self, other: &Self) -> bool {
281        self.keys == other.keys && self.values == other.values && self.context == other.context
282    }
283}
284
285/// `m[key]` on a map to plain values: the value under a PRESENT key; a missing key traps with the
286/// same message the interpreter raises.
287impl<K: Hash + Eq + Clone + std::fmt::Display, T: Ord + Clone + Default> crate::LogosIndex<K>
288    for ORMap<K, LatestWrite<T>>
289{
290    type Output = T;
291
292    fn logos_get(&self, key: K) -> T {
293        match self.value(&key) {
294            Some(v) => v.clone(),
295            None => panic!("Key '{key}' not found in map"),
296        }
297    }
298}
299
300/// `Set m[key] to value` on a map to plain values.
301impl<K: Hash + Eq + Clone + std::fmt::Display, T: Ord + Clone + Default> crate::LogosIndexMut<K>
302    for ORMap<K, LatestWrite<T>>
303{
304    fn logos_set(&mut self, key: K, value: T) {
305        self.put(key, value);
306    }
307}
308
309/// `m contains key` — observed-remove key membership.
310impl<K: Hash + Eq + Clone, V: Merge + Default + Clone> crate::LogosContains<K> for ORMap<K, V> {
311    fn logos_contains(&self, key: &K) -> bool {
312        self.contains_key(key)
313    }
314}
315
316#[cfg(test)]
317#[path = "../../../logicaffeine_tests/unit/logicaffeine_data/crdt/ormap/tests.rs"]
318mod tests;