crdt-data-types 0.1.3

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
use crate::lww_set_capnp;
use crate::traits::{Crdt, CrdtError, CrdtReader};
use crate::vector_clock::VectorClock;
use capnp::message::{Builder, HeapAllocator, ReaderOptions};
use capnp::serialize;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::cmp::Ordering;
use std::hash::Hash;

/// LWW-Set: A Last-Write-Wins Set CRDT.
///
/// An LWW-Set (Last-Write-Wins Set) stores elements where each element's
/// presence is determined by the latest timestamp associated with an add
/// or remove operation. It resolves conflicts between concurrent additions
/// and removals by choosing the operation with the highest timestamp.
///
/// # Key Properties
///
/// - **Add/Remove Sets**: Maintains separate sets for additions and removals, each with timestamps.
/// - **LWW Resolution**: An element is present if its addition timestamp is greater than its removal timestamp.
/// - **Bias**: Typically biased towards addition in case of timestamp ties (configurable, but usually Add-Wins).
///
/// # Algebraic Properties
///
/// - **Commutativity**: Yes.
/// - **Associativity**: Yes.
/// - **Idempotence**: Yes.
///
/// # Example
///
/// ```
/// use crdt_data_types::LWWSet;
///
/// let mut set = LWWSet::new();
/// set.insert("node_a", "apple".to_string(), 100);
/// set.remove("node_b", "apple".to_string(), 50); // Older removal
///
/// assert!(set.contains(&"apple".to_string())); // Addition wins (100 > 50)
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(
    serialize = "T: Serialize",
    deserialize = "T: DeserializeOwned + Eq + Hash + Ord"
))]
pub struct LWWSet<T: Eq + Hash + Ord> {
    /// Tracks addition timestamps: element -> (timestamp, node_id).
    #[serde(serialize_with = "serialize_lww_map", deserialize_with = "deserialize_lww_map")]
    pub add_set: Vec<(T, (u64, String))>,
    /// Tracks removal timestamps: element -> (timestamp, node_id).
    #[serde(serialize_with = "serialize_lww_map", deserialize_with = "deserialize_lww_map")]
    pub remove_set: Vec<(T, (u64, String))>,
    /// Vector clock representing the causal history of the set.
    pub vclock: VectorClock,
}

