about summary refs log tree commit diff
path: root/tvix/castore/src/fs/tests.rs
blob: 226c9975d573c5e2069b4e3b2903c2f9e9f74b1e (plain) (blame)
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
use bstr::ByteSlice;
use bytes::Bytes;
use std::{
    collections::BTreeMap,
    ffi::{OsStr, OsString},
    io::{self, Cursor},
    os::unix::{ffi::OsStrExt, fs::MetadataExt},
    path::Path,
    sync::Arc,
};
use tempfile::TempDir;
use tokio_stream::{wrappers::ReadDirStream, StreamExt};

use super::{fuse::FuseDaemon, TvixStoreFs};
use crate::proto as castorepb;
use crate::proto::node::Node;
use crate::{
    blobservice::{BlobService, MemoryBlobService},
    directoryservice::{DirectoryService, MemoryDirectoryService},
    fixtures,
};

const BLOB_A_NAME: &str = "00000000000000000000000000000000-test";
const BLOB_B_NAME: &str = "55555555555555555555555555555555-test";
const HELLOWORLD_BLOB_NAME: &str = "66666666666666666666666666666666-test";
const SYMLINK_NAME: &str = "11111111111111111111111111111111-test";
const SYMLINK_NAME2: &str = "44444444444444444444444444444444-test";
const DIRECTORY_WITH_KEEP_NAME: &str = "22222222222222222222222222222222-test";
const DIRECTORY_COMPLICATED_NAME: &str = "33333333333333333333333333333333-test";

fn gen_svcs() -> (Arc<dyn BlobService>, Arc<dyn DirectoryService>) {
    (
        Arc::new(MemoryBlobService::default()) as Arc<dyn BlobService>,
        Arc::new(MemoryDirectoryService::default()) as Arc<dyn DirectoryService>,
    )
}

fn do_mount<P: AsRef<Path>, BS, DS>(
    blob_service: BS,
    directory_service: DS,
    root_nodes: BTreeMap<bytes::Bytes, Node>,
    mountpoint: P,
    list_root: bool,
    show_xattr: bool,
) -> io::Result<FuseDaemon>
where
    BS: AsRef<dyn BlobService> + Send + Sync + Clone + 'static,
    DS: AsRef<dyn DirectoryService> + Send + Sync + Clone + 'static,
{
    let fs = TvixStoreFs::new(
        blob_service,
        directory_service,
        Arc::new(root_nodes),
        list_root,
        show_xattr,
    );
    FuseDaemon::new(Arc::new(fs), mountpoint.as_ref(), 4, false)
}

async fn populate_blob_a(
    blob_service: &Arc<dyn BlobService>,
    root_nodes: &mut BTreeMap<Bytes, Node>,
) {
    let mut bw = blob_service.open_write().await;
    tokio::io::copy(&mut Cursor::new(fixtures::BLOB_A.to_vec()), &mut bw)
        .await
        .expect("must succeed uploading");
    bw.close().await.expect("must succeed closing");

    root_nodes.insert(
        BLOB_A_NAME.into(),
        Node::File(castorepb::FileNode {
            name: BLOB_A_NAME.into(),
            digest: fixtures::BLOB_A_DIGEST.clone().into(),
            size: fixtures::BLOB_A.len() as u64,
            executable: false,
        }),
    );
}

async fn populate_blob_b(
    blob_service: &Arc<dyn BlobService>,
    root_nodes: &mut BTreeMap<Bytes, Node>,
) {
    let mut bw = blob_service.open_write().await;
    tokio::io::copy(&mut Cursor::new(fixtures::BLOB_B.to_vec()), &mut bw)
        .await
        .expect("must succeed uploading");
    bw.close().await.expect("must succeed closing");

    root_nodes.insert(
        BLOB_B_NAME.into(),
        Node::File(castorepb::FileNode {
            name: BLOB_B_NAME.into(),
            digest: fixtures::BLOB_B_DIGEST.clone().into(),
            size: fixtures::BLOB_B.len() as u64,
            executable: false,
        }),
    );
}

