crdt-data-types 0.1.2

High-performance CRDT library with dual pathways: JSON-native for web APIs and Cap'n Proto zero-copy for binary transport
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use crate::orset_capnp;
use crate::traits::{Crdt, CrdtError, CrdtReader};
use crate::vector_clock::VectorClock;
use capnp::message::{Builder, HeapAllocator, ReaderOptions};
use capnp::serialize;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::hash::Hash;

use serde::de::DeserializeOwned;

/// OR-Set: An Observed-Remove Set CRDT.
///
/// An OR-Set (Observed-Remove Set) allows both addition and removal of elements.
/// It resolves conflicts by preferring additions over removals in the case of
/// concurrent operations (Add-Wins semantics).
///
/// # Key Properties
///
/// - **Add-Wins**: If an element is concurrently added and removed, the addition wins.
/// - **Unique Tags**: Each addition is tagged with a unique identifier (from the vector clock).
/// - **Removal**: Removing an element removes all currently observed tags for that element.
///
/// # Algebraic Properties
///
/// - **Commutativity**: Yes.
/// - **Associativity**: Yes.
/// - **Idempotence**: Yes.
///
/// # Example
///
/// ```
/// use crdt_data_types::ORSet;
///
/// let mut set = ORSet::new();
/// set.insert("node_a", "apple".to_string());
/// set.remove(&"apple".to_string());
/// set.insert("node_b", "apple".to_string()); // Concurrent add
///
/// assert!(set.contains(&"apple".to_string()));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(
    serialize = "T: Serialize",
    deserialize = "T: DeserializeOwned + Eq + Hash + Ord"
))]
pub struct ORSet<T: Eq + Hash + Ord> {
    /// List of (element, set of observations) pairs, sorted by element.
    #[serde(serialize_with = "serialize_elements", deserialize_with = "deserialize_elements")]
    pub elements: Vec<(T, HashSet<(String, u64)>)>,
    /// Vector clock representing the causal history of the set.
    pub vclock: VectorClock,
}

fn serialize_elements<S, T>(
    elements: &Vec<(T, HashSet<(String, u64)>)>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
    T: Serialize,
{
    use serde::ser::SerializeMap;
    let mut map = serializer.serialize_map(Some(elements.len()))?;
    for (k, v) in elements {
        map.serialize_entry(k, v)?;
    }
    map.end()
}

type ORSetEntry<T> = (T, HashSet<(String, u64)>);

fn deserialize_elements<'de, D, T>(deserializer: D) -> Result<Vec<ORSetEntry<T>>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: DeserializeOwned + Eq + Hash + Ord,
{
    struct ElementsVisitor<T>(std::marker::PhantomData<T>);

    impl<'de, T> serde::de::Visitor<'de> for ElementsVisitor<T>
    where
        T: DeserializeOwned + Eq + Hash + Ord,
    {
        type Value = Vec<ORSetEntry<T>>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a map of elements to observations")
        }

        fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
        where
            M: serde::de::MapAccess<'de>,
        {
            let mut elements: Vec<ORSetEntry<T>> = Vec::with_capacity(access.size_hint().unwrap_or(0));
            while let Some((key, value)) = access.next_entry()? {
                elements.push((key, value));
            }
            // Sort to maintain invariant
            elements.sort_by(|a, b| a.0.cmp(&b.0));
            Ok(elements)
        }
    }

    deserializer.deserialize_map(ElementsVisitor(std::marker::PhantomData))
}

impl<T: Eq + Hash + Ord> Default for ORSet<T> {
    fn default() -> Self {
        Self {
            elements: Vec::new(),
            vclock: VectorClock::new(),
        }
    }
}

impl<T: Eq + Hash + Ord> ORSet<T> {
    /// Creates a new, empty OR-Set.
    pub fn new() -> Self {
        Self::default()
    }
}

