crdt-graph 0.3.1

An op-based 2P2P-Graph CRDT implementation in Rust.
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
use std::fmt::Debug;
use std::hash::Hash;

use crate::TwoPTwoPGraphError;

/// Common trait for all operation types, providing a unique identifier.
pub trait TwoPTwoPId<Id> {
    /// Returns the unique identifier of this operation.
    fn id(&self) -> &Id;
}

/// Marker trait for a vertex-add operation.
pub trait TwoPTwoPAddVertex<Id>: TwoPTwoPId<Id> {}

/// Trait for a vertex-remove operation, linking back to the original add.
pub trait TwoPTwoPRemoveVertex<Id>: TwoPTwoPId<Id> {
    /// Returns the ID of the corresponding `addVertex` operation.
    fn add_vertex_id(&self) -> &Id;
}

/// Trait for an edge-add operation, specifying source and target vertices.
pub trait TwoPTwoPAddEdge<Id>: TwoPTwoPId<Id> {
    /// Returns the source vertex ID.
    fn source(&self) -> &Id;
    /// Returns the target vertex ID.
    fn target(&self) -> &Id;
}

/// Trait for an edge-remove operation, linking back to the original add.
pub trait TwoPTwoPRemoveEdge<Id>: TwoPTwoPId<Id> {
    /// Returns the ID of the corresponding `addEdge` operation.
    fn add_edge_id(&self) -> &Id;
}

/// Distinguishes the two phases of an op-based CRDT update.
pub enum UpdateType {
    /// Executed only on the originating replica; checks preconditions.
    AtSource,
    /// Executed on all replicas; applies the actual state change.
    Downstream,
}

/// An update operation that can be applied to a [`TwoPTwoPGraph`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UpdateOperation<VA, VR, EA, ER> {
    AddVertex(VA),
    RemoveVertex(VR),
    AddEdge(EA),
    RemoveEdge(ER),
}

/// An op-based 2P2P-Graph CRDT.
///
/// Maintains four sets corresponding to the paper's payload:
/// - `V_A` — vertices added
/// - `V_R` — vertices removed
/// - `E_A` — edges added
/// - `E_R` — edges removed
///
/// Generic parameters:
/// - `VA` / `VR` — vertex add / remove operation types
/// - `EA` / `ER` — edge add / remove operation types
/// - `I` — the shared identifier type
#[derive(Clone, Debug)]
pub struct TwoPTwoPGraph<VA, VR, EA, ER, I>
where
    VA: Clone + TwoPTwoPAddVertex<I>,
    VR: Clone + TwoPTwoPRemoveVertex<I>,
    EA: Clone + TwoPTwoPAddEdge<I>,
    ER: Clone + TwoPTwoPRemoveEdge<I>,
    I: Eq + Hash + Debug + Clone,
{
    vertices_added: Vec<VA>,
    vertices_removed: Vec<VR>,
    edges_added: Vec<EA>,
    edges_removed: Vec<ER>,
    _phantom: std::marker::PhantomData<I>,
}

impl<VA, VR, EA, ER, I> Default for TwoPTwoPGraph<VA, VR, EA, ER, I>
where
    VA: Clone + TwoPTwoPAddVertex<I>,
    VR: Clone + TwoPTwoPRemoveVertex<I>,
    EA: Clone + TwoPTwoPAddEdge<I>,
    ER: Clone + TwoPTwoPRemoveEdge<I>,
    I: Eq + Hash + Debug + Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<VA, VR, EA, ER, I> TwoPTwoPGraph<VA, VR, EA, ER, I>