/// adds a blob containing helloworld and marks it as executable
async fn populate_blob_helloworld(
    blob_service: &Arc<dyn BlobService>,
    root_nodes: &mut BTreeMap<Bytes, Node>,
) {
    let mut bw = blob_service.open_write().await;
    tokio::io::copy(
        &mut Cursor::new(fixtures::HELLOWORLD_BLOB_CONTENTS.to_vec()),
        &mut bw,
    )
    .await
    .expect("must succeed uploading");
    bw.close().await.expect("must succeed closing");

    root_nodes.insert(
        HELLOWORLD_BLOB_NAME.into(),
        Node::File(castorepb::FileNode {
            name: HELLOWORLD_BLOB_NAME.into(),
            digest: fixtures::HELLOWORLD_BLOB_DIGEST.clone().into(),
            size: fixtures::HELLOWORLD_BLOB_CONTENTS.len() as u64,
            executable: true,
        }),
    );
}

async fn populate_symlink(root_nodes: &mut BTreeMap<Bytes, Node>) {
    root_nodes.insert(
        SYMLINK_NAME.into(),
        Node::Symlink(castorepb::SymlinkNode {
            name: SYMLINK_NAME.into(),
            target: BLOB_A_NAME.into(),
        }),
    );
}

/// This writes a symlink pointing to /nix/store/somewhereelse,
/// which is the same symlink target as "aa" inside DIRECTORY_COMPLICATED.
async fn populate_symlink2(root_nodes: &mut BTreeMap<Bytes, Node>) {
    root_nodes.insert(
        SYMLINK_NAME2.into(),
        Node::Symlink(castorepb::SymlinkNode {
            name: SYMLINK_NAME2.into(),
            target: "/nix/store/somewhereelse".into(),
        }),
    );
}

async fn populate_directory_with_keep(
    blob_service: &Arc<dyn BlobService>,
    directory_service: &Arc<dyn DirectoryService>,
    root_nodes: &mut BTreeMap<Bytes, Node>,
) {
    // upload empty blob
    let mut bw = blob_service.open_write().await;
    assert_eq!(
        fixtures::EMPTY_BLOB_DIGEST.as_slice(),
        bw.close().await.expect("must succeed closing").as_slice(),
    );

    // upload directory
    directory_service
        .put(fixtures::DIRECTORY_WITH_KEEP.clone())
        .await
        .expect("must succeed uploading");

    root_nodes.insert(
        DIRECTORY_WITH_KEEP_NAME.into(),
        castorepb::node::Node::Directory(castorepb::DirectoryNode {
            name: DIRECTORY_WITH_KEEP_NAME.into(),
            digest: fixtures::DIRECTORY_WITH_KEEP.digest().into(),
            size: fixtures::DIRECTORY_WITH_KEEP.size(),
        }),
    );
}

/// Create a root node for DIRECTORY_WITH_KEEP, but don't upload the Directory
/// itself.
async fn populate_directorynode_without_directory(root_nodes: &mut BTreeMap<Bytes, Node>) {
    root_nodes.insert(
        DIRECTORY_WITH_KEEP_NAME.into(),
        castorepb::node::Node::Directory(castorepb::DirectoryNode {
            name: DIRECTORY_WITH_KEEP_NAME.into(),
            digest: fixtures::DIRECTORY_WITH_KEEP.digest().into(),
            size: fixtures::DIRECTORY_WITH_KEEP.size(),
        }),
    );
}

/// Insert BLOB_A, but don't provide the blob .keep is pointing to.
async fn populate_filenode_without_blob(root_nodes: &mut BTreeMap<Bytes, Node>) {
    root_nodes.insert(
        BLOB_A_NAME.into(),
        Node::File(castorepb::FileNode {
            name: BLOB_A_NAME.into(),
            digest: fixtures::BLOB_A_DIGEST.clone().into(),
            size: fixtures::BLOB_A.len() as u64,
            executable: false,
        }),
    );
}