impl<T> ORSet<T>
where
    T: Clone + Eq + Hash + Ord + Serialize + DeserializeOwned + Default + Send + Sync + 'static,
{
    /// Adds an element to the set.
    ///
    /// # Arguments
    /// * `node_id` - The identifier of the node performing the addition.
    /// * `element` - The element to add.
    pub fn insert(&mut self, node_id: &str, element: T) {
        self.vclock.increment(node_id);
        let id = self.vclock.clocks.get(node_id).copied().unwrap_or((0, 0));
        
        match self.elements.binary_search_by(|(e, _)| e.cmp(&element)) {
            Ok(idx) => {
                self.elements[idx].1.insert((node_id.to_string(), id.0));
            }
            Err(idx) => {
                let mut obs = HashSet::new();
                obs.insert((node_id.to_string(), id.0));
                self.elements.insert(idx, (element, obs));
            }
        }
    }

    /// Removes an element from the set by clearing its observations.
    ///
    /// # Arguments
    /// * `element` - The element to remove.
    pub fn remove(&mut self, element: &T) {
        if let Ok(idx) = self.elements.binary_search_by(|(e, _)| e.cmp(element)) {
            self.elements.remove(idx);
        }
    }

    /// Returns true if the set contains the specified element.
    pub fn contains(&self, element: &T) -> bool {
        self.elements.binary_search_by(|(e, _)| e.cmp(element)).is_ok()
    }

    /// Returns the number of elements in the set.
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Returns true if the set is empty.
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Iterator over the elements currently in the set.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.elements.iter().map(|(e, _)| e)
    }

    /// Merges another OR-Set into this one.
    ///
    /// For each element, the merged set contains the union of the observed IDs,
    /// but only those that are not causally overshadowed by a removal.
    pub fn merge(&mut self, other: &Self) {
        let mut new_elements = Vec::with_capacity(self.elements.len() + other.elements.len());
        let mut i = 0;
        let mut j = 0;

        while i < self.elements.len() && j < other.elements.len() {
            let (k1, v1) = &self.elements[i];
            let (k2, v2) = &other.elements[j];

            match k1.cmp(k2) {
                std::cmp::Ordering::Less => {
                    // Element only in self. Check if it was removed in other.
                    let mut kept_ids = HashSet::new();
                    for id in v1 {
                        let other_version = other.vclock.clocks.get(&id.0).map(|(c, _)| *c).unwrap_or(0);
                        // Keep the ID if the other replica hasn't observed this addition yet.
                        // If the other replica *has* observed this addition (id.1 <= other_version)
                        // but the element is missing from `other`, it implies `other` has removed it.
                        if id.1 > other_version {
                            kept_ids.insert(id.clone());
                        }
                    }
                    if !kept_ids.is_empty() {
                        new_elements.push((k1.clone(), kept_ids));
                    }
                    i += 1;
                }
                std::cmp::Ordering::Greater => {
                    // Element only in other. Check if it was removed in self.
                    let mut kept_ids = HashSet::new();
                    for id in v2 {
                        let self_version = self.vclock.clocks.get(&id.0).map(|(c, _)| *c).unwrap_or(0);
                        if id.1 > self_version {
                            kept_ids.insert(id.clone());
                        }
                    }
                    if !kept_ids.is_empty() {
                        new_elements.push((k2.clone(), kept_ids));
                    }
                    j += 1;
                }
                std::cmp::Ordering::Equal => {
                    // Element in both. Merge observations.
                    let mut merged_ids = HashSet::new();
                    
                    // Process IDs from self
                    for id in v1 {
                        let other_version = other.vclock.clocks.get(&id.0).map(|(c, _)| *c).unwrap_or(0);
                        if id.1 > other_version || v2.contains(id) {
                            merged_ids.insert(id.clone());
                        }
                    }
                    
                    // Process IDs from other
                    for id in v2 {
                        let self_version = self.vclock.clocks.get(&id.0).map(|(c, _)| *c).unwrap_or(0);
                        if id.1 > self_version || v1.contains(id) {
                            merged_ids.insert(id.clone());
                        }
                    }
                    
                    if !merged_ids.is_empty() {
                        new_elements.push((k1.clone(), merged_ids));
                    }
                    i += 1;
                    j += 1;
                }
            }
        }

        // Process remaining elements in self
        while i < self.elements.len() {
            let (k1, v1) = &self.elements[i];
            let mut kept_ids = HashSet::new();
            for id in v1 {
                let other_version = other.vclock.clocks.get(&id.0).map(|(c, _)| *c).unwrap_or(0);
                if id.1 > other_version {
                    kept_ids.insert(id.clone());
                }
            }
            if !kept_ids.is_empty() {
                new_elements.push((k1.clone(), kept_ids));
            }
            i += 1;
        }

        // Process remaining elements in other
        while j < other.elements.len() {
            let (k2, v2) = &other.elements[j];
            let mut kept_ids = HashSet::new();
            for id in v2 {
                let self_version = self.vclock.clocks.get(&id.0).map(|(c, _)| *c).unwrap_or(0);
                if id.1 > self_version {
                    kept_ids.insert(id.clone());
                }
            }
            if !kept_ids.is_empty() {
                new_elements.push((k2.clone(), kept_ids));
            }
            j += 1;
        }

        self.elements = new_elements;
        self.vclock.merge(&other.vclock);
    }
}

