mdcs-db 0.1.2

Database layer for the Carnelia MDCS - Document API with collaborative features
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! RGA List - Replicated Growable Array for ordered sequences.
//!
//! RGA provides a CRDT list that supports:
//! - Insert at any position
//! - Delete at any position
//! - Move elements (delete + insert)
//!
//! Uses unique IDs to maintain consistent ordering across replicas.

use mdcs_core::lattice::Lattice;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use ulid::Ulid;

/// Unique identifier for a list element.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ListId {
    /// The replica that created this element.
    pub replica: String,
    /// Sequence number within that replica.
    pub seq: u64,
    /// Unique identifier for disambiguation.
    pub ulid: Ulid,
}

impl ListId {
    pub fn new(replica: impl Into<String>, seq: u64) -> Self {
        Self {
            replica: replica.into(),
            seq,
            ulid: Ulid::new(),
        }
    }

    /// Create a genesis ID (for the virtual head).
    pub fn genesis() -> Self {
        Self {
            replica: "".to_string(),
            seq: 0,
            ulid: Ulid::nil(),
        }
    }
}

impl PartialOrd for ListId {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ListId {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Higher sequence = later in causal order
        // Tie-break on replica ID, then ULID
        self.seq
            .cmp(&other.seq)
            .then_with(|| self.replica.cmp(&other.replica))
            .then_with(|| self.ulid.cmp(&other.ulid))
    }
}

/// A node in the RGA list.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListNode<T> {
    /// The unique ID of this node.
    pub id: ListId,
    /// The value stored (None if deleted - tombstone).
    pub value: Option<T>,
    /// The ID of the element this was inserted after.
    pub origin: ListId,
    /// Whether this node is deleted (tombstone).
    pub deleted: bool,
}

impl<T> ListNode<T> {
    pub fn new(id: ListId, value: T, origin: ListId) -> Self {
        Self {
            id,
            value: Some(value),
            origin,
            deleted: false,
        }
    }
}

/// Delta for RGA list operations.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RGAListDelta<T: Clone + PartialEq> {
    /// Nodes to insert.
    pub inserts: Vec<ListNode<T>>,
    /// IDs of nodes to delete.
    pub deletes: Vec<ListId>,
}

impl<T: Clone + PartialEq> RGAListDelta<T> {
    pub fn new() -> Self {
        Self {
            inserts: Vec::new(),
            deletes: Vec::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.inserts.is_empty() && self.deletes.is_empty()
    }
}

impl<T: Clone + PartialEq> Default for RGAListDelta<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Replicated Growable Array - an ordered list CRDT.
///
/// Supports insert, delete, and move operations with
/// deterministic conflict resolution.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RGAList<T: Clone + PartialEq> {
    /// All nodes indexed by their ID.
    nodes: HashMap<ListId, ListNode<T>>,
    /// Children of each node (for ordering).
    /// Maps origin -> list of children sorted by ID.
    children: HashMap<ListId, Vec<ListId>>,
    /// The replica ID for this instance.
    replica_id: String,
    /// Sequence counter for generating IDs.
    seq: u64,
    /// Pending delta for replication.
    #[serde(skip)]
    pending_delta: Option<RGAListDelta<T>>,
}

impl<T: Clone + PartialEq> RGAList<T> {
    /// Create a new empty RGA list.
    pub fn new(replica_id: impl Into<String>) -> Self {
        let replica_id = replica_id.into();
        let mut list = Self {
            nodes: HashMap::new(),
            children: HashMap::new(),
            replica_id,
            seq: 0,
            pending_delta: None,
        };

        // Insert virtual head node
        let genesis = ListId::genesis();
        list.children.insert(genesis, Vec::new());

        list
    }

    /// Get the replica ID.
    pub fn replica_id(&self) -> &str {
        &self.replica_id
    }

    /// Generate a new unique ID.
    fn next_id(&mut self) -> ListId {
        self.seq += 1;
        ListId::new(&self.replica_id, self.seq)
    }

    /// Insert a value at the given index.
    pub fn insert(&mut self, index: usize, value: T) {
        let origin = self
            .id_at_index(index.saturating_sub(1))
            .unwrap_or(ListId::genesis());
        self.insert_after(&origin, value);
    }

    /// Insert a value after the given origin ID.
    pub fn insert_after(&mut self, origin: &ListId, value: T) {
        let id = self.next_id();
        let node = ListNode::new(id.clone(), value, origin.clone());

        self.integrate_node(node.clone());

        // Record delta
        let delta = self.pending_delta.get_or_insert_with(RGAListDelta::new);
        delta.inserts.push(node);
    }

    /// Insert at the beginning.
    pub fn push_front(&mut self, value: T) {
        self.insert(0, value);
    }