async fn populate_directory_complicated(
    blob_service: &Arc<dyn BlobService>,
    directory_service: &Arc<dyn DirectoryService>,
    root_nodes: &mut BTreeMap<Bytes, Node>,
) {
    // upload empty blob
    let mut bw = blob_service.open_write().await;
    assert_eq!(
        fixtures::EMPTY_BLOB_DIGEST.as_slice(),
        bw.close().await.expect("must succeed closing").as_slice(),
    );

    // upload inner directory
    directory_service
        .put(fixtures::DIRECTORY_WITH_KEEP.clone())
        .await
        .expect("must succeed uploading");

    // upload parent directory
    directory_service
        .put(fixtures::DIRECTORY_COMPLICATED.clone())
        .await
        .expect("must succeed uploading");

    root_nodes.insert(
        DIRECTORY_COMPLICATED_NAME.into(),
        Node::Directory(castorepb::DirectoryNode {
            name: DIRECTORY_COMPLICATED_NAME.into(),
            digest: fixtures::DIRECTORY_COMPLICATED.digest().into(),
            size: fixtures::DIRECTORY_COMPLICATED.size(),
        }),
    );
}

/// Ensure mounting itself doesn't fail
#[tokio::test]
async fn mount() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }

    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        BTreeMap::default(),
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    fuse_daemon.unmount().expect("unmount");
}
/// Ensure listing the root isn't allowed
#[tokio::test]
async fn root() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        BTreeMap::default(),
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    {
        // read_dir succeeds, but getting the first element will fail.
        let mut it = ReadDirStream::new(tokio::fs::read_dir(tmpdir).await.expect("must succeed"));

        let err = it
            .next()
            .await
            .expect("must be some")
            .expect_err("must be err");
        assert_eq!(std::io::ErrorKind::PermissionDenied, err.kind());
    }

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure listing the root is allowed if configured explicitly
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn root_with_listing() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_a(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        true, /* allow listing */
        false,
    )
    .expect("must succeed");

    {
        // read_dir succeeds, but getting the first element will fail.
        let mut it = ReadDirStream::new(tokio::fs::read_dir(tmpdir).await.expect("must succeed"));

        let e = it
            .next()
            .await
            .expect("must be some")
            .expect("must succeed");

        let metadata = e.metadata().await.expect("must succeed");
        assert!(metadata.is_file());
        assert!(metadata.permissions().readonly());
        assert_eq!(fixtures::BLOB_A.len() as u64, metadata.len());
    }

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure we can stat a file at the root
#[tokio::test]
async fn stat_file_at_root() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_a(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(BLOB_A_NAME);

    // peek at the file metadata
    let metadata = tokio::fs::metadata(p).await.expect("must succeed");

    assert!(metadata.is_file());
    assert!(metadata.permissions().readonly());
    assert_eq!(fixtures::BLOB_A.len() as u64, metadata.len());

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure we can read a file at the root
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_file_at_root() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_a(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(BLOB_A_NAME);

    // read the file contents
    let data = tokio::fs::read(p).await.expect("must succeed");

    // ensure size and contents match
    assert_eq!(fixtures::BLOB_A.len(), data.len());
    assert_eq!(fixtures::BLOB_A.to_vec(), data);

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure we can read a large file at the root
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_large_file_at_root() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_b(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(BLOB_B_NAME);
    {
        // peek at the file metadata
        let metadata = tokio::fs::metadata(&p).await.expect("must succeed");

        assert!(metadata.is_file());
        assert!(metadata.permissions().readonly());
        assert_eq!(fixtures::BLOB_B.len() as u64, metadata.len());
    }

    // read the file contents
    let data = tokio::fs::read(p).await.expect("must succeed");

    // ensure size and contents match
    assert_eq!(fixtures::BLOB_B.len(), data.len());
    assert_eq!(fixtures::BLOB_B.to_vec(), data);

    fuse_daemon.unmount().expect("unmount");
}

/// Read the target of a symlink
#[tokio::test]
async fn symlink_readlink() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_symlink(&mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(SYMLINK_NAME);

    let target = tokio::fs::read_link(&p).await.expect("must succeed");
    assert_eq!(BLOB_A_NAME, target.to_str().unwrap());

    // peek at the file metadata, which follows symlinks.
    // this must fail, as we didn't populate the target.
    let e = tokio::fs::metadata(&p).await.expect_err("must fail");
    assert_eq!(std::io::ErrorKind::NotFound, e.kind());

    // peeking at the file metadata without following symlinks will succeed.
    let metadata = tokio::fs::symlink_metadata(&p).await.expect("must succeed");
    assert!(metadata.is_symlink());

    // reading from the symlink (which follows) will fail, because the target doesn't exist.
    let e = tokio::fs::read(p).await.expect_err("must fail");
    assert_eq!(std::io::ErrorKind::NotFound, e.kind());

    fuse_daemon.unmount().expect("unmount");
}

/// Read and stat a regular file through a symlink pointing to it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_stat_through_symlink() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_a(&blob_service, &mut root_nodes).await;
    populate_symlink(&mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p_symlink = tmpdir.path().join(SYMLINK_NAME);
    let p_blob = tmpdir.path().join(SYMLINK_NAME);

    // peek at the file metadata, which follows symlinks.
    // this must now return the same metadata as when statting at the target directly.
    let metadata_symlink = tokio::fs::metadata(&p_symlink).await.expect("must succeed");
    let metadata_blob = tokio::fs::metadata(&p_blob).await.expect("must succeed");
    assert_eq!(metadata_blob.file_type(), metadata_symlink.file_type());
    assert_eq!(metadata_blob.len(), metadata_symlink.len());

    // reading from the symlink (which follows) will return the same data as if
    // we were reading from the file directly.
    assert_eq!(
        tokio::fs::read(p_blob).await.expect("must succeed"),
        tokio::fs::read(p_symlink).await.expect("must succeed"),
    );

    fuse_daemon.unmount().expect("unmount");
}

/// Read a directory in the root, and validate some attributes.
#[tokio::test]
async fn read_stat_directory() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_with_keep(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(DIRECTORY_WITH_KEEP_NAME);

    // peek at the metadata of the directory
    let metadata = tokio::fs::metadata(p).await.expect("must succeed");
    assert!(metadata.is_dir());
    assert!(metadata.permissions().readonly());

    fuse_daemon.unmount().expect("unmount");
}

/// Read a directory and file in the root, and ensure the xattrs expose blob or
/// directory digests.
#[tokio::test]
async fn xattr() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_with_keep(&blob_service, &directory_service, &mut root_nodes).await;
    populate_blob_a(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        true, /* support xattr */
    )
    .expect("must succeed");

    // peek at the directory
    {
        let p = tmpdir.path().join(DIRECTORY_WITH_KEEP_NAME);

        let xattr_names: Vec<OsString> = xattr::list(&p).expect("must succeed").collect();
        // There should be 1 key, XATTR_NAME_DIRECTORY_DIGEST.
        assert_eq!(1, xattr_names.len(), "there should be 1 xattr name");
        assert_eq!(
            super::XATTR_NAME_DIRECTORY_DIGEST,
            xattr_names.first().unwrap().as_encoded_bytes()
        );

        // The key should equal to the string-formatted b3 digest.
        let val = xattr::get(&p, OsStr::from_bytes(super::XATTR_NAME_DIRECTORY_DIGEST))
            .expect("must succeed")
            .expect("must be some");
        assert_eq!(
            fixtures::DIRECTORY_WITH_KEEP
                .digest()
                .to_string()
                .as_bytes()
                .as_bstr(),
            val.as_bstr()
        );

        // Reading another xattr key is gonna return None.
        let val = xattr::get(&p, OsStr::from_bytes(b"user.cheesecake")).expect("must succeed");
        assert_eq!(None, val);
    }
    // peek at the file
    {
        let p = tmpdir.path().join(BLOB_A_NAME);

        let xattr_names: Vec<OsString> = xattr::list(&p).expect("must succeed").collect();
        // There should be 1 key, XATTR_NAME_BLOB_DIGEST.
        assert_eq!(1, xattr_names.len(), "there should be 1 xattr name");
        assert_eq!(
            super::XATTR_NAME_BLOB_DIGEST,
            xattr_names.first().unwrap().as_encoded_bytes()
        );

        // The key should equal to the string-formatted b3 digest.
        let val = xattr::get(&p, OsStr::from_bytes(super::XATTR_NAME_BLOB_DIGEST))
            .expect("must succeed")
            .expect("must be some");
        assert_eq!(
            fixtures::BLOB_A_DIGEST.to_string().as_bytes().as_bstr(),
            val.as_bstr()
        );

        // Reading another xattr key is gonna return None.
        let val = xattr::get(&p, OsStr::from_bytes(b"user.cheesecake")).expect("must succeed");
        assert_eq!(None, val);
    }

    fuse_daemon.unmount().expect("unmount");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
/// Read a blob inside a directory. This ensures we successfully populate directory data.
async fn read_blob_inside_dir() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_with_keep(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(DIRECTORY_WITH_KEEP_NAME).join(".keep");

    // peek at metadata.
    let metadata = tokio::fs::metadata(&p).await.expect("must succeed");
    assert!(metadata.is_file());
    assert!(metadata.permissions().readonly());

    // read from it
    let data = tokio::fs::read(&p).await.expect("must succeed");
    assert_eq!(fixtures::EMPTY_BLOB_CONTENTS.to_vec(), data);

    fuse_daemon.unmount().expect("unmount");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
/// Read a blob inside a directory inside a directory. This ensures we properly
/// populate directories as we traverse down the structure.
async fn read_blob_deep_inside_dir() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_complicated(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir
        .path()
        .join(DIRECTORY_COMPLICATED_NAME)
        .join("keep")
        .join(".keep");

    // peek at metadata.
    let metadata = tokio::fs::metadata(&p).await.expect("must succeed");
    assert!(metadata.is_file());
    assert!(metadata.permissions().readonly());

    // read from it
    let data = tokio::fs::read(&p).await.expect("must succeed");
    assert_eq!(fixtures::EMPTY_BLOB_CONTENTS.to_vec(), data);

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure readdir works.
#[tokio::test]
async fn readdir() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_complicated(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(DIRECTORY_COMPLICATED_NAME);

    {
        // read_dir should succeed. Collect all elements
        let elements: Vec<_> =
            ReadDirStream::new(tokio::fs::read_dir(p).await.expect("must succeed"))
                .map(|e| e.expect("must not be err"))
                .collect()
                .await;

        assert_eq!(3, elements.len(), "number of elements should be 3"); // rust skips . and ..

        // We explicitly look at specific positions here, because we always emit
        // them ordered.

        // ".keep", 0 byte file.
        let e = &elements[0];
        assert_eq!(".keep", e.file_name());
        assert!(e.file_type().await.expect("must succeed").is_file());
        assert_eq!(0, e.metadata().await.expect("must succeed").len());

        // "aa", symlink.
        let e = &elements[1];
        assert_eq!("aa", e.file_name());
        assert!(e.file_type().await.expect("must succeed").is_symlink());

        // "keep", directory
        let e = &elements[2];
        assert_eq!("keep", e.file_name());
        assert!(e.file_type().await.expect("must succeed").is_dir());
    }

    fuse_daemon.unmount().expect("unmount");
}

#[tokio::test]
/// Do a readdir deeper inside a directory, without doing readdir or stat in the parent directory.
async fn readdir_deep() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_complicated(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(DIRECTORY_COMPLICATED_NAME).join("keep");

    {
        // read_dir should succeed. Collect all elements
        let elements: Vec<_> =
            ReadDirStream::new(tokio::fs::read_dir(p).await.expect("must succeed"))
                .map(|e| e.expect("must not be err"))
                .collect()
                .await;

        assert_eq!(1, elements.len(), "number of elements should be 1"); // rust skips . and ..

        // ".keep", 0 byte file.
        let e = &elements[0];
        assert_eq!(".keep", e.file_name());
        assert!(e.file_type().await.expect("must succeed").is_file());
        assert_eq!(0, e.metadata().await.expect("must succeed").len());
    }

    fuse_daemon.unmount().expect("unmount");
}

/// Check attributes match how they show up in /nix/store normally.
#[tokio::test]
async fn check_attributes() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_a(&blob_service, &mut root_nodes).await;
    populate_directory_with_keep(&blob_service, &directory_service, &mut root_nodes).await;
    populate_symlink(&mut root_nodes).await;
    populate_blob_helloworld(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p_file = tmpdir.path().join(BLOB_A_NAME);
    let p_directory = tmpdir.path().join(DIRECTORY_WITH_KEEP_NAME);
    let p_symlink = tmpdir.path().join(SYMLINK_NAME);
    let p_executable_file = tmpdir.path().join(HELLOWORLD_BLOB_NAME);

    // peek at metadata. We use symlink_metadata to ensure we don't traverse a symlink by accident.
    let metadata_file = tokio::fs::symlink_metadata(&p_file)
        .await
        .expect("must succeed");
    let metadata_executable_file = tokio::fs::symlink_metadata(&p_executable_file)
        .await
        .expect("must succeed");
    let metadata_directory = tokio::fs::symlink_metadata(&p_directory)
        .await
        .expect("must succeed");
    let metadata_symlink = tokio::fs::symlink_metadata(&p_symlink)
        .await
        .expect("must succeed");

    // modes should match. We & with 0o777 to remove any higher bits.
    assert_eq!(0o444, metadata_file.mode() & 0o777);
    assert_eq!(0o555, metadata_executable_file.mode() & 0o777);
    assert_eq!(0o555, metadata_directory.mode() & 0o777);
    assert_eq!(0o444, metadata_symlink.mode() & 0o777);

    // files should have the correct filesize
    assert_eq!(fixtures::BLOB_A.len() as u64, metadata_file.len());
    // directories should have their "size" as filesize
    assert_eq!(
        { fixtures::DIRECTORY_WITH_KEEP.size() },
        metadata_directory.size()
    );

    for metadata in &[&metadata_file, &metadata_directory, &metadata_symlink] {
        // uid and gid should be 0.
        assert_eq!(0, metadata.uid());
        assert_eq!(0, metadata.gid());

        // all times should be set to the unix epoch.
        assert_eq!(0, metadata.atime());
        assert_eq!(0, metadata.mtime());
        assert_eq!(0, metadata.ctime());
        // crtime seems MacOS only
    }

    fuse_daemon.unmount().expect("unmount");
}

#[tokio::test]
/// Ensure we allocate the same inodes for the same directory contents.
/// $DIRECTORY_COMPLICATED_NAME/keep contains the same data as $DIRECTORY_WITH_KEEP.
async fn compare_inodes_directories() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_with_keep(&blob_service, &directory_service, &mut root_nodes).await;
    populate_directory_complicated(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p_dir_with_keep = tmpdir.path().join(DIRECTORY_WITH_KEEP_NAME);
    let p_sibling_dir = tmpdir.path().join(DIRECTORY_COMPLICATED_NAME).join("keep");

    // peek at metadata.
    assert_eq!(
        tokio::fs::metadata(p_dir_with_keep)
            .await
            .expect("must succeed")
            .ino(),
        tokio::fs::metadata(p_sibling_dir)
            .await
            .expect("must succeed")
            .ino()
    );

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure we allocate the same inodes for the same directory contents.
/// $DIRECTORY_COMPLICATED_NAME/keep/,keep contains the same data as $DIRECTORY_COMPLICATED_NAME/.keep
#[tokio::test]
async fn compare_inodes_files() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_complicated(&blob_service, &directory_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p_keep1 = tmpdir.path().join(DIRECTORY_COMPLICATED_NAME).join(".keep");
    let p_keep2 = tmpdir
        .path()
        .join(DIRECTORY_COMPLICATED_NAME)
        .join("keep")
        .join(".keep");

    // peek at metadata.
    assert_eq!(
        tokio::fs::metadata(p_keep1)
            .await
            .expect("must succeed")
            .ino(),
        tokio::fs::metadata(p_keep2)
            .await
            .expect("must succeed")
            .ino()
    );

    fuse_daemon.unmount().expect("unmount");
}

/// Ensure we allocate the same inode for symlinks pointing to the same targets.
/// $DIRECTORY_COMPLICATED_NAME/aa points to the same target as SYMLINK_NAME2.
#[tokio::test]
async fn compare_inodes_symlinks() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directory_complicated(&blob_service, &directory_service, &mut root_nodes).await;
    populate_symlink2(&mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p1 = tmpdir.path().join(DIRECTORY_COMPLICATED_NAME).join("aa");
    let p2 = tmpdir.path().join(SYMLINK_NAME2);

    // peek at metadata.
    assert_eq!(
        tokio::fs::symlink_metadata(p1)
            .await
            .expect("must succeed")
            .ino(),
        tokio::fs::symlink_metadata(p2)
            .await
            .expect("must succeed")
            .ino()
    );

    fuse_daemon.unmount().expect("unmount");
}

/// Check we match paths exactly.
#[tokio::test]
async fn read_wrong_paths_in_root() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_blob_a(&blob_service, &mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    // wrong name
    assert!(
        tokio::fs::metadata(tmpdir.path().join("00000000000000000000000000000000-tes"))
            .await
            .is_err()
    );

    // invalid hash
    assert!(
        tokio::fs::metadata(tmpdir.path().join("0000000000000000000000000000000-test"))
            .await
            .is_err()
    );

    // right name, must exist
    assert!(
        tokio::fs::metadata(tmpdir.path().join("00000000000000000000000000000000-test"))
            .await
            .is_ok()
    );

    // now wrong name with right hash still may not exist
    assert!(
        tokio::fs::metadata(tmpdir.path().join("00000000000000000000000000000000-tes"))
            .await
            .is_err()
    );

    fuse_daemon.unmount().expect("unmount");
}

/// Make sure writes are not allowed
#[tokio::test]
async fn disallow_writes() {
    // https://plume.benboeckel.net/~/JustAnotherBlog/skipping-tests-in-rust
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }

    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let root_nodes = BTreeMap::default();

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(BLOB_A_NAME);
    let e = tokio::fs::File::create(p).await.expect_err("must fail");

    assert_eq!(Some(libc::EROFS), e.raw_os_error());

    fuse_daemon.unmount().expect("unmount");
}

#[tokio::test]
/// Ensure we get an IO error if the directory service does not have the Directory object.
async fn missing_directory() {
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_directorynode_without_directory(&mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(DIRECTORY_WITH_KEEP_NAME);

    {
        // `stat` on the path should succeed, because it doesn't trigger the directory request.
        tokio::fs::metadata(&p).await.expect("must succeed");

        // However, calling either `readdir` or `stat` on a child should fail with an IO error.
        // It fails when trying to pull the first entry, because we don't implement opendir separately
        ReadDirStream::new(tokio::fs::read_dir(&p).await.unwrap())
            .next()
            .await
            .expect("must be some")
            .expect_err("must be err");

        // rust currently sets e.kind() to Uncategorized, which isn't very
        // helpful, so we don't look at the error more closely than that..
        tokio::fs::metadata(p.join(".keep"))
            .await
            .expect_err("must fail");
    }

    fuse_daemon.unmount().expect("unmount");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
/// Ensure we get an IO error if the blob service does not have the blob
async fn missing_blob() {
    if !std::path::Path::new("/dev/fuse").exists() {
        eprintln!("skipping test");
        return;
    }
    let tmpdir = TempDir::new().unwrap();

    let (blob_service, directory_service) = gen_svcs();
    let mut root_nodes = BTreeMap::default();

    populate_filenode_without_blob(&mut root_nodes).await;

    let mut fuse_daemon = do_mount(
        blob_service,
        directory_service,
        root_nodes,
        tmpdir.path(),
        false,
        false,
    )
    .expect("must succeed");

    let p = tmpdir.path().join(BLOB_A_NAME);

    {
        // `stat` on the blob should succeed, because it doesn't trigger a request to the blob service.
        tokio::fs::metadata(&p).await.expect("must succeed");

        // However, calling read on the blob should fail.
        // rust currently sets e.kind() to Uncategorized, which isn't very
        // helpful, so we don't look at the error more closely than that..
        tokio::fs::read(p).await.expect_err("must fail");
    }

    fuse_daemon.unmount().expect("unmount");
}