// ============================================================================
// Zero-Copy Reader
// ============================================================================

pub struct ORSetReader<'a, T> {
    bytes: &'a [u8],
    _phantom: std::marker::PhantomData<T>,
}

impl<'a, T> ORSetReader<'a, T> {
    pub fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<'a, T> CrdtReader<'a> for ORSetReader<'a, T>
where
    T: DeserializeOwned + Eq + Hash + Ord + Send + Sync,
{
    fn is_empty(&self) -> Result<bool, CrdtError> {
        let reader = serialize::read_message(self.bytes, ReaderOptions::new())
            .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
        let orset = reader
            .get_root::<orset_capnp::or_set::Reader>()
            .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
        let elements = orset
            .get_elements()
            .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
        Ok(elements.len() == 0)
    }
}

// ============================================================================
// CRDT Trait Implementation
// ============================================================================

impl<T> Crdt for ORSet<T>
where
    T: Clone + Eq + Hash + Ord + Serialize + DeserializeOwned + Default + Send + Sync + 'static,
{
    type Reader<'a> = ORSetReader<'a, T>;

    fn merge_from_readers(readers: &[Self::Reader<'_>]) -> Result<Self, CrdtError> {
        let mut result = ORSet::new();
        for reader in readers {
            let msg_reader = serialize::read_message(reader.bytes, ReaderOptions::new())
                .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
            let orset_reader = msg_reader
                .get_root::<orset_capnp::or_set::Reader>()
                .map_err(|e| CrdtError::Deserialization(e.to_string()))?;

            // Deserialize to temp ORSet
            let mut temp_set = ORSet::new();
            
            // VClock
            if orset_reader.has_vclock() {
                let vc_bytes = orset_reader
                    .get_vclock()
                    .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
                temp_set.vclock = VectorClock::merge_from_readers(&[crate::vector_clock::VectorClockReader::new(vc_bytes)])?;
            }

            // Elements
            let elements_reader = orset_reader
                .get_elements()
                .map_err(|e| CrdtError::Deserialization(e.to_string()))?;

            for element_entry in elements_reader {
                let element_bytes = element_entry
                    .get_element()
                    .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
                let element: T = serde_json::from_slice(element_bytes)
                    .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
                
                let mut obs = HashSet::new();
                let ids = element_entry
                    .get_ids()
                    .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
                
                for id_entry in ids {
                    let node_id = id_entry
                        .get_node_id()
                        .map_err(|e| CrdtError::Deserialization(e.to_string()))?
                        .to_string()
                        .map_err(|e| CrdtError::Deserialization(e.to_string()))?;
                    let counter = id_entry.get_counter();
                    obs.insert((node_id, counter));
                }
                temp_set.elements.push((element, obs));
            }
            // Ensure sorted invariant
            temp_set.elements.sort_by(|a, b| a.0.cmp(&b.0));

            result.merge(&temp_set);
        }
        Ok(result)
    }

    fn to_capnp_bytes(&self) -> Vec<u8> {
        let mut message = Builder::new(HeapAllocator::new());
        {
            let mut orset = message.init_root::<orset_capnp::or_set::Builder>();
            let mut elements = orset.reborrow().init_elements(self.elements.len() as u32);
            
            for (i, (element, obs)) in self.elements.iter().enumerate() {
                let mut element_entry = elements.reborrow().get(i as u32);
                let element_bytes = serde_json::to_vec(element).expect("Failed to serialize element");
                element_entry.set_element(&element_bytes);
                
                let mut ids = element_entry.init_ids(obs.len() as u32);
                for (j, (node_id, counter)) in obs.iter().enumerate() {
                    let mut id_entry = ids.reborrow().get(j as u32);
                    id_entry.set_node_id(node_id.as_str().into());
                    id_entry.set_counter(*counter);
                }
            }
            
            let vclock_bytes = self.vclock.to_capnp_bytes();
            orset.set_vclock(&vclock_bytes);
        }
        let mut buf = Vec::new();
        serialize::write_message(&mut buf, &message).expect("ORSet serialization fail");
        buf
    }

    fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    fn validate(&self) -> Result<(), CrdtError> {
        Ok(())
    }
}