crdt_data_types/traits.rs
1// Copyright (c) 2026 Adrian Robinson. All rights reserved.
2// Licensed under the MIT License. See LICENSE file in the project root for full license information.
3
4use serde::{de::DeserializeOwned, Serialize};
5use thiserror::Error;
6
7/// Error type for CRDT operations
8#[derive(Debug, Error)]
9pub enum CrdtError {
10 #[error("Serialization error: {0}")]
11 Serialization(String),
12 #[error("Deserialization error: {0}")]
13 Deserialization(String),
14 #[error("Merge error: {0}")]
15 Merge(String),
16 #[error("Validation error: {0}")]
17 Validation(String),
18 #[error("Invalid input: {0}")]
19 InvalidInput(String),
20 #[error("Internal error: {0}")]
21 Internal(String),
22}
23
24/// CRDT Reader trait - provides zero-copy access to serialized CRDT data.
25///
26/// Implementations of this trait should wrap Cap'n Proto readers to allow
27/// inspection of CRDT fields without full deserialization. This is critical
28/// for the performance of the zero-copy merge pattern.
29pub trait CrdtReader<'a> {
30 /// Returns true if the CRDT is in its default (empty) state.
31 fn is_empty(&self) -> Result<bool, CrdtError>;
32}
33
34/// Core CRDT trait - defines the interface for state-based Conflict-free Replicated Data Types.
35///
36/// All CRDTs in this crate implement this trait to support the zero-copy merge pattern.
37/// The pattern unifies merge and compaction, minimizing allocations and CPU overhead.
38///
39/// # Requirements
40///
41/// Implementations must satisfy the following algebraic properties:
42/// - **Commutativity**: `merge([A, B]) == merge([B, A])`
43/// - **Associativity**: `merge([merge([A, B]), C]) == merge([A, merge([B, C])])`
44/// - **Idempotence**: `merge([A, A]) == merge([A])`
45pub trait Crdt: Clone + Serialize + DeserializeOwned + Send + Sync {
46 /// Zero-copy reader type associated with this CRDT.
47 type Reader<'a>: CrdtReader<'a>
48 where
49 Self: 'a;
50
51 /// Merges N CRDTs from zero-copy readers into a single new CRDT instance.
52 ///
53 /// This is the primary mechanism for both state synchronization and data compaction.
54 /// By reading from multiple sources and producing a single merged result, we
55 /// minimize memory churn and garbage collection pressure.
56 ///
57 /// # Arguments
58 /// * `readers` - A slice of zero-copy readers pointing to serialized CRDT states.
59 fn merge_from_readers(readers: &[Self::Reader<'_>]) -> Result<Self, CrdtError>
60 where
61 Self: Sized;
62
63 /// Validates the internal consistency of the CRDT state.
64 ///
65 /// This is typically called after a merge operation to ensure that all
66 /// invariants for the specific CRDT type are maintained.
67 fn validate(&self) -> Result<(), CrdtError>;
68
69 /// Returns true if the CRDT is in its default (empty) state.
70 fn is_empty(&self) -> bool;
71
72 /// Serializes the CRDT to a byte buffer using Cap'n Proto.
73 ///
74 /// The resulting bytes are optimized for zero-copy reading by `CrdtReader`.
75 fn to_capnp_bytes(&self) -> Vec<u8>;
76}