fn serialize_lww_map<S, T>(
    elements: &Vec<(T, (u64, String))>,
    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 LWWSetEntry<T> = (T, (u64, String));

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

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

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

        fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
        where
            M: serde::de::MapAccess<'de>,
        {
            let mut elements: Vec<LWWSetEntry<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(LWWMapVisitor(std::marker::PhantomData))
}

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

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

impl<T: Clone + Eq + Hash + Ord + Serialize + DeserializeOwned + Send + Sync + 'static> LWWSet<T> {
    /// Adds an element to the set with a specific timestamp.
    pub fn insert(&mut self, node_id: &str, element: T, timestamp: u64) {
        let node_id_str = node_id.to_string();
        match self.add_set.binary_search_by(|(e, _)| e.cmp(&element)) {
            Ok(idx) => {
                let (_, (ts, nid)) = &self.add_set[idx];
                if timestamp > *ts || (timestamp == *ts && node_id_str > *nid) {
                    self.add_set[idx] = (element, (timestamp, node_id_str));
                    self.vclock.increment(node_id);
                }
            }
            Err(idx) => {
                self.add_set.insert(idx, (element, (timestamp, node_id_str)));
                self.vclock.increment(node_id);
            }
        }
    }

    /// Removes an element from the set by adding a tombstone with a specific timestamp.
    pub fn remove(&mut self, node_id: &str, element: T, timestamp: u64) {
        let node_id_str = node_id.to_string();
        match self.remove_set.binary_search_by(|(e, _)| e.cmp(&element)) {
            Ok(idx) => {
                let (_, (ts, nid)) = &self.remove_set[idx];
                if timestamp > *ts || (timestamp == *ts && node_id_str > *nid) {
                    self.remove_set[idx] = (element, (timestamp, node_id_str));
                    self.vclock.increment(node_id);
                }
            }
            Err(idx) => {
                self.remove_set.insert(idx, (element, (timestamp, node_id_str)));
                self.vclock.increment(node_id);
            }
        }
    }

    /// Returns true if the set contains the specified element.
    ///
    /// An element is present if its latest add timestamp is strictly greater
    /// than its latest remove timestamp (or if no removal exists).
    pub fn contains(&self, element: &T) -> bool {
        let add_entry = self
            .add_set
            .binary_search_by(|(e, _)| e.cmp(element))
            .map(|idx| &self.add_set[idx].1)
            .ok();
        
        let remove_entry = self
            .remove_set
            .binary_search_by(|(e, _)| e.cmp(element))
            .map(|idx| &self.remove_set[idx].1)
            .ok();

        match (add_entry, remove_entry) {
            (Some((a_ts, a_id)), Some((r_ts, r_id))) => {
                *a_ts > *r_ts || (*a_ts == *r_ts && a_id > r_id)
            }
            (Some(_), None) => true,
            _ => false,
        }
    }

    /// Iterator over the elements currently in the set.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.add_set.iter().filter_map(move |(e, _)| {
            if self.contains(e) {
                Some(e)
            } else {
                None
            }
        })
    }

    /// Merges another LWW-Set into this one.
    pub fn merge(&mut self, other: &Self) {
        self.add_set = Self::merge_vecs(&self.add_set, &other.add_set);
        self.remove_set = Self::merge_vecs(&self.remove_set, &other.remove_set);
        self.vclock.merge(&other.vclock);
    }

    fn merge_vecs(
        left: &[(T, (u64, String))],
        right: &[(T, (u64, String))],
    ) -> Vec<(T, (u64, String))> {
        let mut result = Vec::with_capacity(left.len() + right.len());
        let mut i = 0;
        let mut j = 0;

        while i < left.len() && j < right.len() {
            let (k1, (ts1, id1)) = &left[i];
            let (k2, (ts2, id2)) = &right[j];

            match k1.cmp(k2) {
                Ordering::Less => {
                    result.push((k1.clone(), (*ts1, id1.clone())));
                    i += 1;
                }
                Ordering::Greater => {
                    result.push((k2.clone(), (*ts2, id2.clone())));
                    j += 1;
                }
                Ordering::Equal => {
                    // Both have the element, keep the one with higher timestamp/id
                    if *ts1 > *ts2 || (*ts1 == *ts2 && id1 > id2) {
                        result.push((k1.clone(), (*ts1, id1.clone())));
                    } else {
                        result.push((k2.clone(), (*ts2, id2.clone())));
                    }
                    i += 1;
                    j += 1;
                }
            }
        }

        while i < left.len() {
            result.push(left[i].clone());
            i += 1;
        }
        while j < right.len() {
            result.push(right[j].clone());
            j += 1;
        }

        result
    }
}

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

pub struct LWWSetReader<'a, T: Eq + Hash + Ord> {
    bytes: &'a [u8],
    _phantom: std::marker::PhantomData<T>,
}