    /// Insert at the end.
    pub fn push_back(&mut self, value: T) {
        let len = self.len();
        self.insert(len, value);
    }

    /// Delete the element at the given index.
    pub fn delete(&mut self, index: usize) -> Option<T> {
        let id = self.id_at_index(index)?;
        self.delete_by_id(&id)
    }

    /// Delete an element by its ID.
    pub fn delete_by_id(&mut self, id: &ListId) -> Option<T> {
        if let Some(node) = self.nodes.get_mut(id) {
            if !node.deleted {
                node.deleted = true;
                let value = node.value.take();

                // Record delta
                let delta = self.pending_delta.get_or_insert_with(RGAListDelta::new);
                delta.deletes.push(id.clone());

                return value;
            }
        }
        None
    }

    /// Move an element from one index to another.
    pub fn move_element(&mut self, from: usize, to: usize) -> bool {
        if let Some(value) = self.delete(from) {
            // Adjust target index if moving forward
            let adjusted_to = if to > from { to - 1 } else { to };
            self.insert(adjusted_to, value);
            true
        } else {
            false
        }
    }

    /// Get the element at the given index.
    pub fn get(&self, index: usize) -> Option<&T> {
        let id = self.id_at_index(index)?;
        self.nodes.get(&id).and_then(|n| n.value.as_ref())
    }

    /// Get a mutable reference to the element at the given index.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        let id = self.id_at_index(index)?;
        self.nodes.get_mut(&id).and_then(|n| n.value.as_mut())
    }

    /// Get the number of non-deleted elements.
    pub fn len(&self) -> usize {
        self.nodes.values().filter(|n| !n.deleted).count()
    }

    /// Check if the list is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Iterate over values in order.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.iter_nodes()
            .filter(|n| !n.deleted)
            .filter_map(|n| n.value.as_ref())
    }

    /// Iterate over (index, value) pairs.
    pub fn iter_indexed(&self) -> impl Iterator<Item = (usize, &T)> {
        self.iter().enumerate()
    }

    /// Convert to a Vec.
    pub fn to_vec(&self) -> Vec<T> {
        self.iter().cloned().collect()
    }

    /// Get the ID at a given visible index.
    fn id_at_index(&self, index: usize) -> Option<ListId> {
        self.iter_nodes()
            .filter(|n| !n.deleted)
            .nth(index)
            .map(|n| n.id.clone())
    }

    /// Get the visible index for an ID.
    pub fn index_of_id(&self, id: &ListId) -> Option<usize> {
        self.iter_nodes()
            .filter(|n| !n.deleted)
            .position(|n| &n.id == id)
    }

    /// Iterate over all nodes in order (including tombstones).
    fn iter_nodes(&self) -> impl Iterator<Item = &ListNode<T>> {
        RGAIterator {
            list: self,
            stack: vec![ListId::genesis()],
            visited: std::collections::HashSet::new(),
        }
    }

    /// Integrate a node into the list.
    fn integrate_node(&mut self, node: ListNode<T>) {
        let id = node.id.clone();
        let origin = node.origin.clone();

        // Add to nodes map
        self.nodes.insert(id.clone(), node);

        // Add to children of origin, maintaining sort order
        let children = self.children.entry(origin).or_default();

        // Find insertion position (maintain descending order by ID for RGA)
        let pos = children
            .iter()
            .position(|c| c < &id)
            .unwrap_or(children.len());
        children.insert(pos, id.clone());

        // Ensure this node has a children entry (reuse cloned id)
        self.children.entry(id).or_default();
    }

    /// Take the pending delta.
    pub fn take_delta(&mut self) -> Option<RGAListDelta<T>> {
        self.pending_delta.take()
    }

    /// Apply a delta from another replica.
    pub fn apply_delta(&mut self, delta: &RGAListDelta<T>) {
        // Estimate how many entries are truly new before reserving.
        // This avoids allocating proportional to raw delta size when inserts are duplicates.
        let mut new_nodes = 0usize;
        let mut new_origins = 0usize;

        for node in &delta.inserts {
            if !self.nodes.contains_key(&node.id) {
                new_nodes += 1;
                if !self.children.contains_key(&node.origin) {
                    new_origins += 1;
                }
            }
        }

        if new_nodes > 0 {
            self.nodes.reserve(new_nodes);
        }
        if new_origins > 0 {
            self.children.reserve(new_origins);
        }

        // Apply inserts
        for node in &delta.inserts {
            if !self.nodes.contains_key(&node.id) {
                self.integrate_node(node.clone());
            }
        }

        // Apply deletes
        for id in &delta.deletes {
            if let Some(node) = self.nodes.get_mut(id) {
                node.deleted = true;
                node.value = None;
            }
        }
    }
}