where
    VA: Clone + TwoPTwoPAddVertex<I>,
    VR: Clone + TwoPTwoPRemoveVertex<I>,
    EA: Clone + TwoPTwoPAddEdge<I>,
    ER: Clone + TwoPTwoPRemoveEdge<I>,
    I: Eq + Hash + Debug + Clone,
{
    /// Creates an empty graph with all four sets initialized to ∅.
    pub fn new() -> Self {
        TwoPTwoPGraph {
            vertices_added: Vec::new(),
            vertices_removed: Vec::new(),
            edges_added: Vec::new(),
            edges_removed: Vec::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Returns `true` if the vertex is in `V_A \ V_R` (added and not removed).
    pub fn lookup_vertex(&self, vertex_id: &I) -> bool {
        self.vertices_added.iter().any(|va| va.id() == vertex_id)
            && !self
                .vertices_removed
                .iter()
                .any(|vr| vr.add_vertex_id() == vertex_id)
    }

    /// Returns the edge-add operation referenced by a given edge-remove operation, if present.
    pub fn get_edge_added_from_remove_edge(&self, remove_edge: &ER) -> Option<&EA> {
        self.edges_added
            .iter()
            .find(|ea| ea.id() == remove_edge.add_edge_id())
    }

    /// Returns `true` if the edge referenced by `remove_edge` exists in `E_A \ E_R`
    /// and both of its endpoint vertices are currently in `V_A \ V_R`.
    pub fn lookup_from_remove_edge(&self, remove_edge: &ER) -> bool {
        self.get_edge_added_from_remove_edge(remove_edge)
            .is_some_and(|edge_added| {
                self.lookup_vertex(edge_added.source())
                    && self.lookup_vertex(edge_added.target())
                    && !self
                        .edges_removed
                        .iter()
                        .any(|er| er.add_edge_id() == remove_edge.add_edge_id())
            })
    }

    /// Convenience method that calls [`prepare`](Self::prepare) and discards the returned operation.
    pub fn update_operation(
        &mut self,
        update_operation: UpdateOperation<VA, VR, EA, ER>,
    ) -> Result<(), TwoPTwoPGraphError<I>> {
        self.prepare(update_operation).map(|_| ())
    }

    /// Executes atSource precondition checks and applies the downstream effect locally.
    /// Returns the operation to broadcast to other replicas.
    pub fn prepare(
        &mut self,
        op: UpdateOperation<VA, VR, EA, ER>,
    ) -> Result<UpdateOperation<VA, VR, EA, ER>, TwoPTwoPGraphError<I>> {
        let broadcast = op.clone();
        match op {
            UpdateOperation::AddVertex(vertex) => self.add_vertex(vertex, UpdateType::AtSource)?,
            UpdateOperation::AddEdge(edge) => self.add_edge(edge, UpdateType::AtSource)?,
            UpdateOperation::RemoveVertex(vertex) => {
                self.remove_vertex(vertex, UpdateType::AtSource)?
            }
            UpdateOperation::RemoveEdge(edge) => self.remove_edge(edge, UpdateType::AtSource)?,
        }
        Ok(broadcast)
    }

    /// Applies an operation received from a remote replica (downstream).
    pub fn apply_downstream(
        &mut self,
        op: UpdateOperation<VA, VR, EA, ER>,
    ) -> Result<(), TwoPTwoPGraphError<I>> {
        match op {
            UpdateOperation::AddVertex(vertex) => self.add_vertex(vertex, UpdateType::Downstream),
            UpdateOperation::AddEdge(edge) => self.add_edge(edge, UpdateType::Downstream),
            UpdateOperation::RemoveVertex(vertex) => {
                self.remove_vertex(vertex, UpdateType::Downstream)
            }
            UpdateOperation::RemoveEdge(edge) => self.remove_edge(edge, UpdateType::Downstream),
        }
    }

    /// Adds a vertex to `V_A`. Fails if a vertex with the same ID already exists.
    ///
    /// Both `AtSource` and `Downstream` behave identically (no preconditions per the paper).
    pub fn add_vertex(
        &mut self,
        vertex: VA,
        _update_type: UpdateType,
    ) -> Result<(), TwoPTwoPGraphError<I>> {
        if self.vertices_added.iter().any(|va| va.id() == vertex.id()) {
            return Err(TwoPTwoPGraphError::VertexAlreadyExists(vertex.id().clone()));
        }
        self.vertices_added.push(vertex);
        Ok(())
    }

    /// Adds an edge to `E_A`.
    ///
    /// - **AtSource**: checks `lookup(source) ∧ lookup(target)`.
    /// - **Downstream**: skips vertex existence checks (per the paper).
    pub fn add_edge(
        &mut self,
        edge: EA,
        update_type: UpdateType,
    ) -> Result<(), TwoPTwoPGraphError<I>> {
        if matches!(update_type, UpdateType::AtSource) {
            if !self.lookup_vertex(&edge.source()) {
                return Err(TwoPTwoPGraphError::VertexDoesNotExists(
                    edge.source().clone(),
                ));
            }
            if !self.lookup_vertex(&edge.target()) {
                return Err(TwoPTwoPGraphError::VertexDoesNotExists(
                    edge.target().clone(),
                ));
            }
        }
        if self.edges_added.iter().any(|ea| ea.id() == edge.id()) {
            return Err(TwoPTwoPGraphError::EdgeAlreadyExists(edge.id().clone()));
        }
        self.edges_added.push(edge);
        Ok(())
    }

    /// Adds a vertex-remove to `V_R`.
    ///
    /// - **AtSource**: checks `lookup(w)` and that no active edge references `w`.
    /// - **Downstream**: checks that the corresponding `addVertex(w)` has been delivered.
    pub fn remove_vertex(
        &mut self,
        vertex: VR,
        update_type: UpdateType,
    ) -> Result<(), TwoPTwoPGraphError<I>> {
        if matches!(update_type, UpdateType::AtSource) {
            // pre
            if !self.lookup_vertex(vertex.add_vertex_id()) {
                return Err(TwoPTwoPGraphError::VertexDoesNotExists(
                    vertex.add_vertex_id().clone(),
                ));
            }
            // pre: E ⊆ V × V — vertex has no active edges
            for ea in self.edges_added.iter() {
                let is_removed = self
                    .edges_removed
                    .iter()
                    .any(|er| ea.id() == er.add_edge_id());
                if !is_removed
                    && (ea.source() == vertex.add_vertex_id()
                        || ea.target() == vertex.add_vertex_id())
                {
                    return Err(TwoPTwoPGraphError::VertexHasEdge(
                        vertex.add_vertex_id().clone(),
                        ea.id().clone(),
                    ));
                }
            }
        }

        if matches!(update_type, UpdateType::Downstream) {
            // pre: addVertex(w) delivered
            if !self
                .vertices_added
                .iter()
                .any(|va| va.id() == vertex.add_vertex_id())
            {
                return Err(TwoPTwoPGraphError::AddVertexNotDelivered(
                    vertex.add_vertex_id().clone(),
                ));
            }
        }

        if self
            .vertices_removed
            .iter()
            .any(|vr| vr.id() == vertex.id())
        {
            return Err(TwoPTwoPGraphError::VertexAlreadyExists(vertex.id().clone()));
        }
        self.vertices_removed.push(vertex);
        Ok(())
    }

    /// Adds an edge-remove to `E_R`.
    ///
    /// - **AtSource**: checks `lookup((u,v))`.
    /// - **Downstream**: checks that the corresponding `addEdge(u,v)` has been delivered.
    pub fn remove_edge(
        &mut self,
        remove_edge: ER,
        update_type: UpdateType,
    ) -> Result<(), TwoPTwoPGraphError<I>> {
        if matches!(update_type, UpdateType::AtSource) {
            // pre: lookup((u,v))
            if !self.lookup_from_remove_edge(&remove_edge) {
                return Err(TwoPTwoPGraphError::EdgeDoesNotExists(
                    remove_edge.add_edge_id().clone(),
                ));
            }
        }

        if matches!(update_type, UpdateType::Downstream) {
            // pre: addEdge(u,v) delivered
            if !self
                .edges_added
                .iter()
                .any(|ea| ea.id() == remove_edge.add_edge_id())
            {
                return Err(TwoPTwoPGraphError::AddEdgeNotDelivered(
                    remove_edge.add_edge_id().clone(),
                ));
            }
        }

        if self
            .edges_removed
            .iter()
            .any(|er| er.id() == remove_edge.id())
        {
            return Err(TwoPTwoPGraphError::EdgeAlreadyExists(
                remove_edge.id().clone(),
            ));
        }
        self.edges_removed.push(remove_edge);
        Ok(())
    }

    /// Converts the current CRDT state into a [`petgraph::graph::DiGraph`].
    ///
    /// Only vertices in `V_A \ V_R` and edges in `E_A \ E_R` (whose endpoints
    /// are present) are included in the resulting directed graph.
    pub fn generate_petgraph(&self) -> petgraph::graph::DiGraph<VA, EA> {
        let mut graph = petgraph::graph::DiGraph::new();
        let mut vertex_map = std::collections::HashMap::new();
        for va in self.vertices_added.iter() {
            let is_removed = self
                .vertices_removed
                .iter()
                .any(|vr| va.id() == vr.add_vertex_id());
            if !is_removed {
                let vertex = graph.add_node(va.clone());
                vertex_map.insert(va.id().clone(), vertex);
            }
        }
        for ea in self.edges_added.iter() {
            let is_removed = self
                .edges_removed
                .iter()
                .any(|er| ea.id() == er.add_edge_id());
            if !is_removed {
                if let (Some(&source), Some(&target)) =
                    (vertex_map.get(ea.source()), vertex_map.get(ea.target()))
                {
                    graph.add_edge(source, target, ea.clone());
                }
            }
        }
        graph
    }

    /// Returns the number of active vertices (`V_A \ V_R`).
    pub fn vertex_count(&self) -> usize {
        self.vertices_added
            .iter()
            .filter(|va| {
                !self
                    .vertices_removed
                    .iter()
                    .any(|vr| va.id() == vr.add_vertex_id())
            })
            .count()
    }

    /// Returns the number of active edges (`E_A \ E_R`).
    pub fn edge_count(&self) -> usize {
        self.edges_added
            .iter()
            .filter(|ea| {
                !self
                    .edges_removed
                    .iter()
                    .any(|er| ea.id() == er.add_edge_id())
            })
            .count()
    }

    /// Returns `true` if the graph has no active vertices and no active edges.
    pub fn is_empty(&self) -> bool {
        self.vertex_count() == 0 && self.edge_count() == 0
    }

    /// Returns an iterator over all active (non-removed) vertex-add operations.
    pub fn vertices(&self) -> impl Iterator<Item = &VA> {
        self.vertices_added.iter().filter(|va| {
            !self
                .vertices_removed
                .iter()
                .any(|vr| va.id() == vr.add_vertex_id())
        })
    }

    /// Returns an iterator over all active (non-removed) edge-add operations.
    pub fn edges(&self) -> impl Iterator<Item = &EA> {
        self.edges_added.iter().filter(|ea| {
            !self
                .edges_removed
                .iter()
                .any(|er| ea.id() == er.add_edge_id())
        })
    }

    /// Returns a slice of all vertex-add operations ever recorded (`V_A`).
    pub fn all_vertices_added(&self) -> &[VA] {
        &self.vertices_added
    }

    /// Returns a slice of all vertex-remove operations ever recorded (`V_R`).
    pub fn all_vertices_removed(&self) -> &[VR] {
        &self.vertices_removed
    }

    /// Returns a slice of all edge-add operations ever recorded (`E_A`).
    pub fn all_edges_added(&self) -> &[EA] {
        &self.edges_added
    }

    /// Returns a slice of all edge-remove operations ever recorded (`E_R`).
    pub fn all_edges_removed(&self) -> &[ER] {
        &self.edges_removed
    }
}