impl<'a, T: Clone + Eq + Hash + Ord + Serialize + DeserializeOwned + Send + Sync + 'static>
    LWWSetReader<'a, T>
{
    pub fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            _phantom: std::marker::PhantomData,
        }
    }

    fn to_set(&self) -> Result<LWWSet<T>, CrdtError> {
        let reader = serialize::read_message(self.bytes, ReaderOptions::new())
            .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
        let lww_set = reader
            .get_root::<lww_set_capnp::lww_set::Reader>()
            .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;

        let mut add_set = Vec::new();
        let adds = lww_set
            .get_add_set()
            .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
        for entry in adds {
            let entry: lww_set_capnp::lww_set::entry::Reader = entry;
            let element: T = bincode::deserialize(
                entry
                    .get_element()
                    .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?,
            )
            .map_err(|e: bincode::Error| CrdtError::Deserialization(e.to_string()))?;
            add_set.push((
                element,
                (
                    entry.get_timestamp(),
                    entry
                        .get_node_id()
                        .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?
                        .to_string()
                        .map_err(|e: std::str::Utf8Error| {
                            CrdtError::Deserialization(e.to_string())
                        })?,
                ),
            ));
        }
        // Sort to maintain invariant
        add_set.sort_by(|a, b| a.0.cmp(&b.0));

        let mut remove_set = Vec::new();
        let removes = lww_set
            .get_remove_set()
            .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
        for entry in removes {
            let entry: lww_set_capnp::lww_set::entry::Reader = entry;
            let element: T = bincode::deserialize(
                entry
                    .get_element()
                    .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?,
            )
            .map_err(|e: bincode::Error| CrdtError::Deserialization(e.to_string()))?;
            remove_set.push((
                element,
                (
                    entry.get_timestamp(),
                    entry
                        .get_node_id()
                        .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?
                        .to_string()
                        .map_err(|e: std::str::Utf8Error| {
                            CrdtError::Deserialization(e.to_string())
                        })?,
                ),
            ));
        }
        // Sort to maintain invariant
        remove_set.sort_by(|a, b| a.0.cmp(&b.0));

        let vclock = if lww_set.has_vclock() {
            let vc_bytes = lww_set
                .get_vclock()
                .map_err(|e: capnp::Error| CrdtError::Deserialization(e.to_string()))?;
            VectorClock::merge_from_readers(&[crate::vector_clock::VectorClockReader::new(
                vc_bytes,
            )])?
        } else {
            VectorClock::new()
        };

        Ok(LWWSet {
            add_set,
            remove_set,
            vclock,
        })
    }
}

impl<'a, T> CrdtReader<'a> for LWWSetReader<'a, T>
where
    T: Clone + Eq + Hash + Ord + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    fn is_empty(&self) -> Result<bool, CrdtError> {
        Ok(self.to_set()?.add_set.is_empty())
    }
}

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

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

    fn merge_from_readers(readers: &[Self::Reader<'_>]) -> Result<Self, CrdtError> {
        let mut result = LWWSet::new();
        for reader in readers {
            result.merge(&reader.to_set()?);
        }
        Ok(result)
    }

    fn to_capnp_bytes(&self) -> Vec<u8> {
        let mut message = Builder::new(HeapAllocator::new());
        {
            let mut lww_set = message.init_root::<lww_set_capnp::lww_set::Builder>();

            let mut adds = lww_set.reborrow().init_add_set(self.add_set.len() as u32);
            for (idx, (element, (timestamp, node_id))) in self.add_set.iter().enumerate() {
                let mut entry = adds.reborrow().get(idx as u32);
                let bytes = bincode::serialize(element).expect("LWWSet element serialization fail");
                entry.set_element(&bytes);
                entry.set_timestamp(*timestamp);
                entry.set_node_id(node_id.as_str().into());
            }

            let mut removes = lww_set
                .reborrow()
                .init_remove_set(self.remove_set.len() as u32);
            for (idx, (element, (timestamp, node_id))) in self.remove_set.iter().enumerate() {
                let mut entry = removes.reborrow().get(idx as u32);
                let bytes = bincode::serialize(element).expect("LWWSet element serialization fail");
                entry.set_element(&bytes);
                entry.set_timestamp(*timestamp);
                entry.set_node_id(node_id.as_str().into());
            }

            let vclock_bytes = self.vclock.to_capnp_bytes();
            lww_set.set_vclock(&vclock_bytes);
        }
        let mut buf = Vec::new();
        serialize::write_message(&mut buf, &message).expect("LWWSet serialization fail");
        buf
    }

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

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