/// Iterator for traversing the RGA list in order.
struct RGAIterator<'a, T: Clone + PartialEq> {
    list: &'a RGAList<T>,
    stack: Vec<ListId>,
    visited: std::collections::HashSet<ListId>,
}

impl<'a, T: Clone + PartialEq> Iterator for RGAIterator<'a, T> {
    type Item = &'a ListNode<T>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(id) = self.stack.pop() {
            if self.visited.contains(&id) {
                continue;
            }
            self.visited.insert(id.clone());

            // Push children in reverse order (so first child is processed first)
            if let Some(children) = self.list.children.get(&id) {
                for child in children.iter().rev() {
                    if !self.visited.contains(child) {
                        self.stack.push(child.clone());
                    }
                }
            }

            // Return the node (skip genesis)
            if id != ListId::genesis() {
                if let Some(node) = self.list.nodes.get(&id) {
                    return Some(node);
                }
            }
        }
        None
    }
}

impl<T: Clone + PartialEq> PartialEq for RGAList<T> {
    fn eq(&self, other: &Self) -> bool {
        // Compare visible content
        self.to_vec() == other.to_vec()
    }
}

impl<T: Clone + PartialEq> Lattice for RGAList<T> {
    fn bottom() -> Self {
        Self::new("")
    }

    fn join(&self, other: &Self) -> Self {
        let mut result = self.clone();

        // Merge all nodes from other
        for (id, node) in &other.nodes {
            if let Some(existing) = result.nodes.get_mut(id) {
                // If deleted in either, mark as deleted
                if node.deleted {
                    existing.deleted = true;
                    existing.value = None;
                }
            } else {
                // Add new node
                result.integrate_node(node.clone());
            }
        }

        result
    }
}

impl<T: Clone + PartialEq> Default for RGAList<T> {
    fn default() -> Self {
        Self::new("")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_operations() {
        let mut list: RGAList<String> = RGAList::new("r1");

        list.push_back("a".to_string());
        list.push_back("b".to_string());
        list.push_back("c".to_string());

        assert_eq!(list.len(), 3);
        assert_eq!(list.get(0), Some(&"a".to_string()));
        assert_eq!(list.get(1), Some(&"b".to_string()));
        assert_eq!(list.get(2), Some(&"c".to_string()));
    }

    #[test]
    fn test_insert_at_index() {
        let mut list: RGAList<i32> = RGAList::new("r1");

        list.push_back(1);
        list.push_back(3);
        list.insert(1, 2);

        assert_eq!(list.to_vec(), vec![1, 2, 3]);
    }

    #[test]
    fn test_delete() {
        let mut list: RGAList<i32> = RGAList::new("r1");

        list.push_back(1);
        list.push_back(2);
        list.push_back(3);

        let deleted = list.delete(1);
        assert_eq!(deleted, Some(2));
        assert_eq!(list.to_vec(), vec![1, 3]);
    }

    #[test]
    fn test_concurrent_inserts() {
        let mut list1: RGAList<&str> = RGAList::new("r1");
        let mut list2: RGAList<&str> = RGAList::new("r2");

        // Both start with "a"
        list1.push_back("a");
        list2.apply_delta(&list1.take_delta().unwrap());

        // Concurrent inserts after "a"
        list1.push_back("b"); // r1 inserts "b"
        list2.push_back("c"); // r2 inserts "c"

        // Exchange deltas
        let delta1 = list1.take_delta().unwrap();
        let delta2 = list2.take_delta().unwrap();

        list1.apply_delta(&delta2);
        list2.apply_delta(&delta1);

        // Should converge to same order
        assert_eq!(list1.to_vec(), list2.to_vec());
    }

    #[test]
    fn test_move_element() {
        let mut list: RGAList<i32> = RGAList::new("r1");

        list.push_back(1);
        list.push_back(2);
        list.push_back(3);

        list.move_element(0, 2);
        assert_eq!(list.to_vec(), vec![2, 1, 3]);
    }

    #[test]
    fn test_lattice_join() {
        let mut list1: RGAList<i32> = RGAList::new("r1");
        let mut list2: RGAList<i32> = RGAList::new("r2");

        list1.push_back(1);
        list2.push_back(2);

        let merged = list1.join(&list2);

        // Both elements should be present
        assert_eq!(merged.len(), 2);
    }

    #[test]
    fn test_iter() {
        let mut list: RGAList<i32> = RGAList::new("r1");

        list.push_back(1);
        list.push_back(2);
        list.push_back(3);

        let collected: Vec<_> = list.iter().cloned().collect();
        assert_eq!(collected, vec![1, 2, 3]);
    }
}