forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrdt_manager.rs
More file actions
1512 lines (1361 loc) · 53.3 KB
/
Copy pathcrdt_manager.rs
File metadata and controls
1512 lines (1361 loc) · 53.3 KB
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! CRDT Manager for Nulang.
//!
//! The `CrdtManager` owns all local CRDT replicas and handles inter-node
//! synchronization. Actors interact with CRDTs through `CrdtHandle`s, which
//! are lightweight references to the actual CRDT stored in the manager.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use super::crdt::{AWORSet, Crdt, GCounter, GSet, ORSet, PNCounter};
use super::crdt_reg::{LWWRegister, MVRegister, RGA};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CrdtId(pub u64);
static CRDT_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
impl CrdtId {
/// Mint a node-scoped id: the high 32 bits carry the node id, the low 32
/// bits a process-global counter. Folding the node id in guarantees ids
/// created independently on different nodes never collide (each node's
/// counter starts at the same value, so a bare counter would).
pub fn new(node_id: u64) -> Self {
let counter = CRDT_ID_COUNTER.fetch_add(1, Ordering::Relaxed) & 0xFFFF_FFFF;
CrdtId((node_id << 32) | counter)
}
}
// Re-export the canonical CrdtType from ast.
pub use crate::ast::CrdtType;
// Legacy to_u8/from_u8 are now on ast::CrdtType.
// The CrdtType import above provides them.
#[derive(Debug, Clone, PartialEq)]
pub struct CrdtOp {
pub crdt_id: CrdtId,
pub crdt_type: CrdtType,
pub payload: Vec<u8>,
}
impl CrdtOp {
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::new();
buf.extend_from_slice(&self.crdt_id.0.to_be_bytes());
buf.push(self.crdt_type as u8);
buf.extend_from_slice(&(self.payload.len() as u32).to_be_bytes());
buf.extend_from_slice(&self.payload);
buf
}
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
if bytes.len() < 13 {
return None;
}
let crdt_id = CrdtId(u64::from_be_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]));
let crdt_type = match bytes[8] {
0 => CrdtType::GCounter,
1 => CrdtType::PNCounter,
2 => CrdtType::GSet,
3 => CrdtType::ORSet,
4 => CrdtType::AWORSet,
5 => CrdtType::LWWRegister,
6 => CrdtType::MVRegister,
7 => CrdtType::RGA,
_ => return None,
};
let payload_len = u32::from_be_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]) as usize;
if bytes.len() < 13 + payload_len {
return None;
}
let payload = bytes[13..13 + payload_len].to_vec();
Some(CrdtOp {
crdt_id,
crdt_type,
payload,
})
}
}
/// A CRDT sync op tagged as either a **delta** (changes since the sender's
/// last sync) or a **full-state** snapshot.
///
/// Deltas are produced by [`CrdtManager::generate_delta_sync_ops`] and ride
/// in `Packet::CrdtDeltaSync`. A delta payload is itself a valid serialized
/// CRDT state, so receivers merge it with the same `merge` used for full
/// states — the difference is only that a delta for an *unknown* entry id
/// is ignored (there is no base to apply it onto), while a full-state op
/// creates the entry, exactly like `CrdtManager::apply_op`.
#[derive(Debug, Clone, PartialEq)]
pub struct CrdtDeltaOp {
pub op: CrdtOp,
pub is_delta: bool,
}
impl CrdtDeltaOp {
/// Wire layout: `[is_delta:u8][CrdtOp bytes]`.
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.op.payload.len() + 14);
buf.push(if self.is_delta { 1 } else { 0 });
buf.extend_from_slice(&self.op.to_bytes());
buf
}
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
let is_delta = match bytes.first()? {
0 => false,
1 => true,
_ => return None,
};
let op = CrdtOp::from_bytes(&bytes[1..])?;
Some(CrdtDeltaOp { op, is_delta })
}
}
#[derive(Debug, Clone)]
pub enum CrdtEntry {
GCounter(GCounter),
PNCounter(PNCounter),
GSet(GSet<String>),
ORSet(ORSet<String>),
AWORSet(AWORSet<String>),
LWWRegister(LWWRegister<String>),
MVRegister(MVRegister<String>),
RGA(RGA<String>),
}
/// Helper trait mapping CRDT inner types to their `CrdtEntry` variant so
/// [`CrdtManager::entry_mut`] can return typed references without per-type
/// boilerplate accessors.
pub trait CrdtEntryInner: Sized {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self>;
}
impl CrdtEntryInner for GCounter {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::GCounter(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for PNCounter {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::PNCounter(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for GSet<String> {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::GSet(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for ORSet<String> {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::ORSet(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for AWORSet<String> {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::AWORSet(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for LWWRegister<String> {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::LWWRegister(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for MVRegister<String> {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::MVRegister(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntryInner for RGA<String> {
fn try_from_entry(entry: &mut CrdtEntry) -> Option<&mut Self> {
match entry {
CrdtEntry::RGA(c) => Some(c),
_ => None,
}
}
}
impl CrdtEntry {
pub fn payload_bytes(&self) -> Vec<u8> {
match self {
CrdtEntry::GCounter(c) => c.to_bytes(),
CrdtEntry::PNCounter(c) => c.to_bytes(),
CrdtEntry::GSet(c) => c.to_bytes(),
CrdtEntry::ORSet(c) => c.to_bytes(),
CrdtEntry::AWORSet(c) => c.to_bytes(),
CrdtEntry::LWWRegister(c) => c.to_bytes(),
CrdtEntry::MVRegister(c) => c.to_bytes(),
CrdtEntry::RGA(c) => c.to_bytes(),
}
}
pub fn crdt_type(&self) -> CrdtType {
match self {
CrdtEntry::GCounter(_) => CrdtType::GCounter,
CrdtEntry::PNCounter(_) => CrdtType::PNCounter,
CrdtEntry::GSet(_) => CrdtType::GSet,
CrdtEntry::ORSet(_) => CrdtType::ORSet,
CrdtEntry::AWORSet(_) => CrdtType::AWORSet,
CrdtEntry::LWWRegister(_) => CrdtType::LWWRegister,
CrdtEntry::MVRegister(_) => CrdtType::MVRegister,
CrdtEntry::RGA(_) => CrdtType::RGA,
}
}
pub fn merge_entry(&mut self, other: &CrdtEntry) -> bool {
match (self, other) {
(CrdtEntry::GCounter(a), CrdtEntry::GCounter(b)) => {
a.merge(b);
true
}
(CrdtEntry::PNCounter(a), CrdtEntry::PNCounter(b)) => {
a.merge(b);
true
}
(CrdtEntry::GSet(a), CrdtEntry::GSet(b)) => {
a.merge(b);
true
}
(CrdtEntry::ORSet(a), CrdtEntry::ORSet(b)) => {
a.merge(b);
true
}
(CrdtEntry::AWORSet(a), CrdtEntry::AWORSet(b)) => {
a.merge(b);
true
}
(CrdtEntry::LWWRegister(a), CrdtEntry::LWWRegister(b)) => {
a.merge(b);
true
}
(CrdtEntry::MVRegister(a), CrdtEntry::MVRegister(b)) => {
a.merge(b);
true
}
(CrdtEntry::RGA(a), CrdtEntry::RGA(b)) => {
a.merge(b);
true
}
_ => false,
}
}
/// Compute the delta-state of this entry relative to `base` (the state
/// last shipped to peers). Returns `None` when the entry did not change
/// since `base`. A type mismatch between `self` and `base` yields the
/// full state as a safe fallback.
pub fn delta_since(&self, base: &CrdtEntry) -> Option<CrdtEntry> {
match (self, base) {
(CrdtEntry::GCounter(a), CrdtEntry::GCounter(b)) => {
a.delta_since(b).map(CrdtEntry::GCounter)
}
(CrdtEntry::PNCounter(a), CrdtEntry::PNCounter(b)) => {
a.delta_since(b).map(CrdtEntry::PNCounter)
}
(CrdtEntry::GSet(a), CrdtEntry::GSet(b)) => a.delta_since(b).map(CrdtEntry::GSet),
(CrdtEntry::ORSet(a), CrdtEntry::ORSet(b)) => a.delta_since(b).map(CrdtEntry::ORSet),
(CrdtEntry::AWORSet(a), CrdtEntry::AWORSet(b)) => {
a.delta_since(b).map(CrdtEntry::AWORSet)
}
(CrdtEntry::LWWRegister(a), CrdtEntry::LWWRegister(b)) => {
a.delta_since(b).map(CrdtEntry::LWWRegister)
}
(CrdtEntry::MVRegister(a), CrdtEntry::MVRegister(b)) => {
a.delta_since(b).map(CrdtEntry::MVRegister)
}
(CrdtEntry::RGA(a), CrdtEntry::RGA(b)) => a.delta_since(b).map(CrdtEntry::RGA),
_ => Some(self.clone()),
}
}
/// Rewrite the replica's *local* node identity so that future local
/// operations are tagged with `node_id`. This is used when a replica is
/// created from a remote sync payload: the remote counts/tags/timestamps
/// are preserved, but new local increments/inserts must use this manager's
/// node id.
pub fn set_local_node_id(&mut self, node_id: u64) {
match self {
CrdtEntry::GCounter(c) => c.node_id = node_id,
CrdtEntry::PNCounter(c) => {
c.increments.node_id = node_id;
c.decrements.node_id = node_id;
}
CrdtEntry::ORSet(c) => {
c.node_id = node_id;
c.matrix.reroot(node_id);
}
CrdtEntry::AWORSet(c) => {
c.clock.node_id = node_id;
c.matrix.reroot(node_id);
}
CrdtEntry::LWWRegister(c) => c.clock.node_id = node_id,
CrdtEntry::MVRegister(c) => c.clock.node_id = node_id,
CrdtEntry::RGA(c) => {
c.clock.node_id = node_id;
c.matrix.reroot(node_id);
}
CrdtEntry::GSet(_) => {}
}
}
}
pub struct CrdtManager {
pub node_id: u64,
pub entries: HashMap<CrdtId, CrdtEntry>,
pub ops_synced: u64,
/// Per-entry snapshot for delta computation.
pub sync_base: HashMap<CrdtId, CrdtEntry>,
/// Maps (actor_id, field_name) → CrdtId for CRDT-backed state fields.
pub field_map: HashMap<(u64, String), CrdtId>,
/// Reverse map: CrdtId → (actor_id, field_name) for pushing merges.
pub field_reverse: HashMap<CrdtId, (u64, String)>,
}
/// Merge a serialized CRDT state (full state or delta — both are valid
/// serialized states) into `entry`. Returns `false` when the payload is
/// malformed.
pub fn merge_payload(entry: &mut CrdtEntry, payload: &[u8]) -> bool {
match entry {
CrdtEntry::GCounter(c) => GCounter::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::PNCounter(c) => PNCounter::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::GSet(c) => GSet::<String>::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::ORSet(c) => ORSet::<String>::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::AWORSet(c) => AWORSet::<String>::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::LWWRegister(c) => LWWRegister::<String>::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::MVRegister(c) => MVRegister::<String>::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
CrdtEntry::RGA(c) => RGA::<String>::from_bytes(payload)
.map(|r| {
c.merge(&r);
})
.is_some(),
}
}
impl CrdtManager {
pub fn new(node_id: u64) -> Self {
CrdtManager {
node_id,
entries: HashMap::new(),
ops_synced: 0,
sync_base: HashMap::new(),
field_map: HashMap::new(),
field_reverse: HashMap::new(),
}
}
pub fn create_gcounter(&mut self) -> (CrdtId, GCounter) {
let id = CrdtId::new(self.node_id);
let counter = GCounter::new(self.node_id);
self.entries
.insert(id, CrdtEntry::GCounter(counter.clone()));
(id, counter)
}
pub fn create_pncounter(&mut self) -> (CrdtId, PNCounter) {
let id = CrdtId::new(self.node_id);
let counter = PNCounter::new(self.node_id);
self.entries
.insert(id, CrdtEntry::PNCounter(counter.clone()));
(id, counter)
}
pub fn create_gset(&mut self) -> (CrdtId, GSet<String>) {
let id = CrdtId::new(self.node_id);
let set = GSet::new();
self.entries.insert(id, CrdtEntry::GSet(set.clone()));
(id, set)
}
pub fn create_orset(&mut self) -> (CrdtId, ORSet<String>) {
let id = CrdtId::new(self.node_id);
let set = ORSet::new(self.node_id);
self.entries.insert(id, CrdtEntry::ORSet(set.clone()));
(id, set)
}
pub fn create_aworset(&mut self) -> (CrdtId, AWORSet<String>) {
let id = CrdtId::new(self.node_id);
let set = AWORSet::new(self.node_id);
self.entries.insert(id, CrdtEntry::AWORSet(set.clone()));
(id, set)
}
pub fn create_lwwregister(&mut self, initial: String) -> (CrdtId, LWWRegister<String>) {
let id = CrdtId::new(self.node_id);
let reg = LWWRegister::new(self.node_id, initial);
self.entries.insert(id, CrdtEntry::LWWRegister(reg.clone()));
(id, reg)
}
pub fn create_mvregister(&mut self) -> (CrdtId, MVRegister<String>) {
let id = CrdtId::new(self.node_id);
let reg = MVRegister::new(self.node_id);
self.entries.insert(id, CrdtEntry::MVRegister(reg.clone()));
(id, reg)
}
pub fn create_rga(&mut self) -> (CrdtId, RGA<String>) {
let id = CrdtId::new(self.node_id);
let rga = RGA::new(self.node_id);
self.entries.insert(id, CrdtEntry::RGA(rga.clone()));
(id, rga)
}
/// Type-safe generic accessor for any CRDT entry managed by the store.
///
/// Returns `Some(&mut T)` when an entry with `id` exists and its variant
/// matches `T`, or `None` for unknown ids / type mismatches.
pub fn entry_mut<T: CrdtEntryInner>(&mut self, id: CrdtId) -> Option<&mut T> {
self.entries.get_mut(&id).and_then(T::try_from_entry)
}
pub fn get_gcounter_mut(&mut self, id: CrdtId) -> Option<&mut GCounter> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::GCounter(c)) => Some(c),
_ => None,
}
}
pub fn get_pncounter_mut(&mut self, id: CrdtId) -> Option<&mut PNCounter> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::PNCounter(c)) => Some(c),
_ => None,
}
}
pub fn get_gset_mut(&mut self, id: CrdtId) -> Option<&mut GSet<String>> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::GSet(c)) => Some(c),
_ => None,
}
}
pub fn get_orset_mut(&mut self, id: CrdtId) -> Option<&mut ORSet<String>> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::ORSet(c)) => Some(c),
_ => None,
}
}
pub fn get_aworset_mut(&mut self, id: CrdtId) -> Option<&mut AWORSet<String>> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::AWORSet(c)) => Some(c),
_ => None,
}
}
pub fn get_lwwregister_mut(&mut self, id: CrdtId) -> Option<&mut LWWRegister<String>> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::LWWRegister(c)) => Some(c),
_ => None,
}
}
pub fn get_mvregister_mut(&mut self, id: CrdtId) -> Option<&mut MVRegister<String>> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::MVRegister(c)) => Some(c),
_ => None,
}
}
pub fn get_rga_mut(&mut self, id: CrdtId) -> Option<&mut RGA<String>> {
match self.entries.get_mut(&id) {
Some(CrdtEntry::RGA(c)) => Some(c),
_ => None,
}
}
pub fn apply_op(&mut self, op: CrdtOp) {
if let Some(entry) = self.entries.get_mut(&op.crdt_id) {
// Guard against stale/misrouted ops whose declared type no longer
// matches the local replica.
if entry.crdt_type() != op.crdt_type {
return;
}
if merge_payload(entry, &op.payload) {
self.ops_synced += 1;
}
} else {
let mut entry = match op.crdt_type {
CrdtType::GCounter => GCounter::from_bytes(&op.payload).map(CrdtEntry::GCounter),
CrdtType::PNCounter => PNCounter::from_bytes(&op.payload).map(CrdtEntry::PNCounter),
CrdtType::GSet => GSet::<String>::from_bytes(&op.payload).map(CrdtEntry::GSet),
CrdtType::ORSet => ORSet::<String>::from_bytes(&op.payload).map(CrdtEntry::ORSet),
CrdtType::AWORSet => {
AWORSet::<String>::from_bytes(&op.payload).map(CrdtEntry::AWORSet)
}
CrdtType::LWWRegister => {
LWWRegister::<String>::from_bytes(&op.payload).map(CrdtEntry::LWWRegister)
}
CrdtType::MVRegister => {
MVRegister::<String>::from_bytes(&op.payload).map(CrdtEntry::MVRegister)
}
CrdtType::RGA => RGA::<String>::from_bytes(&op.payload).map(CrdtEntry::RGA),
};
if let Some(ref mut e) = entry {
e.set_local_node_id(self.node_id);
self.entries.insert(op.crdt_id, e.clone());
self.ops_synced += 1;
}
}
}
pub fn generate_sync_ops(&mut self) -> Vec<CrdtOp> {
self.entries
.iter()
.map(|(id, entry)| CrdtOp {
crdt_id: *id,
crdt_type: entry.crdt_type(),
payload: entry.payload_bytes(),
})
.collect()
}
/// Generate delta-state sync ops for all entries.
///
/// Entries without a recorded sync base (never synced before — e.g.
/// freshly created or learned during join) ship as full-state ops; all
/// others ship only the changes since the last call. Unchanged entries
/// produce no op at all. The current state becomes the new base for the
/// next round.
///
/// Convergence is identical to shipping full states: for a peer that
/// holds the base, merging the delta produces exactly the state that
/// merging the full entry would.
///
/// **Delivery assumption:** the base advances when the ops are
/// *generated*, so a delta lost in transit is not re-sent. Periodic
/// full-state syncs ([`generate_sync_ops`](CrdtManager::generate_sync_ops))
/// remain the repair mechanism after message loss.
pub fn generate_delta_sync_ops(&mut self) -> Vec<CrdtDeltaOp> {
let mut ops = Vec::new();
for (id, entry) in &self.entries {
match self.sync_base.get(id) {
None => {
// Entry never synced: ship full state and record the base.
self.sync_base.insert(*id, entry.clone());
ops.push(CrdtDeltaOp {
op: CrdtOp {
crdt_id: *id,
crdt_type: entry.crdt_type(),
payload: entry.payload_bytes(),
},
is_delta: false,
});
}
Some(base) => {
if let Some(delta) = entry.delta_since(base) {
// Entry changed since last sync: ship delta and advance base.
self.sync_base.insert(*id, entry.clone());
ops.push(CrdtDeltaOp {
op: CrdtOp {
crdt_id: *id,
crdt_type: delta.crdt_type(),
payload: delta.payload_bytes(),
},
is_delta: true,
});
}
// Unchanged: no op, no base update — avoids wasteful clone.
}
}
}
ops
}
/// Generate op-based sync ops for all entries.
///
/// Mirrors [`generate_delta_sync_ops`](CrdtManager::generate_delta_sync_ops)
/// but returns individual [`CrdtOp`]s rather than delta-tagged ops —
/// each op is shipped as its own `Packet::CrdtOp` for the lowest-bandwidth
/// replication path. The sync base advances at generation, and the
/// periodic full-state syncs remain the repair mechanism after message
/// loss.
pub fn generate_op_syncs(&mut self) -> Vec<CrdtOp> {
let mut ops = Vec::new();
for (id, entry) in &self.entries {
match self.sync_base.get(id) {
None => {
// Entry never synced: ship full state and record the base.
self.sync_base.insert(*id, entry.clone());
ops.push(CrdtOp {
crdt_id: *id,
crdt_type: entry.crdt_type(),
payload: entry.payload_bytes(),
});
}
Some(base) => {
if let Some(delta) = entry.delta_since(base) {
// Entry changed since last sync: ship delta and advance base.
self.sync_base.insert(*id, entry.clone());
ops.push(CrdtOp {
crdt_id: *id,
crdt_type: delta.crdt_type(),
payload: delta.payload_bytes(),
});
}
// Unchanged: no op.
}
}
}
ops
}
/// Serialize all entries into a snapshot suitable for persistence.
pub fn snapshot(&self) -> HashMap<CrdtId, (CrdtType, Vec<u8>)> {
self.entries
.iter()
.map(|(id, entry)| (*id, (entry.crdt_type(), entry.payload_bytes())))
.collect()
}
/// Restore CRDT state from a previously saved snapshot.
pub fn restore(&mut self, snapshot: HashMap<CrdtId, (CrdtType, Vec<u8>)>) {
for (id, (crdt_type, bytes)) in snapshot {
let mut entry: Option<CrdtEntry> = match crdt_type {
CrdtType::GCounter => GCounter::from_bytes(&bytes).map(CrdtEntry::GCounter),
CrdtType::PNCounter => PNCounter::from_bytes(&bytes).map(CrdtEntry::PNCounter),
CrdtType::GSet => GSet::<String>::from_bytes(&bytes).map(CrdtEntry::GSet),
CrdtType::ORSet => ORSet::<String>::from_bytes(&bytes).map(CrdtEntry::ORSet),
CrdtType::AWORSet => AWORSet::<String>::from_bytes(&bytes).map(CrdtEntry::AWORSet),
CrdtType::LWWRegister => {
LWWRegister::<String>::from_bytes(&bytes).map(CrdtEntry::LWWRegister)
}
CrdtType::MVRegister => {
MVRegister::<String>::from_bytes(&bytes).map(CrdtEntry::MVRegister)
}
CrdtType::RGA => RGA::<String>::from_bytes(&bytes).map(CrdtEntry::RGA),
};
if let Some(ref mut e) = entry {
e.set_local_node_id(self.node_id);
self.entries.insert(id, e.clone());
}
}
}
/// Apply a delta-tagged sync op received from a peer.
///
/// Full-state ops behave exactly like [`apply_op`](CrdtManager::apply_op)
/// (including creating the entry on first sight). Delta ops only merge
/// into an entry this manager already has: a delta is meaningless
/// without the base it was computed against, so unknown ids are ignored
/// — the entry will arrive via a full-state op (the join fallback).
pub fn apply_delta_op(&mut self, delta_op: CrdtDeltaOp) {
if !delta_op.is_delta {
self.apply_op(delta_op.op);
return;
}
let op = delta_op.op;
if let Some(entry) = self.entries.get_mut(&op.crdt_id) {
// Same staleness guard as apply_op.
if entry.crdt_type() != op.crdt_type {
return;
}
if merge_payload(entry, &op.payload) {
self.ops_synced += 1;
}
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn ops_synced(&self) -> u64 {
self.ops_synced
}
/// Register a CRDT-backed state field for an actor.
///
/// Creates a CRDT entry of the given type initialized from `initial_value`,
/// and records the mapping so merges can be pushed back to the actor.
pub fn register_actor_field(
&mut self,
actor_id: u64,
field_name: &str,
crdt_type: CrdtType,
initial_value: crate::vm::Value,
) {
let id = CrdtId::new(self.node_id);
let initial_i64 = initial_value.as_int().unwrap_or(0);
let entry = match crdt_type {
CrdtType::GCounter => {
let mut c = GCounter::new(self.node_id);
for _ in 0..initial_i64 {
c.increment();
}
CrdtEntry::GCounter(c)
}
CrdtType::PNCounter => {
let mut c = PNCounter::new(self.node_id);
for _ in 0..initial_i64 {
c.increment();
}
CrdtEntry::PNCounter(c)
}
CrdtType::GSet => CrdtEntry::GSet(GSet::new()),
CrdtType::ORSet => CrdtEntry::ORSet(ORSet::new(self.node_id)),
CrdtType::AWORSet => CrdtEntry::AWORSet(AWORSet::new(self.node_id)),
CrdtType::LWWRegister => {
CrdtEntry::LWWRegister(LWWRegister::new(self.node_id, String::new()))
}
CrdtType::MVRegister => CrdtEntry::MVRegister(MVRegister::new(self.node_id)),
CrdtType::RGA => CrdtEntry::RGA(RGA::new(self.node_id)),
};
let key = (actor_id, field_name.to_string());
self.entries.insert(id, entry);
self.field_map.insert(key.clone(), id);
self.field_reverse.insert(id, key);
}
/// Get the CRDT ID for a specific actor field, if registered.
pub fn get_field_id(&self, actor_id: u64, field_name: &str) -> Option<CrdtId> {
self.field_map
.get(&(actor_id, field_name.to_string()))
.copied()
}
/// Get a mutable reference to a CRDT entry by actor ID and field name.
pub fn get_field_mut<T: CrdtEntryInner>(
&mut self,
actor_id: u64,
field_name: &str,
) -> Option<&mut T> {
self.get_field_id(actor_id, field_name)
.and_then(|id| self.entries.get_mut(&id))
.and_then(|e| T::try_from_entry(e))
}
/// Garbage-collect tombstones that are causally stable.
///
/// A tombstone (ORSet/AWORSet removal, RGA deletion) is dropped once
/// every healthy replica — plus the local node — has observed it, as
/// established by the per-CRDT [`MatrixClock`](crate::runtime::crdt::MatrixClock)
/// embedded in each entry. `healthy` lists the peer node ids; the local
/// replica is always considered. A healthy peer that has not (yet)
/// acknowledged an entry's removals blocks GC, so no element can be
/// resurrected by a replica that never observed the removal. Rows for
/// departed peers are pruned so the clock does not grow unboundedly as
/// nodes churn.
///
/// With no peers (`healthy` empty) the watermark collapses to the local
/// replica's own observation: everything it holds is trivially stable, so
/// tombstones are reclaimed for standalone use too.
pub fn gc_stable_tombstones(&mut self, healthy: &[u64]) {
let mut healthy = healthy.to_vec();
if !healthy.contains(&self.node_id) {
healthy.push(self.node_id);
}
for entry in self.entries.values_mut() {
match entry {
CrdtEntry::ORSet(s) => {
s.matrix.prune(&healthy);
let wm = s.matrix.watermark(&healthy);
s.gc_tombstones(&wm);
}
CrdtEntry::AWORSet(s) => {
s.matrix.prune(&healthy);
let wm = s.matrix.watermark(&healthy);
s.gc_tombstones(&wm);
}
CrdtEntry::RGA(s) => {
s.matrix.prune(&healthy);
let wm = s.matrix.watermark(&healthy);
s.gc_tombstones(&wm);
}
_ => {}
}
}
}
/// Push merged CRDT values back to actor state fields.
///
/// After a sync round, call this to update actor state with the
/// latest merged CRDT values. Only fields whose CRDT entry has
/// changed (differs from the sync base) are updated.
pub fn push_to_actors(&self, runtime: &mut crate::runtime::Runtime) {
for (id, entry) in &self.entries {
if let Some(&(actor_id, ref field_name)) = self.field_reverse.get(id) {
let value = match entry {
CrdtEntry::GCounter(c) => crate::vm::Value::int(c.value() as i64),
CrdtEntry::PNCounter(c) => crate::vm::Value::int(c.value() as i64),
_ => crate::vm::Value::int(0), // Other types: placeholder
};
if let Some(actor) = runtime.actors.get_mut(&actor_id) {
actor.set_state_field(field_name.clone(), value);
}
}
}
}
}
// ===========================================================================
// Tests
// ===========================================================================
#[cfg(test)]
mod tests {
use super::*;
/// Apply every generated sync op from `source` to `target`.
fn sync_all(source: &mut CrdtManager, target: &mut CrdtManager) {
let ops = source.generate_sync_ops();
for op in ops {
target.apply_op(op);
}
}
// -----------------------------------------------------------------------
// Convergence happy paths
// -----------------------------------------------------------------------
#[test]
fn test_gcounter_convergence() {
let mut a = CrdtManager::new(1);
let mut b = CrdtManager::new(2);
let id = {
let (id, mut counter) = a.create_gcounter();
counter.increment_by(3);
a.entries.insert(id, CrdtEntry::GCounter(counter));
id
};
// B learns the CRDT from A's sync ops.
sync_all(&mut a, &mut b);
assert_eq!(b.len(), 1);
// Divergent updates.
a.get_gcounter_mut(id).unwrap().increment_by(2);
b.get_gcounter_mut(id).unwrap().increment_by(5);
// Exchange ops both ways.
sync_all(&mut a, &mut b);
sync_all(&mut b, &mut a);
assert_eq!(
a.get_gcounter_mut(id).unwrap().value(),
b.get_gcounter_mut(id).unwrap().value()
);
assert_eq!(a.get_gcounter_mut(id).unwrap().value(), 10);
}
#[test]
fn test_pncounter_convergence() {
let mut a = CrdtManager::new(1);
let mut b = CrdtManager::new(2);
let id = {
let (id, mut counter) = a.create_pncounter();
counter.increment_by(4);
a.entries.insert(id, CrdtEntry::PNCounter(counter));
id
};
sync_all(&mut a, &mut b);
a.get_pncounter_mut(id).unwrap().increment_by(3);
b.get_pncounter_mut(id).unwrap().decrement_by(2);
sync_all(&mut a, &mut b);
sync_all(&mut b, &mut a);
assert_eq!(
a.get_pncounter_mut(id).unwrap().value(),
b.get_pncounter_mut(id).unwrap().value()
);
assert_eq!(a.get_pncounter_mut(id).unwrap().value(), 5);
}
#[test]
fn test_orset_convergence() {
let mut a = CrdtManager::new(1);
let mut b = CrdtManager::new(2);
let id = {
let (id, mut set) = a.create_orset();
set.add("apple".to_string());
a.entries.insert(id, CrdtEntry::ORSet(set));
id
};
sync_all(&mut a, &mut b);
a.get_orset_mut(id).unwrap().add("banana".to_string());
b.get_orset_mut(id).unwrap().add("cherry".to_string());
sync_all(&mut a, &mut b);
sync_all(&mut b, &mut a);
let va = a.get_orset_mut(id).unwrap().value();
let vb = b.get_orset_mut(id).unwrap().value();
assert_eq!(va, vb);
assert!(va.contains("apple"));
assert!(va.contains("banana"));
assert!(va.contains("cherry"));
}
#[test]
fn test_lwwregister_convergence() {
let mut a = CrdtManager::new(1);
let mut b = CrdtManager::new(2);
let id = {
let (id, reg) = a.create_lwwregister("initial".to_string());
a.entries.insert(id, CrdtEntry::LWWRegister(reg));
id
};
sync_all(&mut a, &mut b);
a.get_lwwregister_mut(id)
.unwrap()
.write("A-wins".to_string());
b.get_lwwregister_mut(id)
.unwrap()
.write("B-loses".to_string());
sync_all(&mut a, &mut b);
sync_all(&mut b, &mut a);
let va = a.get_lwwregister_mut(id).unwrap().value();
let vb = b.get_lwwregister_mut(id).unwrap().value();
assert_eq!(va, vb);
// One of the two writes wins deterministically by Lamport timestamp.
assert!(va == "A-wins" || va == "B-loses");
}
#[test]
fn test_rga_convergence() {
let mut a = CrdtManager::new(1);
let mut b = CrdtManager::new(2);
let id = {
let (id, rga) = a.create_rga();
a.entries.insert(id, CrdtEntry::RGA(rga));
id
};
sync_all(&mut a, &mut b);
a.get_rga_mut(id).unwrap().insert_at(0, "first".to_string());
b.get_rga_mut(id)
.unwrap()
.insert_at(0, "second".to_string());
sync_all(&mut a, &mut b);
sync_all(&mut b, &mut a);
let va = a.get_rga_mut(id).unwrap().value();
let vb = b.get_rga_mut(id).unwrap().value();
assert_eq!(va, vb);
assert_eq!(va.len(), 2);
assert!(va.contains(&"first".to_string()));
assert!(va.contains(&"second".to_string()));
}