logicaffeine_data/crdt/sequence/
rga.rs1use crate::crdt::causal::VClock;
7use crate::crdt::delta::DeltaCrdt;
8use crate::crdt::replica::{generate_replica_id, ReplicaId};
9use crate::crdt::Merge;
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12use std::cmp::Ordering;
13use std::collections::HashMap;
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct RGADelta<T> {
18 pub nodes: Vec<RgaNode<T>>,
19 pub timestamp: u64,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct RgaId {
25 pub timestamp: u64,
27 pub replica: ReplicaId,
29}
30
31impl RgaId {
32 fn new(timestamp: u64, replica: ReplicaId) -> Self {
33 Self { timestamp, replica }
34 }
35}
36
37impl Ord for RgaId {
38 fn cmp(&self, other: &Self) -> Ordering {
39 match self.timestamp.cmp(&other.timestamp) {
41 Ordering::Equal => self.replica.cmp(&other.replica),
42 ord => ord,
43 }
44 }
45}
46
47impl PartialOrd for RgaId {
48 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
49 Some(self.cmp(other))
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub struct RgaNode<T> {
56 pub id: RgaId,
57 pub value: T,
58 pub deleted: bool,
59 pub parent: Option<RgaId>,
61}
62
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub struct RGA<T> {
69 nodes: Vec<RgaNode<T>>,
71 timestamp: u64,
73 replica_id: ReplicaId,
75}
76
77impl<T: Clone + PartialEq> RGA<T> {
78 pub fn new(replica_id: ReplicaId) -> Self {
80 Self {
81 nodes: Vec::new(),
82 timestamp: 0,
83 replica_id,
84 }
85 }
86
87 pub fn new_random() -> Self {
89 Self::new(generate_replica_id())
90 }
91
92 pub fn append(&mut self, value: T) {
94 self.timestamp += 1;
95 let id = RgaId::new(self.timestamp, self.replica_id);
96 let parent = self.last_visible_id();
97
98 self.nodes.push(RgaNode {
99 id,
100 value,
101 deleted: false,
102 parent,
103 });
104 }
105
106 pub fn insert_before(&mut self, index: usize, value: T) {
108 if index == 0 {
109 self.timestamp += 1;
111 let id = RgaId::new(self.timestamp, self.replica_id);
112 self.nodes.push(RgaNode {
113 id,
114 value,
115 deleted: false,
116 parent: None,
117 });
118 } else {
119 self.insert_after(index - 1, value);
121 }
122 }
123
124 pub fn insert_after(&mut self, index: usize, value: T) {
126 let parent_id = self.visible_id_at(index);
127 self.timestamp += 1;
128 let id = RgaId::new(self.timestamp, self.replica_id);
129
130 self.nodes.push(RgaNode {
131 id,
132 value,
133 deleted: false,
134 parent: parent_id,
135 });
136 }
137
138 pub fn remove(&mut self, index: usize) {
140 if let Some(id) = self.visible_id_at(index) {
141 if let Some(node) = self.nodes.iter_mut().find(|n| n.id == id) {
142 node.deleted = true;
143 }
144 }
145 }
146
147 pub fn get(&self, index: usize) -> Option<&T> {
149 self.visible_nodes().nth(index).map(|n| &n.value)
150 }
151
152 pub fn len(&self) -> usize {
154 self.visible_nodes().count()
155 }
156
157 pub fn is_empty(&self) -> bool {
159 self.len() == 0
160 }
161
162 pub fn to_vec(&self) -> Vec<T> {
164 self.visible_nodes().map(|n| n.value.clone()).collect()
165 }
166
167 pub fn iter(&self) -> impl Iterator<Item = &T> {
169 self.visible_nodes().map(|n| &n.value)
170 }
171
172 fn visible_nodes(&self) -> impl Iterator<Item = &RgaNode<T>> {
174 self.sorted_nodes().into_iter().filter(|n| !n.deleted)
175 }
176
177 fn sorted_nodes(&self) -> Vec<&RgaNode<T>> {
179 let mut children_map: HashMap<Option<RgaId>, Vec<&RgaNode<T>>> = HashMap::new();
181 for node in &self.nodes {
182 children_map.entry(node.parent).or_default().push(node);
183 }
184
185 for children in children_map.values_mut() {
187 children.sort_by(|a, b| b.id.cmp(&a.id));
188 }
189
190 let mut result: Vec<&RgaNode<T>> = Vec::new();
192 let mut stack: Vec<&RgaNode<T>> = Vec::new();
193
194 if let Some(heads) = children_map.get(&None) {
196 for node in heads.iter().rev() {
197 stack.push(node);
198 }
199 }
200
201 while let Some(node) = stack.pop() {
202 result.push(node);
203
204 if let Some(children) = children_map.get(&Some(node.id)) {
206 for child in children.iter().rev() {
207 stack.push(child);
208 }
209 }
210 }
211
212 result
213 }
214
215 fn last_visible_id(&self) -> Option<RgaId> {
217 self.sorted_nodes()
218 .into_iter()
219 .filter(|n| !n.deleted)
220 .last()
221 .map(|n| n.id)
222 }
223
224 fn visible_id_at(&self, index: usize) -> Option<RgaId> {
226 self.visible_nodes().nth(index).map(|n| n.id)
227 }
228}
229
230impl<T: Clone + PartialEq> Merge for RGA<T> {
231 fn merge(&mut self, other: &Self) {
232 self.timestamp = self.timestamp.max(other.timestamp);
234
235 for other_node in &other.nodes {
237 let exists = self.nodes.iter().any(|n| n.id == other_node.id);
238 if !exists {
239 self.nodes.push(other_node.clone());
240 } else {
241 if let Some(my_node) = self.nodes.iter_mut().find(|n| n.id == other_node.id) {
243 if other_node.deleted {
244 my_node.deleted = true;
245 }
246 }
247 }
248 }
249 }
250}
251
252impl<T: Clone + PartialEq + Serialize + DeserializeOwned + Send + 'static> DeltaCrdt for RGA<T> {
253 type Delta = RGADelta<T>;
254
255 fn delta_since(&self, since: &VClock) -> Option<Self::Delta> {
256 let current = self.version();
257 if since.dominates(¤t) {
258 return None;
259 }
260
261 let nodes: Vec<RgaNode<T>> = self
266 .nodes
267 .iter()
268 .filter(|n| n.id.timestamp > since.get(n.id.replica))
269 .cloned()
270 .collect();
271 Some(RGADelta {
272 nodes,
273 timestamp: self.timestamp,
274 })
275 }
276
277 fn apply_delta(&mut self, delta: &Self::Delta) {
278 self.timestamp = self.timestamp.max(delta.timestamp);
279
280 for delta_node in &delta.nodes {
281 let exists = self.nodes.iter().any(|n| n.id == delta_node.id);
282 if !exists {
283 self.nodes.push(delta_node.clone());
284 } else if let Some(my_node) = self.nodes.iter_mut().find(|n| n.id == delta_node.id) {
285 if delta_node.deleted {
286 my_node.deleted = true;
287 }
288 }
289 }
290 }
291
292 fn version(&self) -> VClock {
293 let mut clock = VClock::new();
295 for node in &self.nodes {
296 let current = clock.get(node.id.replica);
297 if node.id.timestamp > current {
298 for _ in current..node.id.timestamp {
300 clock.increment(node.id.replica);
301 }
302 }
303 }
304 clock
305 }
306}
307
308impl<T: Clone + PartialEq> Default for RGA<T> {
309 fn default() -> Self {
310 Self::new_random()
311 }
312}
313
314impl<T: Clone + PartialEq> IntoIterator for RGA<T> {
316 type Item = T;
317 type IntoIter = std::vec::IntoIter<T>;
318
319 fn into_iter(self) -> Self::IntoIter {
320 self.to_vec().into_iter()
321 }
322}
323
324#[cfg(test)]
325#[path = "../../../../logicaffeine_tests/unit/logicaffeine_data/crdt/sequence/rga/tests.rs"]
326mod tests;