-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.rs
More file actions
4170 lines (3889 loc) · 160 KB
/
Copy pathengine.rs
File metadata and controls
4170 lines (3889 loc) · 160 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
//! The async sync engine: real folders on disk, kept converged with peers.
//!
//! The engine is the daemon-managed layer that turns the pure [`SyncNode`] and
//! the on-wire backend into a live feature. Per configured entry it:
//! - **scans** the folder into the node (each file → `local_write`, missing files
//! → `local_remove` under policy),
//! - **materializes** the node's manifest back to disk (writes present content,
//! restores catalog deletes, removes bus tombstones),
//! - **watches** the folder and re-syncs on change (near-instant, not a poll),
//! - **reconciles** with each target peer over a swappable [`SyncTransport`].
//!
//! The transport is the seam that makes the backend swappable: the daemon plugs
//! in an iroh transport (over the `fabric/sync` ALPN); the tests plug in an
//! in-process loopback transport and exercise the whole engine against real
//! temp folders with no network. Manifests are persisted per entry so logical
//! versions stay monotonic across daemon restarts.
use std::{
collections::{HashMap, HashSet, VecDeque},
future::Future,
path::{Path, PathBuf},
sync::{
Arc, Mutex as StdMutex,
atomic::{AtomicU64, AtomicUsize, Ordering},
},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use anyhow::{Context, Result};
use iroh::EndpointAddr;
use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, OwnedMutexGuard, RwLock, mpsc};
use tokio_util::sync::CancellationToken;
use crate::config::FabricHome;
use super::config::{PolicyRules, SyncBook, SyncEntry, SyncPeers};
use super::manifest::{Author, ContentHash, Manifest};
use super::node::{Reconciled, SyncNode, content_hash};
/// How long to wait after a filesystem event settles before syncing, so a burst
/// of writes coalesces into one reconcile.
const WATCH_DEBOUNCE: Duration = Duration::from_millis(150);
/// A continuously mutating tree must still make progress, but it must not drive
/// the engine at the debounce frequency forever. This caps watcher-driven
/// reconciles at one per window while coalescing everything in between.
const WATCH_MAX_COALESCE: Duration = Duration::from_secs(2);
/// Safety-net periodic reconcile even without filesystem events (catches missed
/// events and newly trusted peers).
const PERIODIC_RESYNC: Duration = Duration::from_secs(30);
/// Bounded safety scan for watcher events missed across sleep/wake or a
/// transient watcher failure. Clean periodic ticks do not scan the tree.
const MISSED_EVENT_RESYNC: Duration = Duration::from_secs(5 * 60);
/// Watcher notifications can arrive after the materialization that caused
/// them. Remember only a bounded number of exact post-write identities so a
/// delayed daemon-owned event can be acknowledged without another tree scan.
const MAX_DAEMON_WRITE_FINGERPRINTS: usize = 4_096;
#[inline]
fn periodic_scan_due(dirty: bool, safety_due: bool) -> bool {
dirty || safety_due
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
hash: ContentHash,
len: u64,
modified: SystemTime,
#[cfg(unix)]
device: u64,
#[cfg(unix)]
inode: u64,
#[cfg(unix)]
ctime_secs: i64,
#[cfg(unix)]
ctime_nanos: i64,
}
impl FileFingerprint {
fn after_write(path: &Path, hash: ContentHash) -> std::io::Result<Self> {
let metadata = std::fs::metadata(path)?;
if !metadata.is_file() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"fingerprinted path is not a regular file",
));
}
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
Ok(Self {
hash,
len: metadata.len(),
modified: metadata.modified()?,
#[cfg(unix)]
device: metadata.dev(),
#[cfg(unix)]
inode: metadata.ino(),
#[cfg(unix)]
ctime_secs: metadata.ctime(),
#[cfg(unix)]
ctime_nanos: metadata.ctime_nsec(),
})
}
fn read(path: &Path) -> std::io::Result<Self> {
let bytes = std::fs::read(path)?;
Self::after_write(path, content_hash(&bytes))
}
}
#[derive(Debug)]
struct DaemonWriteFingerprint {
fingerprint: FileFingerprint,
generation: u64,
sequence: u64,
committed: bool,
}
#[derive(Debug, Default)]
struct DaemonWriteJournal {
next_sequence: u64,
entries: HashMap<PathBuf, DaemonWriteFingerprint>,
order: VecDeque<(PathBuf, u64)>,
}
impl DaemonWriteJournal {
fn record(&mut self, path: PathBuf, fingerprint: FileFingerprint, generation: u64) {
self.next_sequence = self.next_sequence.wrapping_add(1);
let sequence = self.next_sequence;
self.entries.insert(
path.clone(),
DaemonWriteFingerprint {
fingerprint,
generation,
sequence,
committed: false,
},
);
self.order.push_back((path, sequence));
while self.order.len() > MAX_DAEMON_WRITE_FINGERPRINTS {
let Some((path, sequence)) = self.order.pop_front() else {
break;
};
if self
.entries
.get(&path)
.is_some_and(|entry| entry.sequence == sequence)
{
self.entries.remove(&path);
}
}
}
fn consume_batch(
&mut self,
paths: &[(PathBuf, FileFingerprint)],
first_event_generation: u64,
) -> bool {
let matches = !paths.is_empty()
&& paths.iter().all(|(path, fingerprint)| {
self.entries.get(path).is_some_and(|entry| {
entry.committed
&& entry.generation.checked_add(1) == Some(first_event_generation)
&& entry.fingerprint == *fingerprint
})
});
// Whether this was the expected event or an external mismatch, never
// let an old identity suppress a later change to the same path.
for (path, _) in paths {
self.entries.remove(path);
}
matches
}
fn forget_paths<'a>(&mut self, paths: impl IntoIterator<Item = &'a PathBuf>) {
for path in paths {
self.entries.remove(path);
}
}
fn commit_all(&mut self) {
for entry in self.entries.values_mut() {
entry.committed = true;
}
}
}
/// A dialable peer for a reconcile: a display id and, for the iroh transport, its
/// address. The loopback transport routes by `id` alone.
#[derive(Debug, Clone)]
pub struct PeerRef {
pub id: String,
pub addr: Option<EndpointAddr>,
}
/// The swappable transport that carries a client-side reconcile to a peer. The
/// daemon implements this over iroh; tests implement it in-process.
pub trait SyncTransport: Send + Sync + 'static {
/// The peers an entry's selector resolves to right now (membership follows
/// `peers.toml` for the `"*"` wildcard).
fn peers_for(&self, peers: &SyncPeers) -> impl Future<Output = Vec<PeerRef>> + Send;
/// Run a client reconcile for sync `name` against `peer`, mutating `node`.
fn reconcile(
&self,
peer: PeerRef,
name: String,
node: Arc<Mutex<SyncNode>>,
) -> impl Future<Output = Result<Reconciled>> + Send;
}
/// Per-entry work bookkeeping shared with the filesystem-watcher callback.
///
/// The mutation generation makes queued inbound sessions reusable only after a
/// durable scan of the exact generation they can observe. The first inbound
/// session always scans; sessions already queued behind it can skip the
/// redundant pre-merge scan/persist when no mutating event occurred meanwhile.
#[derive(Debug)]
struct EntryWork {
mutation_generation: AtomicU64,
durable_generation: AtomicU64,
inbound_waiters: AtomicUsize,
daemon_writes: StdMutex<DaemonWriteJournal>,
/// Monotonic while this name remains continuously configured in the same
/// daemon. Exposed through `fabric sync ls` so production can prove whether
/// an inbound transaction walked the tree.
full_scans: AtomicU64,
/// Exact-manifest, complete-content inbound transactions that bypassed the
/// guarded scan/materialize path.
inbound_noop_transactions: AtomicU64,
/// Inbound transactions that selected the guarded scan/materialize path.
inbound_guarded_transactions: AtomicU64,
#[cfg(test)]
persist_calls: AtomicUsize,
}
impl EntryWork {
fn new() -> Arc<Self> {
Arc::new(Self {
// Generation one forces the first inbound session to scan even
// before the watcher observes its first event.
mutation_generation: AtomicU64::new(1),
durable_generation: AtomicU64::new(0),
inbound_waiters: AtomicUsize::new(0),
daemon_writes: StdMutex::new(DaemonWriteJournal::default()),
full_scans: AtomicU64::new(0),
inbound_noop_transactions: AtomicU64::new(0),
inbound_guarded_transactions: AtomicU64::new(0),
#[cfg(test)]
persist_calls: AtomicUsize::new(0),
})
}
fn record_mutation(&self) -> u64 {
self.mutation_generation
.fetch_add(1, Ordering::AcqRel)
.wrapping_add(1)
}
fn record_daemon_write(&self, path: &Path, hash: ContentHash, generation: u64) {
let Ok(fingerprint) = FileFingerprint::after_write(path, hash) else {
return;
};
self.daemon_writes
.lock()
.unwrap()
.record(path.to_path_buf(), fingerprint, generation);
}
fn commit_daemon_writes(&self) {
self.daemon_writes.lock().unwrap().commit_all();
}
fn acknowledge_daemon_write_batch(&self, batch: &WatchEventBatch) -> bool {
if !batch.daemon_write_candidate
|| !batch.contiguous
|| batch.paths.is_empty()
|| self.mutation_generation.load(Ordering::Acquire) != batch.last_generation
{
self.daemon_writes
.lock()
.unwrap()
.forget_paths(&batch.paths);
return false;
}
let mut current = Vec::with_capacity(batch.paths.len());
for path in &batch.paths {
let Ok(fingerprint) = FileFingerprint::read(path) else {
self.daemon_writes
.lock()
.unwrap()
.forget_paths(&batch.paths);
return false;
};
current.push((path.clone(), fingerprint));
}
let matches = self
.daemon_writes
.lock()
.unwrap()
.consume_batch(¤t, batch.first_generation);
if matches {
// The callback already advanced the mutation generation before
// queuing this batch. Exact daemon-owned bytes are already durable,
// so acknowledge only the generations represented by this batch.
self.mark_generation_durable(batch.last_generation);
}
matches
}
fn begin_inbound(self: &Arc<Self>) -> InboundWaiter {
let queued = self.inbound_waiters.fetch_add(1, Ordering::AcqRel) > 0;
InboundWaiter {
work: self.clone(),
queued,
}
}
fn may_reuse_durable_scan(&self, queued: bool) -> bool {
queued && self.is_clean()
}
fn is_clean(&self) -> bool {
self.mutation_generation.load(Ordering::Acquire)
== self.durable_generation.load(Ordering::Acquire)
}
fn mark_generation_durable(&self, generation: u64) {
self.durable_generation
.fetch_max(generation, Ordering::AcqRel);
}
}
/// Cancellation-safe accounting for inbound sessions waiting on the entry
/// operation guard.
struct InboundWaiter {
work: Arc<EntryWork>,
queued: bool,
}
impl Drop for InboundWaiter {
fn drop(&mut self) {
self.work.inbound_waiters.fetch_sub(1, Ordering::AcqRel);
}
}
/// One configured entry's live state.
struct EntryState {
config: SyncEntry,
policy: PolicyRules,
node: Arc<Mutex<SyncNode>>,
/// Serialize filesystem scan/materialize phases for this entry. An inbound
/// transaction keeps an owned guard across the wire session; outbound
/// sessions release it while dialing to avoid distributed lock inversion.
operation: Arc<Mutex<()>>,
/// Last state the engine actually observed or materialized on local disk.
/// A Present held only in the node is not evidence that a missing path was
/// locally deleted; this receipt is what distinguishes those cases.
observed: Arc<StdMutex<HashMap<String, ContentHash>>>,
work: Arc<EntryWork>,
}
/// Atomically persisted authoritative state for one sync entry. `manifest.json`
/// remains a compatibility/inspection projection, but restart recovery reads
/// this combined file so manifest transitions and their observed-disk receipt
/// cannot be torn apart by a crash.
#[derive(Debug, Serialize, Deserialize)]
struct PersistedEntryState {
manifest: Manifest,
observed: HashMap<String, ContentHash>,
}
/// State retained across an inbound merge.
///
/// An exactly converged peer can use `Noop`: its manifest cannot change our
/// node, and a complete local content store means the session cannot repair
/// anything locally. Every other reconcile uses `Guarded`; its operation guard
/// keeps engine-driven scan/materialize work out of the middle of the wire
/// session, and `baseline` distinguishes local paths from remote-only paths at
/// completion.
pub(crate) struct PreparedInbound {
entry: Arc<EntryState>,
mode: PreparedInboundMode,
}
enum PreparedInboundMode {
Noop,
Guarded {
baseline: HashMap<String, ContentHash>,
manifest: Manifest,
_waiter: InboundWaiter,
_operation: OwnedMutexGuard<()>,
},
}
impl PreparedInbound {
pub(crate) fn node(&self) -> Arc<Mutex<SyncNode>> {
self.entry.node.clone()
}
}
impl<T: SyncTransport> std::fmt::Debug for SyncEngine<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SyncEngine").finish_non_exhaustive()
}
}
/// The engine: owns every entry's node and drives scan/materialize/reconcile.
pub struct SyncEngine<T: SyncTransport> {
home: FabricHome,
author: Author,
transport: Arc<T>,
entries: RwLock<HashMap<String, Arc<EntryState>>>,
/// Entry names that already have a watch loop, so a reload only spawns loops
/// for newly added entries.
watching: StdMutex<HashSet<String>>,
cancel: CancellationToken,
}
impl<T: SyncTransport> SyncEngine<T> {
/// Build an engine from the current `syncs.toml`, loading any persisted
/// manifests. Does not start watching; call [`SyncEngine::run`] for that.
pub async fn new(
home: FabricHome,
author: Author,
transport: Arc<T>,
cancel: CancellationToken,
) -> Result<Arc<Self>> {
let engine = Arc::new(Self {
home,
author,
transport,
entries: RwLock::new(HashMap::new()),
watching: StdMutex::new(HashSet::new()),
cancel,
});
engine.load_from_config().await?;
Ok(engine)
}
/// (Re)load entries from `syncs.toml`, keeping existing nodes for entries
/// that are unchanged and dropping entries no longer configured.
pub async fn load_from_config(&self) -> Result<()> {
let book = SyncBook::load(&self.home)?;
let mut entries = self.entries.write().await;
let mut next: HashMap<String, Arc<EntryState>> = HashMap::new();
for cfg in book.entries() {
let policy = cfg.policy.rules();
// The existing watcher for a name survives reloads, so its shared
// mutation generation must survive too even when another config
// field changed and the node is rebuilt.
let work = entries
.get(&cfg.name)
.map(|existing| existing.work.clone())
.unwrap_or_else(EntryWork::new);
// Reuse an existing node for an unchanged entry so in-memory content
// survives a reload; otherwise start one from the persisted manifest.
let (node, operation, observed) = match entries.get(&cfg.name) {
Some(existing) if existing.config == *cfg => (
existing.node.clone(),
existing.operation.clone(),
existing.observed.clone(),
),
_ => {
work.durable_generation.store(0, Ordering::Release);
work.record_mutation();
let (node, observed) = self.load_node_and_observed(cfg).await?;
(
Arc::new(Mutex::new(node)),
Arc::new(Mutex::new(())),
Arc::new(StdMutex::new(observed)),
)
}
};
next.insert(
cfg.name.clone(),
Arc::new(EntryState {
config: cfg.clone(),
policy,
node,
operation,
observed,
work,
}),
);
}
*entries = next;
Ok(())
}
async fn load_node_and_observed(
&self,
cfg: &SyncEntry,
) -> Result<(SyncNode, HashMap<String, ContentHash>)> {
let mut node = SyncNode::new(self.author);
if let Some(state) = self.read_state(&cfg.name)? {
node.adopt(&state.manifest);
return Ok((node, state.observed));
}
if let Some(manifest) = self.read_manifest(&cfg.name)? {
node.adopt(&manifest);
}
let observed = observed_from_disk(node.manifest(), cfg)?;
Ok((node, observed))
}
/// Resolve a sync name to its node (used by the daemon's inbound accept).
pub async fn node_for(&self, name: &str) -> Option<Arc<Mutex<SyncNode>>> {
self.entries
.read()
.await
.get(name)
.map(|entry| entry.node.clone())
}
/// Expose an entry's node to an inbound reconcile, bypassing folder scans
/// only when the peer is exactly converged and our content store is
/// complete.
///
/// An unobserved local filesystem change is safe in this exact no-op case:
/// the peer's manifest cannot win or cause local materialization, so the
/// watcher can record the local intent normally. Any differing manifest or
/// missing local content takes the guarded path below.
pub(crate) async fn prepare_inbound_for_manifest(
&self,
name: &str,
remote_manifest: &Manifest,
) -> Result<Option<PreparedInbound>> {
let Some(entry) = self.entries.read().await.get(name).cloned() else {
return Ok(None);
};
let is_complete_noop = {
let node = entry.node.lock().await;
node.manifest() == remote_manifest && node.missing_content_hashes().is_empty()
};
if is_complete_noop {
entry
.work
.inbound_noop_transactions
.fetch_add(1, Ordering::Relaxed);
return Ok(Some(PreparedInbound {
entry,
mode: PreparedInboundMode::Noop,
}));
}
self.prepare_inbound_entry(entry).await.map(Some)
}
/// Scan and durably record local filesystem changes before exposing an
/// entry's node to a potentially mutating inbound reconcile.
///
/// This ordering is essential for delete-propagating policies: an atomic
/// local rename/delete may already express user intent while its watcher
/// event is still inside the debounce window. Letting a peer reconcile and
/// materialize first could restore the stale Present entry and erase the
/// only observable evidence of that local deletion. Scanning before merge
/// also avoids treating paths that are genuinely new on the remote as local
/// deletions, because they are not in the observed-disk receipt yet.
#[cfg(test)]
pub(crate) async fn prepare_inbound(&self, name: &str) -> Result<Option<PreparedInbound>> {
let Some(entry) = self.entries.read().await.get(name).cloned() else {
return Ok(None);
};
self.prepare_inbound_entry(entry).await.map(Some)
}
async fn prepare_inbound_entry(&self, entry: Arc<EntryState>) -> Result<PreparedInbound> {
let waiter = entry.work.begin_inbound();
let operation = entry.operation.clone().lock_owned().await;
let queued = waiter.queued;
if !entry.work.may_reuse_durable_scan(queued) {
let generation = entry.work.mutation_generation.load(Ordering::Acquire);
let before_manifest = entry.node.lock().await.manifest().clone();
let before_observed = entry.observed.lock().unwrap().clone();
self.scan_entry(&entry).await?;
let final_manifest = entry.node.lock().await.manifest().clone();
let final_observed = entry.observed.lock().unwrap().clone();
if entry.work.durable_generation.load(Ordering::Acquire) != generation
|| final_manifest != before_manifest
|| final_observed != before_observed
|| !self.state_path(&entry.config.name).exists()
{
// A legacy entry may not have state.json yet, and a crash
// during this first wire session must not lose newly observed
// local intent. An already durable no-op scan needs no rewrite.
self.persist_entry(&entry).await?;
}
entry.work.mark_generation_durable(generation);
}
entry
.work
.inbound_guarded_transactions
.fetch_add(1, Ordering::Relaxed);
let baseline = entry.observed.lock().unwrap().clone();
let manifest = entry.node.lock().await.manifest().clone();
Ok(PreparedInbound {
entry,
mode: PreparedInboundMode::Guarded {
baseline,
manifest,
_waiter: waiter,
_operation: operation,
},
})
}
/// Complete an inbound transaction while its entry operation guard is still
/// held. Disk changes that landed during the wire session are compared to
/// the pre-merge baseline: a vanished baseline Present is a local delete,
/// while a remote-only Present is materialized instead of tombstoned.
pub(crate) async fn complete_inbound(&self, prepared: PreparedInbound) -> Result<()> {
let PreparedInbound { entry, mode } = prepared;
let PreparedInboundMode::Guarded {
baseline,
manifest,
_waiter,
_operation,
} = mode
else {
return Ok(());
};
let generation = entry.work.mutation_generation.load(Ordering::Acquire);
// This scan is not optional: it catches disk changes that landed during
// the wire session, whose watcher events may still be inside the
// debounce window, so the mutation generation cannot stand in for it.
// It is cheap now because scan_folder reuses recorded hashes for files
// whose size and mtime are unchanged.
self.scan_entry(&entry).await?;
self.materialize_entry_state(&entry, &baseline).await?;
let final_manifest = entry.node.lock().await.manifest().clone();
let final_observed = entry.observed.lock().unwrap().clone();
if final_manifest != manifest || final_observed != baseline {
self.persist_entry(&entry).await?;
}
entry.work.mark_generation_durable(generation);
Ok(())
}
/// The configured sync names.
pub async fn names(&self) -> Vec<String> {
let mut names: Vec<String> = self.entries.read().await.keys().cloned().collect();
names.sort();
names
}
/// A stable snapshot of logical manifest state and the materialized-disk
/// receipt for every entry.
pub async fn status(&self) -> Vec<SyncStatus> {
let entries = self.entries.read().await;
let mut out = Vec::new();
for (name, entry) in entries.iter() {
let _operation = entry.operation.lock().await;
let node = entry.node.lock().await;
let observed = entry.observed.lock().unwrap();
let manifest = node.manifest();
let present = manifest.present_paths().count();
let tombstones = manifest.len() - present;
let missing = manifest
.present_paths()
.filter(|(path, _)| !observed.contains_key(path.as_str()))
.count();
let unexpected = observed
.keys()
.filter(|path| !manifest.get(path).is_some_and(|item| item.is_present()))
.count();
let mismatched = manifest
.present_paths()
.filter(|(path, meta)| {
observed
.get(path.as_str())
.is_some_and(|hash| hash != &meta.hash)
})
.count();
out.push(SyncStatus {
name: name.clone(),
folder: entry.config.folder.clone(),
policy: entry.config.policy.as_str(),
peers: entry.config.peers.clone(),
present,
tombstones,
observed: observed.len(),
missing,
unexpected,
mismatched,
full_scans: entry.work.full_scans.load(Ordering::Relaxed),
inbound_noop_transactions: entry
.work
.inbound_noop_transactions
.load(Ordering::Relaxed),
inbound_guarded_transactions: entry
.work
.inbound_guarded_transactions
.load(Ordering::Relaxed),
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
/// Scan the folder, materialize, reconcile with every target peer, then
/// materialize again and persist the manifest. The full one-shot sync for an
/// entry — safe to call from a watcher, a timer, or after an inbound session.
pub async fn sync_once(&self, name: &str) -> Result<()> {
let Some(entry) = self.entries.read().await.get(name).cloned() else {
return Ok(());
};
// Never hold the local operation guard across a peer dial. If A and B
// initiate together, retaining A while awaiting B's inbound guard (and
// vice versa) is a distributed lock inversion. Carry a pre-merge
// baseline across the unlocked network step instead.
let (baseline, manifest) = {
let _operation = entry.operation.lock().await;
let protected = entry.observed.lock().unwrap().clone();
let generation = entry.work.mutation_generation.load(Ordering::Acquire);
self.scan_entry(&entry).await?;
self.materialize_entry_state(&entry, &protected).await?;
self.persist_entry(&entry).await?;
entry.work.mark_generation_durable(generation);
let baseline = entry.observed.lock().unwrap().clone();
let manifest = entry.node.lock().await.manifest().clone();
(baseline, manifest)
};
let peers = self.transport.peers_for(&entry.config.peers).await;
for peer in peers {
if self.cancel.is_cancelled() {
break;
}
match self
.transport
.reconcile(peer.clone(), name.to_string(), entry.node.clone())
.await
{
Ok(stats) => {
if !stats.is_noop() {
tracing::debug!(sync = name, peer = peer.id, ?stats, "sync reconciled");
}
}
Err(error) => {
tracing::debug!(sync = name, peer = peer.id, %error, "sync reconcile failed");
}
}
}
let _operation = entry.operation.lock().await;
self.scan_entry(&entry).await?;
self.materialize_entry_state(&entry, &baseline).await?;
let final_manifest = entry.node.lock().await.manifest().clone();
let final_observed = entry.observed.lock().unwrap().clone();
if final_manifest != manifest || final_observed != baseline {
self.persist_entry(&entry).await?;
}
Ok(())
}
/// Materialize just this entry to disk.
pub async fn materialize_entry(&self, name: &str) -> Result<()> {
let Some(entry) = self.entries.read().await.get(name).cloned() else {
return Ok(());
};
let _operation = entry.operation.lock().await;
let protected = entry.observed.lock().unwrap().clone();
self.materialize_entry_state(&entry, &protected).await?;
self.persist_entry(&entry).await
}
async fn scan_entry(&self, entry: &EntryState) -> Result<bool> {
entry.work.full_scans.fetch_add(1, Ordering::Relaxed);
let root = entry.config.folder.clone();
let cfg = entry.config.clone();
let policy = entry.policy;
let mut node = entry.node.lock().await;
let mut observed = entry.observed.lock().unwrap();
scan_into_node_observed(&mut node, &root, &cfg, policy, &mut observed)
}
async fn materialize_entry_state(
&self,
entry: &EntryState,
protected: &HashMap<String, ContentHash>,
) -> Result<()> {
let root = entry.config.folder.clone();
let policy = entry.policy;
let generation = entry.work.mutation_generation.load(Ordering::Acquire);
let mut node = entry.node.lock().await;
let mut observed = entry.observed.lock().unwrap();
materialize_tracked(
&mut node,
&root,
policy,
protected,
&mut observed,
Some((&entry.work, generation)),
)
}
async fn persist_entry(&self, entry: &EntryState) -> Result<()> {
#[cfg(test)]
entry.work.persist_calls.fetch_add(1, Ordering::Relaxed);
let manifest = entry.node.lock().await.manifest().clone();
let observed = entry.observed.lock().unwrap().clone();
self.write_state(
&entry.config.name,
&PersistedEntryState { manifest, observed },
)?;
entry.work.commit_daemon_writes();
Ok(())
}
fn manifest_path(&self, name: &str) -> PathBuf {
self.home
.root()
.join("sync")
.join(sanitize_name(name))
.join("manifest.json")
}
fn state_path(&self, name: &str) -> PathBuf {
self.home
.root()
.join("sync")
.join(sanitize_name(name))
.join("state.json")
}
fn read_state(&self, name: &str) -> Result<Option<PersistedEntryState>> {
let path = self.state_path(name);
if !path.exists() {
return Ok(None);
}
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read {}", path.display()))?;
let state: PersistedEntryState = serde_json::from_str(&raw)
.with_context(|| format!("failed to parse {}", path.display()))?;
Ok(Some(state))
}
fn read_manifest(&self, name: &str) -> Result<Option<Manifest>> {
let path = self.manifest_path(name);
if !path.exists() {
return Ok(None);
}
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read {}", path.display()))?;
let manifest: Manifest = serde_json::from_str(&raw)
.with_context(|| format!("failed to parse {}", path.display()))?;
Ok(Some(manifest))
}
fn write_manifest(&self, name: &str, manifest: &Manifest) -> Result<()> {
let path = self.manifest_path(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let raw = serde_json::to_string_pretty(manifest)?;
write_atomic(&path, raw.as_bytes())
}
fn write_state(&self, name: &str, state: &PersistedEntryState) -> Result<()> {
let path = self.state_path(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let raw = serde_json::to_string_pretty(state)?;
// The combined state is authoritative and lands atomically first.
write_atomic(&path, raw.as_bytes())?;
// Keep the established manifest path current for operators and older
// Fabric binaries. A crash between these writes still recovers from the
// already-committed combined state above.
self.write_manifest(name, &state.manifest)
}
/// Start watching every configured entry's folder and syncing on change,
/// then run until the cancellation token fires. Idempotent per entry.
pub async fn run(self: &Arc<Self>) -> Result<()> {
self.ensure_watching().await;
self.cancel.cancelled().await;
Ok(())
}
/// Re-read `syncs.toml` into the engine and start watching any newly added
/// entries. Mirrors `reload-peers`: a running daemon picks up the new file
/// without a restart. (Changing an existing entry's folder still needs a
/// restart to re-point its watcher.)
pub async fn reload(self: &Arc<Self>) -> Result<()> {
self.load_from_config().await?;
self.ensure_watching().await;
Ok(())
}
/// Spawn a watch loop for every configured entry that does not already have
/// one.
async fn ensure_watching(self: &Arc<Self>) {
let names = self.names().await;
let mut watching = self.watching.lock().unwrap();
for name in names {
if watching.insert(name.clone()) {
let engine = self.clone();
tokio::spawn(async move {
engine.entry_loop(name).await;
});
}
}
}
async fn entry_loop(self: Arc<Self>, name: String) {
let entry = match self.entries.read().await.get(&name) {
Some(entry) => entry.clone(),
None => return,
};
let root = entry.config.folder.clone();
// Best-effort initial sync.
if let Err(error) = self.sync_once(&name).await {
tracing::warn!(sync = %name, %error, "initial sync failed");
}
// The channel is only an edge trigger. One pending signal is enough;
// keeping it bounded prevents an arbitrarily hot writer from building
// an in-memory event backlog while the current sync is running.
let (tx, mut rx) = mpsc::channel::<WatchEvent>(1);
let _watcher = spawn_watcher(&root, tx, entry.work.clone());
let mut ticker = tokio::time::interval(PERIODIC_RESYNC);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
ticker.tick().await; // consume the immediate first tick
let mut last_safety_scan = tokio::time::Instant::now();
loop {
tokio::select! {
_ = self.cancel.cancelled() => break,
_ = ticker.tick() => {
let dirty = entry.work.mutation_generation.load(Ordering::Acquire)
!= entry.work.durable_generation.load(Ordering::Acquire);
let safety_due = last_safety_scan.elapsed() >= MISSED_EVENT_RESYNC;
if periodic_scan_due(dirty, safety_due) {
if safety_due { last_safety_scan = tokio::time::Instant::now(); }
if let Err(error) = self.sync_once(&name).await {
tracing::debug!(sync = %name, %error, "periodic sync failed");
}
}
}
event = rx.recv() => {
let Some(event) = event else { break; };
// Wait for a quiet edge, but cap the window so a
// continuously mutating tree still makes bounded progress.
let Some(batch) = coalesce_watch_events(
event,
&mut rx,
WATCH_DEBOUNCE,
WATCH_MAX_COALESCE,
)
.await
else {
break;
};
// Every materialization and its state persist hold this
// guard. Do not acknowledge a delayed self-event before
// the bytes it identifies are durably committed.
let daemon_owned = {
let _operation = entry.operation.lock().await;
entry.work.acknowledge_daemon_write_batch(&batch)
};
if daemon_owned {
continue;
}
if let Err(error) = self.sync_once(&name).await {
tracing::debug!(sync = %name, %error, "watch sync failed");
}
}
}
}
}
}
/// Coalesce watcher events until the tree is quiet for [`WATCH_DEBOUNCE`], or
/// until [`WATCH_MAX_COALESCE`] bounds a continuous mutation stream.
///
/// Returns `None` only when the watcher channel has closed.
async fn coalesce_watch_events(
first: WatchEvent,
rx: &mut mpsc::Receiver<WatchEvent>,
debounce: Duration,
max_coalesce: Duration,
) -> Option<WatchEventBatch> {
let mut batch = WatchEventBatch::new(first);
let deadline = tokio::time::Instant::now() + max_coalesce;
loop {
tokio::select! {
_ = tokio::time::sleep_until(deadline) => break,
next = tokio::time::timeout(debounce, rx.recv()) => {
match next {
Ok(Some(event)) => {
batch.push(event);
continue;
}
Ok(None) => return None,
Err(_) => break,