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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::Mutex;
use uuid::Uuid;
use crate::crypto::{PublicKey, Secret, SecretError, SecretKey, SecretShare};
use crate::linked_data::{BlockEncoded, CodecError, Link};
use crate::peer::{BlobsStore, BlobsStoreError};
use super::conflict::MergeResult;
use super::manifest::{Manifest, ManifestError, Share};
use super::node::{Node, NodeError, NodeLink};
use super::path_ops::{OpType, PathOpLog};
use super::pins::Pins;
use super::principal::PrincipalRole;
pub fn clean_path(path: &Path) -> PathBuf {
if !path.is_absolute() {
panic!("path is not absolute");
}
path.iter()
.skip(1)
.map(|part| part.to_string_lossy().to_string())
.collect::<PathBuf>()
}
#[derive(Clone)]
pub struct MountInner {
// link to the manifest
pub link: Link,
// the loaded manifest
pub manifest: Manifest,
// the loaded, decrypted entry node
pub entry: Node,
// the loaded pins
pub pins: Pins,
// convenience pointer to the height of the mount
pub height: u64,
// the path operations log (CRDT for conflict resolution)
pub ops_log: PathOpLog,
// the local peer ID (for recording operations)
pub peer_id: PublicKey,
// the secret key for signing manifests
pub secret_key: SecretKey,
}
impl MountInner {
pub fn link(&self) -> &Link {
&self.link
}
pub fn entry(&self) -> &Node {
&self.entry
}
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
pub fn pins(&self) -> &Pins {
&self.pins
}
pub fn height(&self) -> u64 {
self.height
}
pub fn ops_log(&self) -> &PathOpLog {
&self.ops_log
}
pub fn peer_id(&self) -> &PublicKey {
&self.peer_id
}
}
#[derive(Clone)]
pub struct Mount(Arc<Mutex<MountInner>>, BlobsStore);
#[derive(Debug, thiserror::Error)]
pub enum MountError {
#[error("default error: {0}")]
Default(#[from] anyhow::Error),
#[error("link not found")]
LinkNotFound(Link),
#[error("path not found: {0}")]
PathNotFound(PathBuf),
#[error("path is not a node: {0}")]
PathNotNode(PathBuf),
#[error("path already exists: {0}")]
PathAlreadyExists(PathBuf),
#[error("cannot move '{from}' to '{to}': destination is inside source")]
MoveIntoSelf { from: PathBuf, to: PathBuf },
#[error("blobs store error: {0}")]
BlobsStore(#[from] BlobsStoreError),
#[error("secret error: {0}")]
Secret(#[from] SecretError),
#[error("node error: {0}")]
Node(#[from] NodeError),
#[error("codec error: {0}")]
Codec(#[from] CodecError),
#[error("share error: {0}")]
Share(#[from] crate::crypto::SecretShareError),
#[error("manifest error: {0}")]
Manifest(#[from] ManifestError),
#[error("peers share was not found")]
ShareNotFound,
#[error("mirror cannot mount: bucket is not published")]
MirrorCannotMount,
#[error("unauthorized: only owners can perform this operation")]
Unauthorized,
}
impl Mount {
pub async fn inner(&self) -> MountInner {
self.0.lock().await.clone()
}
pub fn blobs(&self) -> BlobsStore {
self.1.clone()
}
pub async fn link(&self) -> Link {
let inner = self.0.lock().await;
inner.link.clone()
}
/// Save the current mount state to the blobs store.
///
/// The `publish` parameter controls publish state:
/// - `None` — preserve current state (published stays published, unpublished stays unpublished)
/// - `Some(true)` — publish (store secret in plaintext so mirrors can decrypt)
/// - `Some(false)` — unpublish (clear plaintext secret, revoke mirror access)
pub async fn save(
&self,
blobs: &BlobsStore,
publish: Option<bool>,
) -> Result<(Link, Link, u64), MountError> {
// Clone data we need before any async operations
let (
entry_node,
mut pins,
previous_link,
previous_height,
manifest_template,
ops_log,
secret_key,
) = {
let inner = self.0.lock().await;
(
inner.entry.clone(),
inner.pins.clone(),
inner.link.clone(),
inner.height,
inner.manifest.clone(),
inner.ops_log.clone(),
inner.secret_key.clone(),
)
};
// Increment the height of the mount
let height = previous_height + 1;
// Create a new secret for the updated root
let secret = Secret::generate();
// Put the current root node into blobs with the new secret
let entry = Self::_put_node_in_blobs(&entry_node, &secret, blobs).await?;
// Serialize current pins to blobs
// put the new root link into the pins, as well as the previous link
pins.insert(entry.clone().hash());
pins.insert(previous_link.hash());
// Encrypt and store the ops log if it has any operations
let ops_log_link = if !ops_log.is_empty() {
let link = Self::_put_ops_log_in_blobs(&ops_log, &secret, blobs).await?;
pins.insert(link.hash());
Some(link)
} else {
None
};
let pins_link = Self::_put_pins_in_blobs(&pins, blobs).await?;
// Re-encrypt owner shares with the new secret (mirrors stay unchanged)
let mut manifest = manifest_template;
for share in manifest.shares_mut().values_mut() {
if *share.role() == PrincipalRole::Owner {
let secret_share = SecretShare::new(&secret, &share.principal().identity)?;
share.set_share(secret_share);
}
}
// Apply publish state:
// None = preserve current, Some(true) = publish, Some(false) = unpublish
let should_publish = publish.unwrap_or(manifest.is_published());
if should_publish {
manifest.publish(&secret);
} else {
manifest.unpublish();
}
manifest.set_pins(pins_link.clone());
manifest.set_previous(previous_link.clone());
manifest.set_entry(entry.clone());
manifest.set_height(height);
// Clear inherited ops_log from the template, then set if we have new operations
// Each version's ops_log is independent and encrypted with that version's secret
manifest.clear_ops_log();
if let Some(ops_link) = ops_log_link {
manifest.set_ops_log(ops_link);
}
// Sign the manifest with the stored secret key
manifest.sign(&secret_key)?;
// Put the updated manifest into blobs to determine the new link
let link = Self::_put_manifest_in_blobs(&manifest, blobs).await?;
// Update the internal state
{
let mut inner = self.0.lock().await;
inner.manifest = manifest;
inner.height = height;
inner.link = link.clone();
// Clear the ops_log - it's now persisted in the manifest
// Future operations start a fresh log for the next version
// IMPORTANT: Preserve the clock value so future ops have unique timestamps
inner.ops_log.clear_preserving_clock();
}
Ok((link, previous_link, height))
}
pub async fn init(
id: Uuid,
name: String,
owner: &SecretKey,
blobs: &BlobsStore,
) -> Result<Self, MountError> {
// create a new root node for the bucket
let entry = Node::default();
// create a new secret for the owner
let secret = Secret::generate();
// put the node in the blobs store for the secret
let entry_link = Self::_put_node_in_blobs(&entry, &secret, blobs).await?;
// share the secret with the owner
let share = SecretShare::new(&secret, &owner.public())?;
// Initialize pins with root node hash
let mut pins = Pins::new();
pins.insert(entry_link.hash());
// Put the pins in blobs to get a pins link
let pins_link = Self::_put_pins_in_blobs(&pins, blobs).await?;
// construct the new manifest
let mut manifest = Manifest::new(
id,
name.clone(),
owner.public(),
share,
entry_link.clone(),
pins_link.clone(),
0, // initial height is 0
);
// Sign the manifest with the owner's key
manifest.sign(owner)?;
let link = Self::_put_manifest_in_blobs(&manifest, blobs).await?;
// return the new mount
Ok(Mount(
Arc::new(Mutex::new(MountInner {
link,
manifest,
entry,
pins,
height: 0,
ops_log: PathOpLog::new(),
peer_id: owner.public(),
secret_key: owner.clone(),
})),
blobs.clone(),
))
}
pub async fn load(
link: &Link,
secret_key: &SecretKey,
blobs: &BlobsStore,
) -> Result<Self, MountError> {
let public_key = &secret_key.public();
let manifest = Self::_get_manifest_from_blobs(link, blobs).await?;
let bucket_share = match manifest.get_share(public_key) {
Some(share) => share,
None => return Err(MountError::ShareNotFound),
};
// Get the secret based on role
let secret = match bucket_share.role() {
PrincipalRole::Owner => {
// Owners decrypt their individual share
let share = bucket_share.share().ok_or(MountError::ShareNotFound)?;
share.recover(secret_key)?
}
PrincipalRole::Mirror => {
// Mirrors use the public secret (if bucket is published)
manifest
.public()
.cloned()
.ok_or(MountError::MirrorCannotMount)?
}
};
let pins = Self::_get_pins_from_blobs(manifest.pins(), blobs).await?;
let entry = Self::_get_node_from_blobs(
&NodeLink::Dir(manifest.entry().clone(), secret.clone()),
blobs,
)
.await?;
// Read height from the manifest
let height = manifest.height();
// Load the ops log if it exists, otherwise create a new one
let ops_log = if let Some(ops_link) = manifest.ops_log() {
let mut log = Self::_get_ops_log_from_blobs(ops_link, &secret, blobs).await?;
// Rebuild local clock from operations after deserialization
log.rebuild_clock();
log
} else {
PathOpLog::new()
};
Ok(Mount(
Arc::new(Mutex::new(MountInner {
link: link.clone(),
manifest,
entry,
pins,
height,
ops_log,
peer_id: secret_key.public(),
secret_key: secret_key.clone(),
})),
blobs.clone(),
))
}
/// Load just the manifest from a link without full mount decryption.
///
/// This is useful for checking roles/shares before deciding which version to load.
/// Returns the manifest if the blob exists, without attempting decryption.
pub async fn load_manifest(link: &Link, blobs: &BlobsStore) -> Result<Manifest, MountError> {
Self::_get_manifest_from_blobs(link, blobs).await
}
/// Add an owner to this bucket.
/// Owners get an encrypted share immediately.
pub async fn add_owner(&mut self, peer: PublicKey) -> Result<(), MountError> {
let mut inner = self.0.lock().await;
let secret_share = SecretShare::new(&Secret::default(), &peer)?;
inner
.manifest
.add_share(Share::new_owner(secret_share, peer));
Ok(())
}
/// Add a mirror to this bucket.
/// Mirrors can sync bucket data but cannot decrypt until published.
pub async fn add_mirror(&mut self, peer: PublicKey) {
let mut inner = self.0.lock().await;
inner.manifest.add_share(Share::new_mirror(peer));
}
/// Remove a share from the bucket.
///
/// Only owners can remove shares. Returns an error if the caller is not an owner
/// or if the specified peer is not in the shares.
pub async fn remove_share(&self, peer_public_key: PublicKey) -> Result<(), MountError> {
let mut inner = self.0.lock().await;
// Verify caller is an owner
let our_key = inner.secret_key.public();
let our_share = inner
.manifest
.get_share(&our_key)
.ok_or(MountError::ShareNotFound)?;
if *our_share.role() != PrincipalRole::Owner {
return Err(MountError::Unauthorized);
}
// Verify the target share exists
let key_hex = peer_public_key.to_hex();
if inner.manifest.shares_mut().remove(&key_hex).is_none() {
return Err(MountError::ShareNotFound);
}
Ok(())
}
/// Check if this bucket is published (mirrors can decrypt).
pub async fn is_published(&self) -> bool {
let inner = self.0.lock().await;
inner.manifest.is_published()
}
/// Publish this bucket, granting decryption access to all mirrors.
pub async fn publish(&self) -> Result<(Link, Link, u64), MountError> {
self.save(&self.1, Some(true)).await
}
/// Unpublish this bucket, revoking mirror decryption access.
pub async fn unpublish(&self) -> Result<(Link, Link, u64), MountError> {
self.save(&self.1, Some(false)).await
}
pub async fn add<R>(&mut self, path: &Path, data: R) -> Result<(), MountError>
where
R: Read + Send + Sync + 'static + Unpin,
{
let secret = Secret::generate();
let encrypted_reader = secret.encrypt_reader(data)?;
// TODO (amiller68): this is incredibly dumb
use bytes::Bytes;
use futures::stream;
let encrypted_bytes = {
let mut buf = Vec::new();
let mut reader = encrypted_reader;
reader.read_to_end(&mut buf).map_err(SecretError::Io)?;
buf
};
let stream = Box::pin(stream::once(async move {
Ok::<_, std::io::Error>(Bytes::from(encrypted_bytes))
}));
let hash = self.1.put_stream(stream).await?;
let link = Link::new(crate::linked_data::LD_RAW_CODEC, hash);
let node_link = NodeLink::new_data_from_path(link.clone(), secret, path);
let root_node = {
let inner = self.0.lock().await;
inner.entry.clone()
};
let (updated_link, node_hashes) =
Self::_set_node_link_at_path(root_node, node_link, path, &self.1).await?;
// Update entry if needed
let new_entry = if let NodeLink::Dir(new_root_link, new_secret) = updated_link {
Some(
Self::_get_node_from_blobs(
&NodeLink::Dir(new_root_link.clone(), new_secret),
&self.1,
)
.await?,
)
} else {
None
};
// Update inner state
{
let mut inner = self.0.lock().await;
// Track pins: data blob + all created node hashes
inner.pins.insert(hash);
inner.pins.extend(node_hashes);
if let Some(entry) = new_entry {
inner.entry = entry;
}
// Record the add operation in the ops log
let peer_id = inner.peer_id;
inner
.ops_log
.record(peer_id, OpType::Add, clean_path(path), Some(link), false);
}
Ok(())
}
pub async fn rm(&mut self, path: &Path) -> Result<(), MountError> {
let path = clean_path(path);
let parent_path = path
.parent()
.ok_or_else(|| MountError::Default(anyhow::anyhow!("Cannot remove root")))?;
let entry = {
let inner = self.0.lock().await;
inner.entry.clone()
};
let mut parent_node = if parent_path == Path::new("") {
entry.clone()
} else {
Self::_get_node_at_path(&entry, parent_path, &self.1).await?
};
let file_name = path.file_name().unwrap().to_string_lossy().to_string();
// Get the node link before deleting to check if it's a directory
let removed_link = parent_node.del(&file_name);
if removed_link.is_none() {
return Err(MountError::PathNotFound(path.to_path_buf()));
}
let is_dir = removed_link.map(|l| l.is_dir()).unwrap_or(false);
// Store path for ops log before we lose ownership
let removed_path = path.to_path_buf();
if parent_path == Path::new("") {
let secret = Secret::generate();
let link = Self::_put_node_in_blobs(&parent_node, &secret, &self.1).await?;
let mut inner = self.0.lock().await;
// Track the new root node hash
inner.pins.insert(link.hash());
inner.entry = parent_node;
} else {
// Save the modified parent node to blobs
let secret = Secret::generate();
let parent_link = Self::_put_node_in_blobs(&parent_node, &secret, &self.1).await?;
let node_link = NodeLink::new_dir(parent_link.clone(), secret);
// Convert parent_path back to absolute for _set_node_link_at_path
let abs_parent_path = Path::new("/").join(parent_path);
let (updated_link, node_hashes) =
Self::_set_node_link_at_path(entry, node_link, &abs_parent_path, &self.1).await?;
let new_entry = if let NodeLink::Dir(new_root_link, new_secret) = updated_link {
Some(
Self::_get_node_from_blobs(
&NodeLink::Dir(new_root_link.clone(), new_secret),
&self.1,
)
.await?,
)
} else {
None
};
let mut inner = self.0.lock().await;
// Track the parent node hash and all created node hashes
inner.pins.insert(parent_link.hash());
inner.pins.extend(node_hashes);
if let Some(new_entry) = new_entry {
inner.entry = new_entry;
}
}
// Record the remove operation in the ops log
{
let mut inner = self.0.lock().await;
let peer_id = inner.peer_id;
inner
.ops_log
.record(peer_id, OpType::Remove, removed_path, None, is_dir);
}
Ok(())
}
pub async fn mkdir(&mut self, path: &Path) -> Result<(), MountError> {
let path = clean_path(path);
// Check if the path already exists
let entry = {
let inner = self.0.lock().await;
inner.entry.clone()
};
// Try to get the parent path and file name
let (parent_path, dir_name) = if let Some(parent) = path.parent() {
(
parent,
path.file_name().unwrap().to_string_lossy().to_string(),
)
} else {
return Err(MountError::Default(anyhow::anyhow!("Cannot mkdir at root")));
};
// Get the parent node (or use root if parent is empty)
let parent_node = if parent_path == Path::new("") {
entry.clone()
} else {
// Check if parent path exists, if not it will be created by _set_node_link_at_path
match Self::_get_node_at_path(&entry, parent_path, &self.1).await {
Ok(node) => node,
Err(MountError::PathNotFound(_)) => Node::default(), // Will be created
Err(err) => return Err(err),
}
};
// Check if a node with this name already exists in the parent
if parent_node.get_link(&dir_name).is_some() {
return Err(MountError::PathAlreadyExists(Path::new("/").join(&path)));
}
// Create an empty directory node
let new_dir_node = Node::default();
// Generate a secret for the new directory
let secret = Secret::generate();
// Store the node in blobs
let dir_link = Self::_put_node_in_blobs(&new_dir_node, &secret, &self.1).await?;
// Create a NodeLink for the directory
let node_link = NodeLink::new_dir(dir_link.clone(), secret);
// Convert path back to absolute for _set_node_link_at_path
let abs_path = Path::new("/").join(&path);
// Use _set_node_link_at_path to insert the directory into the tree
let (updated_link, node_hashes) =
Self::_set_node_link_at_path(entry, node_link, &abs_path, &self.1).await?;
// Update entry if the root was modified
let new_entry = if let NodeLink::Dir(new_root_link, new_secret) = updated_link {
Some(
Self::_get_node_from_blobs(
&NodeLink::Dir(new_root_link.clone(), new_secret),
&self.1,
)
.await?,
)
} else {
None
};
// Update inner state
{
let mut inner = self.0.lock().await;
// Track the directory node hash and all created node hashes
inner.pins.insert(dir_link.hash());
inner.pins.extend(node_hashes);
if let Some(new_entry) = new_entry {
inner.entry = new_entry;
}
// Record the mkdir operation in the ops log
let peer_id = inner.peer_id;
inner
.ops_log
.record(peer_id, OpType::Mkdir, path.to_path_buf(), None, true);
}
Ok(())
}
/// Move or rename a file or directory from one path to another.
///
/// This operation:
/// 1. Validates that the move is legal (destination not inside source)
/// 2. Retrieves the node at the source path
/// 3. Removes it from the source location
/// 4. Inserts it at the destination location
///
/// The node's content (files/subdirectories) is not re-encrypted during the move;
/// only the tree structure is updated. This makes moves efficient regardless of
/// the size of the subtree being moved.
///
/// # Errors
///
/// - `PathNotFound` - source path doesn't exist
/// - `PathAlreadyExists` - destination path already exists
/// - `MoveIntoSelf` - attempting to move a directory into itself (e.g., /foo -> /foo/bar)
/// - `Default` - attempting to move the root directory
pub async fn mv(&mut self, from: &Path, to: &Path) -> Result<(), MountError> {
// Convert absolute paths to relative paths for internal operations.
// The mount stores paths relative to root, so "/foo/bar" becomes "foo/bar".
let from_clean = clean_path(from);
let to_clean = clean_path(to);
// ============================================================
// VALIDATION: Prevent moving a directory into itself
// ============================================================
// This catches cases like:
// - /foo -> /foo (same path, would delete then fail to insert)
// - /foo -> /foo/bar (moving into subdirectory of itself)
//
// This is impossible in a filesystem sense - you can't put a box inside itself.
// We check this early to provide a clear error message and avoid corrupting
// the tree structure (the delete would succeed but the insert would fail).
if to.starts_with(from) {
return Err(MountError::MoveIntoSelf {
from: from.to_path_buf(),
to: to.to_path_buf(),
});
}
// ============================================================
// STEP 1: Retrieve the NodeLink at the source path
// ============================================================
// A NodeLink is a reference to either a file or directory. For directories,
// it contains the entire subtree. We'll reuse this same NodeLink at the
// destination, which means no re-encryption is needed for the content.
let node_link = self.get(from).await?;
let is_dir = node_link.is_dir();
// Store paths for ops log before any mutations
let from_path = from_clean.to_path_buf();
let to_path = to_clean.to_path_buf();
// ============================================================
// STEP 2: Verify destination doesn't already exist
// ============================================================
// Unlike Unix mv which can overwrite, we require the destination to be empty.
// This prevents accidental data loss.
if self.get(to).await.is_ok() {
return Err(MountError::PathAlreadyExists(to.to_path_buf()));
}
// ============================================================
// STEP 3: Remove the node from its source location
// ============================================================
// We need to update the parent directory to remove the reference to this node.
// This involves:
// a) Finding the parent directory
// b) Removing the child entry from it
// c) Re-encrypting and saving the modified parent
// d) Propagating changes up to the root (updating all ancestor nodes)
{
// Get the parent path (e.g., "foo" for "foo/bar")
let parent_path = from_clean
.parent()
.ok_or_else(|| MountError::Default(anyhow::anyhow!("Cannot move root")))?;
// Get the current root entry node
let entry = {
let inner = self.0.lock().await;
inner.entry.clone()
};
// Load the parent node - either the root itself or a subdirectory
let mut parent_node = if parent_path == Path::new("") {
// Source is at root level (e.g., "/foo"), parent is root
entry.clone()
} else {
// Source is nested, need to traverse to find parent
Self::_get_node_at_path(&entry, parent_path, &self.1).await?
};
// Extract the filename component (e.g., "bar" from "foo/bar")
let file_name = from_clean
.file_name()
.expect(
"from_clean has no filename - this should be impossible after parent() check",
)
.to_string_lossy()
.to_string();
// Remove the child from the parent's children map
if parent_node.del(&file_name).is_none() {
return Err(MountError::PathNotFound(from_clean.to_path_buf()));
}
// Now we need to persist the modified parent and update the tree
if parent_path == Path::new("") {
// Parent is root - just update root directly
let secret = Secret::generate();
let link = Self::_put_node_in_blobs(&parent_node, &secret, &self.1).await?;
let mut inner = self.0.lock().await;
inner.pins.insert(link.hash());
inner.entry = parent_node;
} else {
// Parent is a subdirectory - need to propagate changes up the tree.
// This creates a new encrypted blob for the parent and updates
// all ancestor nodes to point to the new parent.
let secret = Secret::generate();
let parent_link = Self::_put_node_in_blobs(&parent_node, &secret, &self.1).await?;
let new_node_link = NodeLink::new_dir(parent_link.clone(), secret);
// Update the tree from root down to this parent
let abs_parent_path = Path::new("/").join(parent_path);
let (updated_root_link, node_hashes) =
Self::_set_node_link_at_path(entry, new_node_link, &abs_parent_path, &self.1)
.await?;
// Load the new root entry from the updated link.
// The root should always be a directory; if it's not, something is
// seriously wrong with the mount structure.
let new_entry = Self::_get_node_from_blobs(&updated_root_link, &self.1).await?;
// Update the mount's internal state with the new tree
let mut inner = self.0.lock().await;
inner.pins.insert(parent_link.hash());
inner.pins.extend(node_hashes);
inner.entry = new_entry;
}
}
// ============================================================
// STEP 4: Insert the node at the destination path
// ============================================================
// We reuse the same NodeLink from step 1. This means the actual file/directory
// content doesn't need to be re-encrypted - only the tree structure changes.
// This makes moves O(depth) rather than O(size of subtree).
let entry = {
let inner = self.0.lock().await;
inner.entry.clone()
};
let (updated_root_link, node_hashes) =
Self::_set_node_link_at_path(entry, node_link, to, &self.1).await?;
// ============================================================
// STEP 5: Update internal state with the final tree
// ============================================================
{
// Load the new root entry and update the mount
let new_entry = Self::_get_node_from_blobs(&updated_root_link, &self.1).await?;
let mut inner = self.0.lock().await;
inner.pins.extend(node_hashes);
inner.entry = new_entry;
// ============================================================
// STEP 6: Record mv operation in the ops log
// ============================================================
let peer_id = inner.peer_id;
inner.ops_log.record(
peer_id,
OpType::Mv { from: from_path },
to_path,
None,
is_dir,
);
}
Ok(())
}
pub async fn ls(&self, path: &Path) -> Result<BTreeMap<PathBuf, NodeLink>, MountError> {
let mut items = BTreeMap::new();
let path = clean_path(path);
let inner = self.0.lock().await;
let root_node = inner.entry.clone();
drop(inner);
let node = if path == Path::new("") {
root_node
} else {
match Self::_get_node_at_path(&root_node, &path, &self.1).await {
Ok(node) => node,
Err(MountError::LinkNotFound(_)) => {
return Err(MountError::PathNotNode(path.to_path_buf()))
}
Err(err) => return Err(err),
}
};
for (name, link) in node.get_links() {
let mut full_path = path.clone();
full_path.push(name);
items.insert(full_path, link.clone());
}
Ok(items)
}
pub async fn ls_deep(&self, path: &Path) -> Result<BTreeMap<PathBuf, NodeLink>, MountError> {
let base_path = clean_path(path);
self._ls_deep(path, &base_path).await
}
async fn _ls_deep(
&self,
path: &Path,
base_path: &Path,
) -> Result<BTreeMap<PathBuf, NodeLink>, MountError> {
let mut all_items = BTreeMap::new();
// get the initial items at the given path
let items = self.ls(path).await?;
for (item_path, link) in items {
// Make path relative to the base_path
let relative_path = if base_path == Path::new("") {
item_path.clone()
} else {
item_path
.strip_prefix(base_path)
.unwrap_or(&item_path)
.to_path_buf()
};
all_items.insert(relative_path.clone(), link.clone());
if link.is_dir() {
// Recurse using the absolute path
let abs_item_path = Path::new("/").join(&item_path);
let sub_items = Box::pin(self._ls_deep(&abs_item_path, base_path)).await?;
// Sub items already have correct relative paths from base_path
for (sub_path, sub_link) in sub_items {
all_items.insert(sub_path, sub_link);
}
}
}
Ok(all_items)
}
#[allow(clippy::await_holding_lock)]
pub async fn cat(&self, path: &Path) -> Result<Vec<u8>, MountError> {
let path = clean_path(path);
let inner = self.0.lock().await;
let root_node = inner.entry.clone();
drop(inner);
let (parent_path, file_name) = if let Some(parent) = path.parent() {
(
parent,
path.file_name().unwrap().to_string_lossy().to_string(),
)
} else {
return Err(MountError::PathNotFound(path.to_path_buf()));
};
let parent_node = if parent_path == Path::new("") {
root_node
} else {
Self::_get_node_at_path(&root_node, parent_path, &self.1).await?
};
let link = parent_node
.get_link(&file_name)
.ok_or_else(|| MountError::PathNotFound(path.to_path_buf()))?;
match link {
NodeLink::Data(link, secret, _) => {
let encrypted_data = self.1.get(&link.hash()).await?;
let data = secret.decrypt(&encrypted_data)?;
Ok(data)
}
NodeLink::Dir(_, _) => Err(MountError::PathNotNode(path.to_path_buf())),
}
}
/// Get the NodeLink for a file at a given path
#[allow(clippy::await_holding_lock)]
pub async fn get(&self, path: &Path) -> Result<NodeLink, MountError> {
let path = clean_path(path);
let inner = self.0.lock().await;
let root_node = inner.entry.clone();
drop(inner);
let (parent_path, file_name) = if let Some(parent) = path.parent() {
(
parent,
path.file_name().unwrap().to_string_lossy().to_string(),
)
} else {
return Err(MountError::PathNotFound(path.to_path_buf()));
};
let parent_node = if parent_path == Path::new("") {
root_node
} else {
Self::_get_node_at_path(&root_node, parent_path, &self.1).await?
};
parent_node
.get_link(&file_name)
.cloned()
.ok_or_else(|| MountError::PathNotFound(path.to_path_buf()))
}
async fn _get_node_at_path(
node: &Node,
path: &Path,
blobs: &BlobsStore,
) -> Result<Node, MountError> {
let mut current_node = node.clone();
let mut consumed_path = PathBuf::from("/");
for part in path.iter() {
consumed_path.push(part);
let next = part.to_string_lossy().to_string();
let next_link = current_node
.get_link(&next)
.ok_or(MountError::PathNotFound(consumed_path.clone()))?;
current_node = Self::_get_node_from_blobs(next_link, blobs).await?
}
Ok(current_node)
}
pub async fn _set_node_link_at_path(
node: Node,
node_link: NodeLink,
path: &Path,
blobs: &BlobsStore,
) -> Result<(NodeLink, Vec<crate::linked_data::Hash>), MountError> {
let path = clean_path(path);
let mut visited_nodes = Vec::new();
let mut name = path.file_name().unwrap().to_string_lossy().to_string();
let parent_path = path.parent().unwrap_or(Path::new(""));
let mut consumed_path = PathBuf::from("/");
let mut node = node;
visited_nodes.push((consumed_path.clone(), node.clone()));
for part in parent_path.iter() {
let next = part.to_string_lossy().to_string();
let next_link = node.get_link(&next);
if let Some(next_link) = next_link {
consumed_path.push(part);
match next_link {
NodeLink::Dir(..) => {
node = Self::_get_node_from_blobs(next_link, blobs).await?
}
NodeLink::Data(..) => {
return Err(MountError::PathNotNode(consumed_path.clone()));
}
}
visited_nodes.push((consumed_path.clone(), node.clone()));
} else {
// Create a new directory node
node = Node::default();
consumed_path.push(part);
visited_nodes.push((consumed_path.clone(), node.clone()));
}
}
let mut node_link = node_link;
let mut created_hashes = Vec::new();
for (path, mut node) in visited_nodes.into_iter().rev() {
node.insert(name, node_link.clone());
let secret = Secret::generate();
let link = Self::_put_node_in_blobs(&node, &secret, blobs).await?;
created_hashes.push(link.hash());
node_link = NodeLink::Dir(link, secret);
name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
}
Ok((node_link, created_hashes))
}
async fn _get_manifest_from_blobs(
link: &Link,
blobs: &BlobsStore,
) -> Result<Manifest, MountError> {
tracing::debug!(
"_get_bucket_from_blobs: Checking for bucket data at link {:?}",
link
);
let hash = link.hash();
tracing::debug!("_get_bucket_from_blobs: Bucket hash: {}", hash);
match blobs.stat(&hash).await {
Ok(true) => {
tracing::debug!(
"_get_bucket_from_blobs: Bucket hash {} exists in blobs",
hash
);
}
Ok(false) => {
tracing::error!("_get_bucket_from_blobs: Bucket hash {} NOT FOUND in blobs - LinkNotFound error!", hash);
return Err(MountError::LinkNotFound(link.clone()));
}
Err(e) => {
tracing::error!(
"_get_bucket_from_blobs: Error checking bucket hash {}: {}",
hash,
e
);
return Err(e.into());
}
}
tracing::debug!("_get_bucket_from_blobs: Reading bucket data from blobs");
let data = blobs.get(&hash).await?;
tracing::debug!(
"_get_bucket_from_blobs: Got {} bytes of bucket data",
data.len()
);
let bucket_data = Manifest::decode(&data)?;
tracing::debug!(
"_get_bucket_from_blobs: Successfully decoded BucketData for bucket '{}'",
bucket_data.name()
);
Ok(bucket_data)
}
pub async fn _get_pins_from_blobs(link: &Link, blobs: &BlobsStore) -> Result<Pins, MountError> {
tracing::debug!("_get_pins_from_blobs: Checking for pins at link {:?}", link);
let hash = link.hash();
tracing::debug!("_get_pins_from_blobs: Pins hash: {}", hash);
match blobs.stat(&hash).await {
Ok(true) => {
tracing::debug!("_get_pins_from_blobs: Pins hash {} exists in blobs", hash);
}
Ok(false) => {
tracing::error!(
"_get_pins_from_blobs: Pins hash {} NOT FOUND in blobs - LinkNotFound error!",
hash
);
return Err(MountError::LinkNotFound(link.clone()));
}
Err(e) => {
tracing::error!(
"_get_pins_from_blobs: Error checking pins hash {}: {}",
hash,
e
);
return Err(e.into());
}
}
tracing::debug!("_get_pins_from_blobs: Reading hash list from blobs");
// Read hashes from the hash list blob
let hashes = blobs.read_hash_list(hash).await?;
tracing::debug!(
"_get_pins_from_blobs: Successfully read {} hashes from pinset",
hashes.len()
);
Ok(Pins::from_vec(hashes))
}
async fn _get_node_from_blobs(
node_link: &NodeLink,
blobs: &BlobsStore,
) -> Result<Node, MountError> {
let link = node_link.link();
let secret = node_link.secret();
let hash = link.hash();
tracing::debug!("_get_node_from_blobs: Checking for node at hash {}", hash);
match blobs.stat(&hash).await {
Ok(true) => {
tracing::debug!("_get_node_from_blobs: Node hash {} exists in blobs", hash);
}
Ok(false) => {
tracing::error!(
"_get_node_from_blobs: Node hash {} NOT FOUND in blobs - LinkNotFound error!",
hash
);
return Err(MountError::LinkNotFound(link.clone()));
}
Err(e) => {
tracing::error!(
"_get_node_from_blobs: Error checking node hash {}: {}",
hash,
e
);
return Err(e.into());
}
}
tracing::debug!("_get_node_from_blobs: Reading encrypted node blob");
let blob = blobs.get(&hash).await?;
tracing::debug!(
"_get_node_from_blobs: Got {} bytes of encrypted node data",
blob.len()
);
tracing::debug!("_get_node_from_blobs: Decrypting node data");
let data = secret.decrypt(&blob)?;
tracing::debug!("_get_node_from_blobs: Decrypted {} bytes", data.len());
let node = Node::decode(&data)?;
tracing::debug!("_get_node_from_blobs: Successfully decoded Node");
Ok(node)
}
// TODO (amiller68): you should inline a Link
// into the node when we store encrypt it,
// so that we have an integrity check
async fn _put_node_in_blobs(
node: &Node,
secret: &Secret,
blobs: &BlobsStore,
) -> Result<Link, MountError> {
let _data = node.encode()?;
let data = secret.encrypt(&_data)?;
let hash = blobs.put(data).await?;
// NOTE (amiller68): nodes are always stored as raw
// since they are encrypted blobs
let link = Link::new(crate::linked_data::LD_RAW_CODEC, hash);
Ok(link)
}
pub async fn _put_manifest_in_blobs(
bucket_data: &Manifest,
blobs: &BlobsStore,
) -> Result<Link, MountError> {
let data = bucket_data.encode()?;
let hash = blobs.put(data).await?;
// NOTE (amiller68): buckets are unencrypted, so they can inherit
// the codec of the bucket itself (which is currently always cbor)
let link = Link::new(bucket_data.codec(), hash);
Ok(link)
}
pub async fn _put_pins_in_blobs(pins: &Pins, blobs: &BlobsStore) -> Result<Link, MountError> {
// Create a hash list blob from the pins (raw bytes: 32 bytes per hash, concatenated)
let hash = blobs.create_hash_list(pins.iter().copied()).await?;
// Pins are stored as raw blobs containing concatenated hashes
// Note: The underlying blob is HashSeq format, but Link doesn't track this
let link = Link::new(crate::linked_data::LD_RAW_CODEC, hash);
Ok(link)
}
async fn _get_ops_log_from_blobs(
link: &Link,
secret: &Secret,
blobs: &BlobsStore,
) -> Result<PathOpLog, MountError> {
let hash = link.hash();
tracing::debug!(
"_get_ops_log_from_blobs: Checking for ops log at hash {}",
hash
);
match blobs.stat(&hash).await {
Ok(true) => {
tracing::debug!(
"_get_ops_log_from_blobs: Ops log hash {} exists in blobs",
hash
);
}
Ok(false) => {
tracing::error!(
"_get_ops_log_from_blobs: Ops log hash {} NOT FOUND in blobs - LinkNotFound error!",
hash
);
return Err(MountError::LinkNotFound(link.clone()));
}
Err(e) => {
tracing::error!(
"_get_ops_log_from_blobs: Error checking ops log hash {}: {}",
hash,
e
);
return Err(e.into());
}
}
tracing::debug!("_get_ops_log_from_blobs: Reading encrypted ops log blob");
let blob = blobs.get(&hash).await?;
tracing::debug!(
"_get_ops_log_from_blobs: Got {} bytes of encrypted ops log data",
blob.len()
);
tracing::debug!("_get_ops_log_from_blobs: Decrypting ops log data");
let data = secret.decrypt(&blob)?;
tracing::debug!("_get_ops_log_from_blobs: Decrypted {} bytes", data.len());
let ops_log = PathOpLog::decode(&data)?;
tracing::debug!(
"_get_ops_log_from_blobs: Successfully decoded PathOpLog with {} operations",
ops_log.len()
);
Ok(ops_log)
}
async fn _put_ops_log_in_blobs(
ops_log: &PathOpLog,
secret: &Secret,
blobs: &BlobsStore,
) -> Result<Link, MountError> {
let _data = ops_log.encode()?;
let data = secret.encrypt(&_data)?;
let hash = blobs.put(data).await?;
// Ops log is stored as an encrypted raw blob
let link = Link::new(crate::linked_data::LD_RAW_CODEC, hash);
tracing::debug!(
"_put_ops_log_in_blobs: Stored ops log with {} operations at hash {}",
ops_log.len(),
hash
);
Ok(link)
}
/// Collect all ops from manifest chain back to (but not including) ancestor_link.
///
/// Traverses the manifest chain starting from the current version, collecting
/// ops_logs from each manifest until we reach the ancestor (or genesis).
/// The collected ops are merged in chronological order.
///
/// # Arguments
///
/// * `ancestor_link` - Stop when reaching this link (not included). None means collect all
/// accessible ops (stops when we can't decrypt a manifest).
/// * `blobs` - The blob store to read manifests from
///
/// # Returns
///
/// A combined PathOpLog containing all operations since the ancestor.
pub async fn collect_ops_since(
&self,
ancestor_link: Option<&Link>,
blobs: &BlobsStore,
) -> Result<PathOpLog, MountError> {
let inner = self.0.lock().await;
let secret_key = inner.secret_key.clone();
let current_link = inner.link.clone();
let current_ops = inner.ops_log.clone();
drop(inner);
let mut all_logs: Vec<PathOpLog> = Vec::new();
// Start with any unsaved operations in the current mount
if !current_ops.is_empty() {
all_logs.push(current_ops);
}
// Walk the chain from current manifest backwards
let mut link = current_link;
loop {
// Check if we've reached the ancestor
if let Some(ancestor) = ancestor_link {
if &link == ancestor {
break;
}
}
// Load the manifest at this link
let manifest = Self::_get_manifest_from_blobs(&link, blobs).await?;
// Get the secret for this manifest version
// If we can't get the secret (e.g., we weren't a member at this point),
// stop traversing - we can't read older ops anyway
let secret = match self.get_secret_for_manifest(&manifest, &secret_key) {
Ok(s) => s,
Err(MountError::ShareNotFound) => {
tracing::debug!(
"collect_ops_since: stopping at link {} - no share for current user",
link.hash()
);
break;
}
Err(e) => return Err(e),
};
// Load the ops_log if present
if let Some(ops_link) = manifest.ops_log() {
let mut ops_log = Self::_get_ops_log_from_blobs(ops_link, &secret, blobs).await?;
ops_log.rebuild_clock();
all_logs.push(ops_log);
}
// Move to previous manifest
match manifest.previous() {
Some(prev) => link = prev.clone(),
None => break, // Reached genesis
}
}
// Merge all logs in chronological order (oldest first, so reverse)
all_logs.reverse();
let mut merged = PathOpLog::new();
for log in all_logs {
merged.merge(&log);
}
Ok(merged)
}
/// Get the decryption secret for a manifest.
///
/// Decrypts the secret share using the provided secret key.
#[allow(clippy::result_large_err)]
fn get_secret_for_manifest(
&self,
manifest: &Manifest,
secret_key: &SecretKey,
) -> Result<Secret, MountError> {
let public_key = secret_key.public();
let share = manifest
.get_share(&public_key)
.ok_or(MountError::ShareNotFound)?;
match share.role() {
PrincipalRole::Owner => {
let secret_share = share.share().ok_or(MountError::ShareNotFound)?;
Ok(secret_share.recover(secret_key)?)
}
PrincipalRole::Mirror => manifest
.public()
.cloned()
.ok_or(MountError::MirrorCannotMount),
}
}
/// Find the common ancestor between this mount's chain and another's.
///
/// Walks both chains backwards via the `previous` links and returns
/// the first link where both chains converge.
///
/// # Arguments
///
/// * `other` - The other mount to find common ancestor with
/// * `blobs` - The blob store to read manifests from
///
/// # Returns
///
/// The common ancestor link, or None if chains never converge (different buckets).
pub async fn find_common_ancestor(
&self,
other: &Mount,
blobs: &BlobsStore,
) -> Result<Option<Link>, MountError> {
// Build set of all links in self's chain
let mut self_chain: std::collections::HashSet<Link> = std::collections::HashSet::new();
let self_link = self.link().await;
let mut link = self_link;
loop {
self_chain.insert(link.clone());
let manifest = Self::_get_manifest_from_blobs(&link, blobs).await?;
match manifest.previous() {
Some(prev) => link = prev.clone(),
None => break,
}
}
// Walk other's chain and find first link in self's set
let other_link = other.link().await;
let mut link = other_link;
loop {
if self_chain.contains(&link) {
return Ok(Some(link));
}
let manifest = Self::_get_manifest_from_blobs(&link, blobs).await?;
match manifest.previous() {
Some(prev) => link = prev.clone(),
None => break,
}
}
// No common ancestor found
Ok(None)
}
/// Apply resolved operations to the entry tree.
///
/// For each operation in the resolved state:
/// - Files with content links are checked for existence (cannot recreate without secret)
/// - Directories are created if they don't exist
async fn apply_resolved_state(&mut self, merged_ops: &PathOpLog) -> Result<(), MountError> {
let resolved_state = merged_ops.resolve_all();
for (path, op) in &resolved_state {
if op.content_link.is_some() {
// File operation - check if it exists in our tree
let abs_path = Path::new("/").join(path);
match self.get(&abs_path).await {
Ok(_) => {
// File exists, skip
}
Err(MountError::PathNotFound(_)) => {
// Can't recreate - ops_log stores Link but not decryption secret
tracing::warn!(
"apply_resolved_state: cannot recreate file {} - no secret",
path.display()
);
// Record in ops_log so it's tracked
let mut inner = self.0.lock().await;
inner.ops_log.merge(&PathOpLog::from_operation(op));
}
Err(e) => return Err(e),
}
} else if op.is_dir && matches!(op.op_type, super::path_ops::OpType::Mkdir) {
// Directory operation - create if missing
let abs_path = Path::new("/").join(path);
match self.mkdir(&abs_path).await {
Ok(()) => {}
Err(MountError::PathAlreadyExists(_)) => {}
Err(e) => return Err(e),
}
}
}
Ok(())
}
/// Merge another mount's changes into this one using the given resolver.
///
/// This method:
/// 1. Finds the common ancestor between the two chains
/// 2. Collects ops from both chains since that ancestor
/// 3. Merges using the resolver
/// 4. Applies the merged state
/// 5. Saves the result as a new version
///
/// # Arguments
///
/// * `incoming` - The mount to merge changes from
/// * `resolver` - The conflict resolution strategy to use
/// * `blobs` - The blob store
///
/// # Returns
///
/// A MergeResult containing conflict information and the new version link.
pub async fn merge_from<R: super::ConflictResolver>(
&mut self,
incoming: &Mount,
resolver: &R,
blobs: &BlobsStore,
) -> Result<(MergeResult, Link), MountError> {
// Find the common ancestor
let ancestor = self.find_common_ancestor(incoming, blobs).await?;
// Collect ops from both chains since the ancestor
let local_ops = self.collect_ops_since(ancestor.as_ref(), blobs).await?;
let incoming_ops = incoming.collect_ops_since(ancestor.as_ref(), blobs).await?;
// Get local peer ID for tie-breaking
let peer_id = {
let inner = self.0.lock().await;
inner.peer_id
};
// Merge the operations
let mut merged_ops = local_ops.clone();
let merge_result = merged_ops.merge_with_resolver(&incoming_ops, resolver, &peer_id);
// Apply merged state to the entry tree
self.apply_resolved_state(&merged_ops).await?;
// Merge the ops_log to include all merged operations
{
let mut inner = self.0.lock().await;
inner.ops_log.merge(&merged_ops);
}
// Save the merged state
let (link, _, _) = self.save(blobs, None).await?;
Ok((merge_result, link))
}
}