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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
|
//! Shared node state: the document, lifecycle, per-peer state and timing.
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use anyhow::{Result, bail};
use automerge::{AutoCommit, ChangeHash, sync};
use tokio::sync::{Mutex, RwLock, broadcast, mpsc, watch};
use tokio::time::Instant;
use tracing::{debug, error, warn};
use crate::document::replica::{Epoch, Replica};
use crate::remake::{Host, PeerSummary, RemakeState};
use crate::swarm::sync::{ChangeSet, SyncEvent};
use crate::transport;
use crate::transport::firewall::Firewall;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum NodeLifecycle {
// TODO maybe rename discovered_swarm_id to swarm_id if that doesn't impair readability.
Joining { discovered_swarm_id: Option<String> },
Ready { swarm_id: String },
}
/// How far a peer got into the swarm, as far as we're concerned.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum Standing {
/// Nothing proven yet. With a swarm key, everything but a handshake from it is
/// ignored (`swarm::peer::admit`).
#[default]
Stranger,
/// Proved the swarm key in a HELLO; no HELLO_REPLY yet. Only reached with a key.
Admitted,
/// Its HELLO_REPLY named our swarm (and, with a key, proved it): we sync with it.
Member { swarm_id: String },
}
impl Standing {
/// The swarm a member belongs to; None before its HELLO_REPLY.
pub(crate) fn swarm_id(&self) -> Option<&str> {
match self {
Self::Member { swarm_id } => Some(swarm_id),
Self::Stranger | Self::Admitted => None,
}
}
/// Proved the swarm key (meaningful only with one).
pub(crate) fn is_admitted(&self) -> bool {
!matches!(self, Self::Stranger)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Liveness {
Active,
/// No inbound message for Timing::dormant_after. Kept indefinitely, probed slowly.
Dormant {
since: Instant,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum HelloState {
#[default]
NotSent,
/// A send is in flight. `next_delay` is how long to wait after it before retrying.
Sending { next_delay: Duration },
/// HELLO was sent (or the send failed); no HELLO_REPLY yet.
AwaitingReply {
next_attempt: Instant,
next_delay: Duration,
},
/// HELLO_REPLY received. No more retries.
Established,
}
#[derive(Clone)]
pub(crate) struct PendingOutbound {
pub(crate) message: transport::EncodedMessage,
pub(crate) retry_delay: Duration,
pub(crate) next_attempt: Instant,
/// A sync pass was requested while this was pending. Once it is delivered, the peer
/// must be enqueued again so the deferred changes go out.
pub(crate) regenerate: bool,
}
#[derive(Clone)]
pub(crate) struct PeerState {
/// Whether we lead the pair (`swarm::pair`): we open sync after a reset and send the
/// keepalive PINGs. Fixed for the pair, so computed once.
pub(crate) leads: bool,
pub(crate) standing: Standing,
pub(crate) hello_state: HelloState,
/// The peer sent HELLO; we still owe it a HELLO_REPLY (e.g. we had no swarm ID yet,
/// or sending failed).
pub(crate) reply_owed: bool,
/// Received from this peer before it became a member, waiting to be processed.
pub(crate) pending_inbound_sync: Vec<transport::SyncEnvelope>,
/// Everything about the current Automerge sync with this peer; a reset replaces it.
pub(crate) sync: SyncSession,
pub(crate) liveness: Liveness,
pub(crate) added_at: Instant,
pub(crate) last_seen: Option<Instant>,
pub(crate) last_ping_at: Option<Instant>,
/// Last time a sync message from this peer was applied (survives resets: the
/// keepalive heal looks at it).
pub(crate) last_sync_rx: Option<Instant>,
/// Last self-healing re-handshake (cooldown).
pub(crate) last_resync_at: Option<Instant>,
/// Epoch the peer advertised in its most recent message.
pub(crate) epoch: Option<Epoch>,
/// Whether the peer was ready according to its most recent sync message or keepalive.
pub(crate) reports_ready: Option<bool>,
/// Whether the peer said, in its most recent keepalive, that it would sync with us.
pub(crate) syncs_with_us: Option<bool>,
}
/// One Automerge sync with a peer, from a reset to the next. Everything a reset must
/// forget lives here, so a reset replaces it whole and can't miss a field.
#[derive(Clone)]
pub(crate) struct SyncSession {
pub(crate) state: sync::State,
/// Generated for this peer, waiting for delivery.
pub(crate) outbound: Option<PendingOutbound>,
/// The answer we expect to our last sync message(s), if any.
pub(crate) reply: Option<SyncReplyWait>,
/// How long to wait for it; doubles while answers stay out.
pub(crate) reply_timeout: Duration,
/// Who sends the first message of this session.
pub(crate) opening: Opening,
/// What started this session.
pub(crate) cause: SessionCause,
/// Consecutive exchanges that changed nothing (livelock detection).
pub(crate) stalled_exchanges: u32,
}
/// Who opens a sync session. After a reset, usually both sides do it and both would
/// open at once. The openings cross, and each side answers the other's: harmless between
/// peers that share history, but an empty peer answers with empty heads, which Automerge
/// takes for "lost everything", so the whole document goes out a second time. So only
/// the side that leads the pair opens.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Opening {
/// We open: we lead the pair.
Ours,
/// We open, leader or not: we just switched epochs, and the peer, already on our new
/// epoch, still has our old one on record. It won't sync with us until a message
/// tells it otherwise, and our opening does (no epoch announcement PING needed).
/// Survives resets until the peer has answered, since only then do we know it
/// learned our epoch.
Announce,
/// The peer opens. If nothing came by `until`, we open anyway: the peer may not have
/// reset, or its opening got lost.
Theirs { until: Instant },
}
/// What started a sync session. Kept for the log: when the peer doesn't open within the
/// grace period, the cause usually tells why.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SessionCause {
/// First session with a peer we just learned about.
NewPeer,
/// The peer sent HELLO: it (re)started its handshake with us.
PeerHello,
/// Its HELLO_REPLY completed our handshake.
HandshakeComplete,
/// The peer advertised another epoch than before.
PeerEpochChanged,
/// We switched epochs.
OwnEpochSwitch,
/// The peer went dormant.
PeerDormant,
/// The peer failed the swarm key check.
KeyRejected,
}
impl SessionCause {
/// The likely reason the peer didn't open a session started this way.
pub(crate) fn missing_opening_hint(self) -> &'static str {
match self {
Self::NewPeer | Self::PeerHello | Self::HandshakeComplete => {
"the peer may not count us as a member yet (our HELLO_REPLY hasn't reached it), \
or its opening was lost"
}
Self::PeerEpochChanged => {
"the peer switched epochs but doesn't know we're on its new one yet, or its \
opening was lost"
}
Self::OwnEpochSwitch => {
"we switched epochs; the peer opens only once it learns that, and it may not \
have yet"
}
Self::PeerDormant | Self::KeyRejected => {
"only our side reset, so the peer had no reason to open"
}
}
}
}
/// Sync messages we sent and expect an answer to. Automerge assumes reliable delivery:
/// a lost message leaves both sides waiting (`in_flight`), and changes it carried are
/// never sent again (`sent_hashes`). We resend after a timeout instead.
#[derive(Clone, Debug)]
pub(crate) struct SyncReplyWait {
pub(crate) deadline: Instant,
/// Changes first sent in the unanswered messages.
pub(crate) sent: Vec<automerge::ChangeHash>,
}
/// First wait for a sync answer; generous, since Mycelium delivers large messages in
/// many small packets.
const SYNC_REPLY_TIMEOUT: Duration = Duration::from_secs(10);
/// Upper bound (Mycelium gives up on a message after five minutes).
const SYNC_REPLY_TIMEOUT_MAX: Duration = Duration::from_secs(300);
/// How long the side that doesn't open a fresh sync waits for the other's opening
/// before opening itself (the other one may not have reset, or its message got lost).
const SYNC_OPENING_GRACE: Duration = Duration::from_secs(3);
impl SyncSession {
pub(crate) fn new(leads: bool, cause: SessionCause) -> Self {
Self {
cause,
state: sync::State::new(),
outbound: None,
reply: None,
reply_timeout: SYNC_REPLY_TIMEOUT,
opening: if leads {
Opening::Ours
} else {
Opening::Theirs {
until: Instant::now() + SYNC_OPENING_GRACE,
}
},
stalled_exchanges: 0,
}
}
/// How much longer to hold back our opening, if at all. Only the first message
/// counts: once the peer has said anything, we answer as usual.
pub(crate) fn opening_wait(&self, now: Instant) -> Option<Duration> {
if self.state.their_heads.is_some() {
return None;
}
match self.opening {
Opening::Ours | Opening::Announce => None,
Opening::Theirs { until } => until
.checked_duration_since(now)
.filter(|wait| !wait.is_zero()),
}
}
/// The peer should have opened by now but hasn't said anything: we open ourselves.
pub(crate) fn opening_overdue(&self, now: Instant) -> bool {
self.state.their_heads.is_none()
&& matches!(self.opening, Opening::Theirs { until } if until <= now)
}
/// A sync message went out; `sent` are the changes it carried for the first time.
pub(crate) fn expect_reply(&mut self, sent: Vec<automerge::ChangeHash>, now: Instant) {
match &mut self.reply {
// Still waiting for an earlier one: keep its deadline, remember these too.
Some(wait) => wait.sent.extend(sent),
None => {
self.reply = Some(SyncReplyWait {
deadline: now + self.reply_timeout,
sent,
});
}
}
}
/// No answer is due any more: the peer answered, or keepalives show both documents
/// are the same.
pub(crate) fn reply_settled(&mut self) {
self.reply = None;
self.reply_timeout = SYNC_REPLY_TIMEOUT;
}
/// If the answer is overdue: forgets that the unanswered changes were sent and that
/// a message is in flight, so the next sync pass sends them again. Returns how many
/// changes that concerns.
fn take_overdue_reply(&mut self, now: Instant) -> Option<usize> {
if self.reply.as_ref().is_none_or(|wait| now < wait.deadline) {
return None;
}
let wait = self.reply.take()?;
for hash in &wait.sent {
self.state.sent_hashes.remove(hash);
}
self.state.in_flight = false;
self.reply_timeout = (self.reply_timeout * 2).min(SYNC_REPLY_TIMEOUT_MAX);
Some(wait.sent.len())
}
}
impl PeerState {
pub(crate) fn new(leads: bool) -> Self {
Self {
leads,
standing: Standing::default(),
hello_state: HelloState::default(),
reply_owed: false,
pending_inbound_sync: Vec::new(),
sync: SyncSession::new(leads, SessionCause::NewPeer),
liveness: Liveness::Active,
added_at: Instant::now(),
last_seen: None,
last_ping_at: None,
last_sync_rx: None,
last_resync_at: None,
epoch: None,
reports_ready: None,
syncs_with_us: None,
}
}
/// Start Automerge sync with this peer from scratch. Any envelope generated against
/// the old state is discarded; a stale RetryDelivery event is then a no-op.
pub(crate) fn reset_sync(&mut self, cause: SessionCause) {
let announce =
self.sync.opening == Opening::Announce && self.sync.state.their_heads.is_none();
self.sync = SyncSession::new(self.leads, cause);
if announce {
self.sync.opening = Opening::Announce;
}
}
/// An overdue sync answer from an established, active peer (see
/// `SyncSession::take_overdue_reply`).
pub(crate) fn take_overdue_sync_reply(&mut self, now: Instant) -> Option<usize> {
if self.liveness != Liveness::Active || self.hello_state != HelloState::Established {
return None;
}
self.sync.take_overdue_reply(now)
}
fn quiet_for(&self, now: Instant) -> Duration {
now.saturating_duration_since(self.last_seen.unwrap_or(self.added_at))
}
/// Records inbound activity. Returns true if the peer was dormant.
pub(crate) fn mark_seen(&mut self, now: Instant) -> bool {
self.last_seen = Some(now);
if matches!(self.liveness, Liveness::Dormant { .. }) {
self.liveness = Liveness::Active;
// Force a fresh handshake; its reply resets sync on both sides.
if !matches!(self.hello_state, HelloState::Sending { .. }) {
self.hello_state = HelloState::NotSent;
}
return true;
}
false
}
/// Moves a silent peer to Dormant. Returns true on the transition.
pub(crate) fn check_dormancy(&mut self, timing: &Timing, now: Instant) -> bool {
if self.liveness != Liveness::Active || self.quiet_for(now) < timing.dormant_after {
return false;
}
self.liveness = Liveness::Dormant { since: now };
self.reset_sync(SessionCause::PeerDormant);
if !matches!(self.hello_state, HelloState::Sending { .. }) {
self.hello_state = HelloState::AwaitingReply {
next_attempt: now + timing.dormant_probe,
next_delay: timing.dormant_probe,
};
}
true
}
/// True (and records the ping) if an established, quiet peer needs a keepalive.
///
/// One PING and its PONG tell both sides that the other is alive, so only one side of
/// a pair needs to ping: the one leading the pair (`leads`). Each of its PINGs
/// makes the other side's peer look recently heard from, so the other side never
/// pings while it does. If the pings stop, the other side pings once it has heard
/// nothing for half an interval more. Without that, both sides would get due at about
/// the same time (each one's quiet time starts with the same exchange) and their
/// PINGs would often cross.
pub(crate) fn take_keepalive_due(&mut self, timing: &Timing, now: Instant) -> bool {
let quiet_enough = if self.leads {
timing.keepalive
} else {
timing.keepalive + timing.keepalive / 2
};
let due = self.liveness == Liveness::Active
&& self.hello_state == HelloState::Established
&& now.saturating_duration_since(self.added_at) >= timing.keepalive
&& self.quiet_for(now) >= quiet_enough
&& self
.last_ping_at
.is_none_or(|t| now.saturating_duration_since(t) >= timing.keepalive);
if due {
self.last_ping_at = Some(now);
}
due
}
/// Schedules a fresh handshake, which resets sync on both sides: the peer resets on
/// our HELLO, we reset on its reply. The peer worker sends the HELLO on its next tick.
/// Usable without awaiting (e.g. under a blocking lock).
pub(crate) fn request_resync(&mut self) {
if matches!(self.hello_state, HelloState::Sending { .. }) {
return; // a HELLO is already on its way
}
self.hello_state = HelloState::AwaitingReply {
next_attempt: Instant::now(),
next_delay: Duration::from_millis(500),
};
}
/// Self-healing check on PING/PONG. Returns true if a re-handshake should start.
pub(crate) fn needs_heal(
&mut self,
local: &transport::HeadsSummary,
remote: &transport::HeadsSummary,
timing: &Timing,
now: Instant,
) -> bool {
if local == remote
|| self.liveness != Liveness::Active
|| self.hello_state != HelloState::Established
{
return false;
}
let sync_idle = now.saturating_duration_since(self.last_sync_rx.unwrap_or(self.added_at))
>= timing.resync_after;
let cooled_down = self
.last_resync_at
.is_none_or(|t| now.saturating_duration_since(t) >= timing.resync_after);
if !(sync_idle && cooled_down) {
return false;
}
self.last_resync_at = Some(now);
self.hello_state = HelloState::NotSent; // establish_peer resets sync on the reply
true
}
/// Heard from recently. A returning node counts as alive from its first message,
/// before the handshake finishes, so a swarm-wide forget can't make it flap.
pub(crate) fn is_alive(&self, timing: &Timing, now: Instant) -> bool {
self.liveness == Liveness::Active
&& self
.last_seen
.is_some_and(|t| now.saturating_duration_since(t) < timing.dormant_after)
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Timing {
pub(crate) keepalive: Duration,
pub(crate) dormant_after: Duration,
pub(crate) resync_after: Duration,
pub(crate) dormant_probe: Duration,
/// While catching up: PING the source after this much silence (`swarm::source`).
pub(crate) catch_up_probe: Duration,
}
impl Timing {
// Recommended values
// Environment | Keepalive | Notes
// --------------------------------------------+-----------+------------------------------------------------------------
// Test harness | 1-2 s | Dormancy after about 4–8 s and healing within seconds keep tests short.
// LAN or small swarm (up to ~50 nodes) | 15-30 s | Under 3.5 messages/s per node at 50 nodes and 30 s. Current setting.
// WAN, mobile or metered links, or 100+ nodes | 60-120 s | At 100 nodes and 30 s it’s about 6–7 messages/s per node. Fine, but rarely worth it on battery or metered links.
// Several hundred nodes or more | - | The full mesh becomes the problem in itself, not the interval. Message counts grow O(N²) across the swarm, which calls for partial views (SWIM-style random probing and syncing with a subset of peers).
pub(crate) fn from_keepalive(keepalive: Duration) -> Self {
Self {
keepalive,
dormant_after: keepalive * 4, // dormant_after >= 4* keepalive to tolerate three lost PINGs in a row
resync_after: keepalive * 2, // resync_after should be >= 2* keepalive to guarantee at least one digest exchange while sync is idle
dormant_probe: keepalive * 10, // >= 10*: dormant peers cost almost nothing, but still rejoin within minutes
// Seconds, not a keepalive interval: a dead source should cost little time.
// Only the source gets these, and only while catching up.
catch_up_probe: (keepalive / 30).clamp(Duration::from_secs(1), Duration::from_secs(5)),
}
}
}
#[derive(Clone)]
pub(crate) struct AppState {
/// The document and its epoch. Derefs to `AutoCommit`.
pub(crate) doc: Arc<RwLock<Replica>>,
/// Copy of `doc.epoch` for cheap, lock-free reads (handshakes, keepalives, /peers).
/// Only ever changed while holding `doc`'s write lock, together with `doc.epoch`.
pub(crate) epoch_tx: watch::Sender<Epoch>,
pub(crate) lifecycle: Arc<RwLock<NodeLifecycle>>,
// Serializes swarm-ID establishment, peer membership, and readiness transitions.
//[concurrent]swarm_validation: Arc<Mutex<()>>,
pub(crate) peer_states: Arc<RwLock<HashMap<String, Arc<Mutex<PeerState>>>>>,
pub(crate) transport: Arc<dyn transport::Transport>,
pub(crate) firewall: Arc<Firewall>,
pub(crate) sync_events: mpsc::UnboundedSender<SyncEvent>,
// TODO see key_watchers.md ("Use a per-key notification registry instead of the global `watch<u64>`")
pub(crate) change_tx: watch::Sender<u64>,
pub(crate) initial_sync_done: Arc<AtomicBool>,
pub(crate) change_events: broadcast::Sender<Arc<ChangeSet>>,
pub(crate) timing: Timing,
/// Per-node remake state (prebuilt snapshots, switch status, archive).
pub(crate) remake: Arc<RemakeState>,
/// Pre-shared key every member must prove in the handshake; None admits anyone who
/// knows the swarm ID.
pub(crate) swarm_key: Option<Arc<crate::swarm::auth::SwarmKey>>,
/// While rejoining a newer epoch, the previous document, served read-only (and
/// marked stale) instead of answering 503.
pub(crate) stale: Arc<std::sync::RwLock<Option<StaleView>>>,
/// While the initial sync isn't done: the one peer we catch up from.
pub(crate) catch_up_source: Arc<std::sync::Mutex<Option<CatchUpSource>>>,
}
/// The peer a catching-up node syncs with first (`swarm::source`).
#[derive(Clone, Debug)]
pub(crate) struct CatchUpSource {
pub(crate) peer: String,
/// When it was chosen or last sent us anything.
pub(crate) last_heard: Instant,
/// Our last probe PING to it.
pub(crate) last_probe: Option<Instant>,
/// Its keepalives in a row saying it wouldn't sync with us.
pub(crate) refusals: u32,
}
impl AppState {
pub(crate) fn local_id(&self) -> &str {
self.transport.local_id()
}
/// The local epoch. Code that labels or applies sync messages must use the epoch
/// of the locked `Replica` instead, so label and document can't disagree.
pub(crate) fn local_epoch(&self) -> Epoch {
*self.epoch_tx.borrow()
}
pub(crate) async fn is_ready(&self) -> bool {
matches!(*self.lifecycle.read().await, NodeLifecycle::Ready { .. })
}
pub(crate) async fn swarm_id(&self) -> Option<String> {
match &*self.lifecycle.read().await {
NodeLifecycle::Ready { swarm_id } => Some(swarm_id.clone()),
NodeLifecycle::Joining {
discovered_swarm_id,
} => discovered_swarm_id.clone(),
}
}
// Record the expected swarm without making the node Ready. Bootstrap owns readiness.
pub(crate) async fn set_expected_swarm_id(&self, swarm_id: String) -> Result<()> {
//[concurrent]let _guard = self.swarm_validation.lock().await;
let mut lifecycle = self.lifecycle.write().await;
match &*lifecycle {
NodeLifecycle::Joining {
discovered_swarm_id: Some(existing),
} if existing != &swarm_id => {
bail!(
"Conflicting expected swarm IDs: expected {}, received {}",
existing,
swarm_id
);
}
NodeLifecycle::Joining {
discovered_swarm_id: None,
} => {
let old_lifecycle = lifecycle.clone();
*lifecycle = NodeLifecycle::Joining {
discovered_swarm_id: Some(swarm_id),
};
debug!("Node transitioned from {old_lifecycle:?} {lifecycle:?}");
Ok(())
}
NodeLifecycle::Joining {
discovered_swarm_id: Some(_),
} => {
warn!("Node already Joining with the same identity");
Ok(())
}
NodeLifecycle::Ready { swarm_id: existing } if existing == &swarm_id => {
warn!("Node already Ready with the same identity");
Ok(())
}
NodeLifecycle::Ready { swarm_id: existing } => {
bail!(
"Cannot change established swarm ID: existing {}, received {}",
existing,
swarm_id
);
}
}
}
// Only bootstrap should call this, after validating document metadata.
pub(crate) async fn mark_ready(&self, swarm_id: String) -> Result<()> {
//[concurrent]let _guard = self.swarm_validation.lock().await;
let mut lifecycle = self.lifecycle.write().await;
match &*lifecycle {
NodeLifecycle::Joining {
discovered_swarm_id: Some(expected),
} if expected != &swarm_id => {
bail!(
"Cannot mark node ready: expected swarm {}, received {}",
expected,
swarm_id
);
}
NodeLifecycle::Joining { .. } => {
let old_lifecycle = lifecycle.clone();
*lifecycle = NodeLifecycle::Ready { swarm_id };
debug!("Node transitioned from {old_lifecycle:?} {lifecycle:?}");
}
NodeLifecycle::Ready { swarm_id: existing } if existing == &swarm_id => {
debug!("Node already ready with the same identity");
}
NodeLifecycle::Ready { swarm_id: existing } => {
bail!(
"Cannot change established swarm ID: existing {}, received {}",
existing,
swarm_id
);
}
}
Ok(())
}
/// Looks up a peer without creating it. Background work (sync, retries,
/// keepalives) must use this so a forgotten peer isn't resurrected.
pub(crate) async fn get_peer_state(&self, pk: &str) -> Option<Arc<Mutex<PeerState>>> {
self.peer_states.read().await.get(pk).cloned()
}
pub(crate) async fn get_or_create_peer_state(&self, pk: &str) -> Arc<Mutex<PeerState>> {
let mut peers = self.peer_states.write().await;
Arc::clone(
peers
.entry(pk.to_owned())
.or_insert_with(|| self.new_peer_state(pk)),
)
}
/// State for a peer we haven't known so far (not inserted).
pub(crate) fn new_peer_state(&self, pk: &str) -> Arc<Mutex<PeerState>> {
let leads = crate::swarm::pair::leads(self.local_id(), pk);
Arc::new(Mutex::new(PeerState::new(leads)))
}
pub(crate) fn notify_store_changed(&self) {
self.change_tx.send_modify(|version| {
*version = version.wrapping_add(1);
});
}
/// Reads the document on the blocking pool; `finish` runs after the lock is released.
pub(crate) async fn render<T, R>(
&self,
read: impl FnOnce(&AutoCommit) -> T + Send + 'static,
finish: impl FnOnce(T) -> R + Send + 'static,
) -> R
where
R: Send + 'static,
{
let doc = Arc::clone(&self.doc);
tokio::task::spawn_blocking(move || {
let data = {
let guard = doc.blocking_read();
read(&guard.doc)
};
finish(data)
})
.await
.expect("document read task panicked")
}
/// Mutates the document on the blocking pool.
pub(crate) async fn write_doc<T>(
&self,
f: impl FnOnce(&mut AutoCommit) -> T + Send + 'static,
) -> T
where
T: Send + 'static,
{
let doc = Arc::clone(&self.doc);
tokio::task::spawn_blocking(move || f(&mut doc.blocking_write().doc))
.await
.expect("document write task panicked")
}
/// Mutates the document on the blocking pool as one Automerge change, then
/// publishes it. Write and notification run in the same blocking task, so a
/// cancelled request can't leave a committed write unannounced.
pub(crate) async fn mutate_doc<T, E>(
&self,
f: impl FnOnce(&mut AutoCommit) -> Result<T, E> + Send + 'static,
) -> Result<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
let state = self.clone();
tokio::task::spawn_blocking(move || {
let result = {
let mut replica = state.doc.blocking_write();
let result = f(&mut replica.doc);
match &result {
// One API write = one Automerge change.
Ok(_) => {
replica.doc.commit();
}
// Discard partial ops (e.g. old value deleted, new one not written).
Err(_) => {
replica.doc.rollback();
}
}
result
}; // lock released before notifying
if result.is_ok() {
state.publish_change();
}
result
})
.await
.expect("document write task panicked")
}
pub(crate) fn publish_change(&self) {
self.notify_store_changed();
if let Err(error) = self.sync_events.send(SyncEvent::DocumentChanged) {
// The write is committed; failing the request would misreport it.
error!(error = %error, "Sync worker is gone; change will not be replicated");
}
}
}
impl AppState {
/// After the document was replaced: every peer's sync state refers to the old
/// document, so start over with all of them. Peers still on the old epoch are
/// skipped by the sync worker until they switch too.
async fn after_epoch_switch(&self) {
let peers: Vec<(String, Arc<Mutex<PeerState>>)> = self
.peer_states
.read()
.await
.iter()
.map(|(id, peer)| (id.clone(), Arc::clone(peer)))
.collect();
// Sync states were reset under the document lock by the swap itself.
self.publish_change();
// Tell peers about the new epoch now instead of with the next keepalive (up to a
// keepalive interval later). Peers already on it learn it from our sync opening,
// which goes out right away; everyone else gets a PING, so peers that never saw
// the commit start catching up (we don't sync with them, so nothing else would
// tell them).
let local = self.local_epoch();
let mut announce = Vec::new();
for (id, peer_state_mutex) in &peers {
let mut peer_state = peer_state_mutex.lock().await;
// What it said about syncing with us was about our old epoch.
peer_state.syncs_with_us = None;
let syncs_with_us = peer_state.liveness == Liveness::Active
&& matches!(peer_state.standing, Standing::Member { .. })
&& peer_state.epoch == Some(local);
if syncs_with_us {
peer_state.sync.opening = Opening::Announce;
} else {
announce.push(id);
}
}
for id in announce {
let keepalive = crate::swarm::peer::local_keepalive(self, id).await;
if let Err(error) = self
.transport
.send_message(id, &transport::ParsedMessage::Ping(keepalive))
.await
{
debug!(peer = %id, error = %format!("{error:#}"), "Epoch announcement failed");
}
}
for (id, _) in peers {
let _ = self.sync_events.send(SyncEvent::PeerNeedsSync(id));
}
}
}
/// A read-only view of the document the node served before it started rejoining.
pub(crate) struct StaleView {
pub(crate) epoch: Epoch,
pub(crate) doc: Arc<AutoCommit>,
}
/// Where a read was served from.
pub(crate) enum ReadSource {
Live,
/// The pre-rejoin document of this epoch.
Stale(Epoch),
}
impl AppState {
/// Renders a read for the store API: from the live document when the node is ready,
/// from the stale view while it rejoins, and otherwise `503`, or the live document
/// anyway with `unready_live`.
///
/// With `with_heads`, a live read also returns the document's heads at the moment of
/// the read (for clients that base later requests on what they read). That needs the
/// write lock, so it is opt-in. Stale reads have no heads.
pub(crate) async fn render_read<T, R>(
&self,
unready_live: bool,
with_heads: bool,
read: impl FnOnce(&AutoCommit) -> T + Send + 'static,
finish: impl FnOnce(T) -> R + Send + 'static,
) -> Result<(R, ReadSource, Option<Vec<ChangeHash>>), axum::http::StatusCode>
where
T: Send + 'static,
R: Send + 'static,
{
if self.is_ready().await {
let (rendered, heads) = self.render_live(with_heads, read, finish).await;
return Ok((rendered, ReadSource::Live, heads));
}
let stale = self
.stale
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.as_ref()
.map(|view| (view.epoch, Arc::clone(&view.doc)));
let Some((epoch, doc)) = stale else {
if unready_live {
let (rendered, heads) = self.render_live(with_heads, read, finish).await;
return Ok((rendered, ReadSource::Live, heads));
}
return Err(axum::http::StatusCode::SERVICE_UNAVAILABLE);
};
let rendered = tokio::task::spawn_blocking(move || finish(read(&doc)))
.await
.expect("document read task panicked");
Ok((rendered, ReadSource::Stale(epoch), None))
}
async fn render_live<T, R>(
&self,
with_heads: bool,
read: impl FnOnce(&AutoCommit) -> T + Send + 'static,
finish: impl FnOnce(T) -> R + Send + 'static,
) -> (R, Option<Vec<ChangeHash>>)
where
T: Send + 'static,
R: Send + 'static,
{
if !with_heads {
return (self.render(read, finish).await, None);
}
// AutoCommit::get_heads takes &mut self (it closes a pending transaction).
let (data, mut heads) = self
.write_doc(move |doc| {
let heads = doc.get_heads();
(read(doc), heads)
})
.await;
heads.sort();
let rendered = tokio::task::spawn_blocking(move || finish(data))
.await
.expect("document read task panicked");
(rendered, Some(heads))
}
fn set_stale(&self, view: Option<StaleView>) {
*self
.stale
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = view;
}
}
pub(crate) fn unix_millis() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
/// The node as seen by the remake module.
impl Host for AppState {
fn remake(&self) -> &RemakeState {
&self.remake
}
fn node_id(&self) -> String {
self.local_id().to_owned()
}
fn current_epoch(&self) -> Epoch {
self.local_epoch()
}
fn dormant_after(&self) -> Duration {
self.timing.dormant_after
}
fn is_node_ready(&self) -> impl Future<Output = bool> + Send {
let state = self.clone();
async move { state.is_ready().await }
}
fn peer_summaries(&self) -> impl Future<Output = Vec<PeerSummary>> + Send {
let state = self.clone();
async move {
let peers: Vec<(String, Arc<Mutex<PeerState>>)> = state
.peer_states
.read()
.await
.iter()
.map(|(id, peer)| (id.clone(), Arc::clone(peer)))
.collect();
let mut summaries = Vec::with_capacity(peers.len());
for (id, peer) in peers {
let peer = peer.lock().await;
summaries.push(PeerSummary {
id,
active: peer.liveness == Liveness::Active,
epoch: peer.epoch,
});
}
summaries
}
}
fn suspend(&self) -> impl Future<Output = bool> + Send {
let state = self.clone();
async move {
let mut lifecycle = state.lifecycle.write().await;
let NodeLifecycle::Ready { swarm_id } = &*lifecycle else {
return false;
};
let swarm_id = swarm_id.clone();
debug!(swarm_id = %swarm_id, "Node suspended (rejoining)");
*lifecycle = NodeLifecycle::Joining {
discovered_swarm_id: Some(swarm_id),
};
true
}
}
fn resume(&self) -> impl Future<Output = ()> + Send {
let state = self.clone();
async move {
let mut lifecycle = state.lifecycle.write().await;
if let NodeLifecycle::Joining {
discovered_swarm_id: Some(swarm_id),
} = &*lifecycle
{
let swarm_id = swarm_id.clone();
debug!(swarm_id = %swarm_id, "Node resumed");
*lifecycle = NodeLifecycle::Ready { swarm_id };
}
}
}
fn set_stale_view(&self, view: Option<(Epoch, AutoCommit)>) {
self.set_stale(view.map(|(epoch, doc)| StaleView {
epoch,
doc: Arc::new(doc),
}));
}
fn initial_sync_done(&self) -> bool {
self.initial_sync_done
.load(std::sync::atomic::Ordering::Acquire)
}
fn reset_initial_sync(&self) {
self.initial_sync_done
.store(false, std::sync::atomic::Ordering::Release);
*self
.catch_up_source
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
}
fn subscribe_changes(&self) -> broadcast::Receiver<Arc<ChangeSet>> {
self.change_events.subscribe()
}
fn read_doc<T, F>(&self, f: F) -> impl Future<Output = T> + Send
where
F: FnOnce(&AutoCommit) -> T + Send + 'static,
T: Send + 'static,
{
let state = self.clone();
async move { state.render(f, |value| value).await }
}
fn commit_doc<T, E, F>(&self, f: F) -> impl Future<Output = Result<T, E>> + Send
where
F: FnOnce(&mut AutoCommit) -> Result<T, E> + Send + 'static,
T: Send + 'static,
E: Send + 'static,
{
let state = self.clone();
async move { state.mutate_doc(f).await }
}
fn switch_epoch<E, F>(
&self,
epoch: Epoch,
f: F,
) -> impl Future<Output = Result<AutoCommit, E>> + Send
where
F: FnOnce(&mut AutoCommit) -> Result<AutoCommit, E> + Send + 'static,
E: Send + 'static,
{
let state = self.clone();
async move {
let swapped = {
let state = state.clone();
tokio::task::spawn_blocking(move || -> Result<AutoCommit, E> {
let mut replica = state.doc.blocking_write();
let new_doc = f(&mut replica.doc)?;
let old_doc = std::mem::replace(&mut replica.doc, new_doc);
replica.epoch = epoch;
// Updated under the same lock, so the cached epoch never disagrees
// with the document for anyone holding the lock.
state.epoch_tx.send_replace(epoch);
// Reset every peer's sync state before the lock is released, so no
// message is generated from or applied to a state that describes the
// old document. (Lock order doc -> peer, as in sync generation.)
let now = Instant::now();
for peer in state.peer_states.blocking_read().values() {
let mut peer = peer.blocking_lock();
peer.reset_sync(SessionCause::OwnEpochSwitch);
// A fresh start, not an idle sync: no heal re-handshake for it.
peer.last_sync_rx = Some(now);
}
Ok(old_doc)
})
.await
.expect("epoch switch task panicked")
};
if swapped.is_ok() {
state.after_epoch_switch().await;
}
swapped
}
}
}
|