eidetica/crdt/traits.rs
1//! Core traits for CRDT (Conflict-free Replicated Data Type) implementations.
2//!
3//! This module defines the fundamental traits that all CRDT implementations must satisfy:
4//! - `Data`: A marker trait for types that can be stored in Eidetica
5//! - `CRDT`: The core trait defining merge semantics for conflict resolution
6
7use crate::Result;
8
9/// Marker trait for data types that can be stored in Eidetica.
10///
11/// This trait requires serialization capabilities and cloning for data structures
12/// that can be stored in the Eidetica database. All storable types must support
13/// JSON serialization/deserialization and cloning for efficient data operations.
14///
15/// Implementing this trait signifies that a type can be safely used as the data component
16/// of an Entry in the database.
17///
18/// # Examples
19///
20/// ```
21/// use eidetica::crdt::Data;
22///
23/// #[derive(Clone, serde::Serialize, serde::Deserialize)]
24/// struct MyData {
25/// value: String,
26/// }
27///
28/// impl Data for MyData {}
29/// ```
30pub trait Data: Clone + serde::Serialize + serde::de::DeserializeOwned {}
31
32/// A trait for Conflict-free Replicated Data Types (CRDTs).
33///
34/// CRDTs are data structures that can be replicated across multiple nodes and automatically
35/// resolve conflicts without requiring coordination between nodes. They guarantee that
36/// concurrent updates can be merged deterministically, ensuring eventual consistency.
37///
38/// All CRDT types must also implement the `Data` trait, ensuring they can be stored
39/// and serialized within the Eidetica database.
40///
41/// # Examples
42///
43/// ```
44/// use eidetica::crdt::{CRDT, Data, Doc};
45/// use eidetica::Result;
46///
47/// let mut kv1 = Doc::new();
48/// kv1.set("key", "value1");
49///
50/// let mut kv2 = Doc::new();
51/// kv2.set("key", "value2");
52///
53/// let merged = kv1.merge(&kv2).unwrap();
54/// // Doc uses last-write-wins semantics for scalar values
55/// ```
56pub trait CRDT: Data + Default {
57 /// Merge this CRDT with another instance, returning a new merged instance.
58 ///
59 /// This operation must be:
60 /// - **Associative**: `(a.merge(b)).merge(c) == a.merge(b.merge(c))`
61 ///
62 /// Unlike traditional state-based CRDTs (which require a join-semilattice with
63 /// commutativity and idempotency), Eidetica's Merkle-CRDT design relaxes these
64 /// requirements. The Merkle DAG provides deterministic traversal order, eliminating
65 /// the need for commutativity, and ensures each entry is applied exactly once,
66 /// eliminating the need for idempotency.
67 ///
68 /// # Arguments
69 ///
70 /// * `other` - The other CRDT instance to merge with
71 ///
72 /// # Returns
73 ///
74 /// A new CRDT instance representing the merged state, or an error if the merge fails.
75 fn merge(&self, other: &Self) -> Result<Self>
76 where
77 Self: Sized;
78}