vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
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
//! Integration tests for the Engine.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use engine::{
    AuthorizationData, AuthorizationPolicy, AuthorizationRequest, AuthorizationResult,
    CreateOptions, Engine, Error, EventType, MetadataPatch, MetadataValue, Name, SubscriptionId,
    Timestamp, VirtualPath,
};

fn new_engine() -> Arc<Engine> {
    Arc::new(Engine::default())
}

fn name(value: &str) -> Name {
    Name::new(value).expect("valid name")
}

/// A policy that denies everything.
#[derive(Default)]
struct DenyAll;

impl AuthorizationPolicy for DenyAll {
    fn authorize(&self, _request: &AuthorizationRequest<'_>) -> AuthorizationResult {
        AuthorizationResult::Denied {
            reason: Some("denied by test policy".to_owned()),
        }
    }
}

// ----------------------------------------------------------------------
// Object model and filesystem
// ----------------------------------------------------------------------

#[test]
fn root_is_a_directory() {
    let engine = new_engine();
    let root = engine.root();
    assert!(engine.exists(root));
    assert_eq!(engine.metadata(None, root).unwrap().name().as_str(), "/");
    assert!(engine.list(None, root).unwrap().is_empty());
}

#[test]
fn create_and_lookup_roundtrip() {
    let engine = new_engine();
    let root = engine.root();
    let path = "/usr/bin/ls".parse::<VirtualPath>().unwrap();

    let usr = engine.create_directory(None, root, name("usr")).unwrap();
    let bin = engine.create_directory(None, usr, name("bin")).unwrap();
    let ls = engine
        .create_file(None, bin, name("ls"), Some(b"#!/bin/sh\n".to_vec()))
        .unwrap();

    assert_eq!(engine.lookup(None, &path).unwrap(), ls);
    assert_eq!(engine.read(None, ls).unwrap().unwrap(), b"#!/bin/sh\n");
    assert_eq!(engine.list(None, usr).unwrap(), vec![(name("bin"), bin)]);
}

#[test]
fn identity_survives_move() {
    let engine = new_engine();
    let root = engine.root();
    let home = engine.create_directory(None, root, name("home")).unwrap();
    let rey = engine.create_directory(None, home, name("rey")).unwrap();
    let usr = engine.create_directory(None, root, name("usr")).unwrap();

    let ls = engine.create_file(None, usr, name("ls"), None).unwrap();
    let metadata_before = engine.metadata(None, ls).unwrap();

    engine
        .move_object(None, ls, rey, Some(name("my_ls")))
        .unwrap();

    let new_path = "/home/rey/my_ls".parse::<VirtualPath>().unwrap();
    let old_path = "/usr/bin/ls".parse::<VirtualPath>().unwrap();
    assert_eq!(
        engine.lookup(None, &new_path).unwrap(),
        ls,
        "the moved object must keep its identity"
    );
    assert!(matches!(
        engine.lookup(None, &old_path),
        Err(Error::PathNotFound(_))
    ));
    let metadata_after = engine.metadata(None, ls).unwrap();
    assert_eq!(metadata_after.name().as_str(), "my_ls");
    assert_eq!(metadata_after.created(), metadata_before.created());
    assert_eq!(metadata_after.modified(), metadata_before.modified());
    assert_eq!(metadata_after.accessed(), metadata_before.accessed());
    assert_eq!(metadata_after.owner(), metadata_before.owner());
}

#[test]
fn move_rejects_cycles() {
    let engine = new_engine();
    let root = engine.root();
    let a = engine.create_directory(None, root, name("a")).unwrap();
    let b = engine.create_directory(None, a, name("b")).unwrap();

    assert!(matches!(
        engine.move_object(None, a, b, None),
        Err(Error::CyclicMove(_))
    ));
    assert!(matches!(
        engine.move_object(None, a, a, None),
        Err(Error::CyclicMove(_))
    ));
}

#[test]
fn move_rejects_name_conflicts() {
    let engine = new_engine();
    let root = engine.root();
    let dir = engine.create_directory(None, root, name("dir")).unwrap();
    engine.create_file(None, dir, name("a"), None).unwrap();
    let b = engine.create_file(None, dir, name("b"), None).unwrap();

    assert!(matches!(
        engine.move_object(None, b, dir, Some(name("a"))),
        Err(Error::NameAlreadyExists { .. })
    ));
}

// ----------------------------------------------------------------------
// Attach safety
// ----------------------------------------------------------------------

#[test]
fn attach_rejects_an_attached_object() {
    // An object with a parent must not be attachable elsewhere: that would
    // leave it listed under two parents and dangle when deleted from one.
    let engine = new_engine();
    let root = engine.root();
    let p = engine.create_directory(None, root, name("p")).unwrap();
    let q = engine.create_directory(None, root, name("q")).unwrap();
    let f = engine.create_file(None, p, name("f"), None).unwrap();

    assert!(matches!(
        engine.attach_object(None, f, q),
        Err(Error::AttachedObject(_))
    ));

    // The tree is intact: both directories list exactly their own child.
    assert_eq!(engine.children(None, p).unwrap(), vec![f]);
    assert!(engine.children(None, q).unwrap().is_empty());
}

#[test]
fn attach_rejects_cycles() {
    let engine = new_engine();
    let root = engine.root();
    let a = engine.create_directory(None, root, name("a")).unwrap();
    let b = engine.create_directory(None, a, name("b")).unwrap();

    engine.detach_object(None, a).unwrap();
    assert!(matches!(
        engine.attach_object(None, a, b),
        Err(Error::CyclicAttach(_))
    ));
    assert!(matches!(
        engine.attach_object(None, a, a),
        Err(Error::CyclicAttach(_))
    ));

    // Attaching into a *descendant-free* target still works afterwards.
    engine.attach_object(None, a, root).unwrap();
}

#[test]
fn moving_onto_itself_is_a_noop() {
    let engine = new_engine();
    let root = engine.root();
    let dir = engine.create_directory(None, root, name("dir")).unwrap();
    let f = engine.create_file(None, dir, name("f"), None).unwrap();

    // Pure same-parent move, explicit same-name rename: both succeed.
    engine.move_object(None, f, dir, None).unwrap();
    engine.move_object(None, f, dir, Some(name("f"))).unwrap();
    assert_eq!(engine.metadata(None, f).unwrap().name().as_str(), "f");
}

// ----------------------------------------------------------------------
// Event bus semantics
// ----------------------------------------------------------------------

#[test]
fn unsubscribing_during_dispatch_takes_effect_afterwards() {
    use std::sync::{Arc, Mutex};

    let engine = new_engine();
    let root = engine.root();
    let seen: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
    let id_slot: Arc<Mutex<Option<SubscriptionId>>> = Arc::new(Mutex::new(None));

    let seen_handle = Arc::clone(&seen);
    let id_handle = Arc::clone(&id_slot);
    let engine_handle = Arc::clone(&engine);
    let subscription = engine.subscribe(None, move |_event| {
        *seen_handle.lock().unwrap() += 1;
        if let Some(id) = *id_handle.lock().unwrap() {
            engine_handle.unsubscribe(id);
        }
    });
    *id_slot.lock().unwrap() = Some(subscription);

    engine.create_file(None, root, name("first"), None).unwrap();
    engine
        .create_file(None, root, name("second"), None)
        .unwrap();

    assert_eq!(
        *seen.lock().unwrap(),
        1,
        "the self-unsubscribing listener fires exactly once"
    );
    assert_eq!(engine.listener_count(), 0, "the unsubscribe took effect");
}

#[test]
fn a_panicking_listener_is_contained() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let engine = new_engine();
    let root = engine.root();

    let _poison = engine.subscribe(None, |_event| panic!("a broken listener"));
    let good_count = Arc::new(AtomicUsize::new(0));
    let good = {
        let count = Arc::clone(&good_count);
        engine.subscribe(None, move |_event| {
            count.fetch_add(1, Ordering::Relaxed);
        })
    };
    let _ = good;

    // Neither dispatch nor the Engine is damaged by the panicking listener.
    engine.create_file(None, root, name("f"), None).unwrap();
    assert_eq!(
        good_count.load(Ordering::Relaxed),
        1,
        "listeners after the broken one still observe events"
    );
    assert_eq!(
        engine.listener_count(),
        1,
        "only the broken listener is evicted"
    );
}

// ----------------------------------------------------------------------
// Metadata atomicity
// ----------------------------------------------------------------------

#[test]
fn an_invalid_extension_key_applies_nothing() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine.create_file(None, root, name("f"), None).unwrap();

    // Seed a known state with a valid patch.
    let seed = MetadataPatch {
        version: Some(Some("1.0".to_owned())),
        ..MetadataPatch::default()
    };
    engine.update_metadata(None, file, &seed).unwrap();

    // A patch mixing a version change and an invalid key applies nothing.
    let patch = MetadataPatch {
        version: Some(Some("2.0".to_owned())),
        extensions: [(String::new(), Some(MetadataValue::Unsigned(1)))].into(),
        ..MetadataPatch::default()
    };

    assert!(engine.update_metadata(None, file, &patch).is_err());
    let metadata = engine.metadata(None, file).unwrap();
    assert_eq!(metadata.version(), Some("1.0"), "version untouched");
}

#[test]
fn root_cannot_be_moved_or_deleted() {
    let engine = new_engine();
    let root = engine.root();
    assert!(matches!(
        engine.move_object(None, root, root, None),
        Err(Error::RootMove)
    ));
    assert!(matches!(engine.delete(None, root), Err(Error::RootDelete)));
}

#[test]
fn copy_is_deep_and_independent() {
    let engine = new_engine();
    let root = engine.root();
    let src = engine.create_directory(None, root, name("src")).unwrap();
    let file = engine
        .create_file(None, src, name("data.txt"), Some(b"hello".to_vec()))
        .unwrap();
    let backup = engine.create_directory(None, root, name("backup")).unwrap();

    let copy = engine
        .copy_object(None, src, backup, name("src_copy"))
        .unwrap();
    let copy_file = engine
        .lookup(
            None,
            &"/backup/src_copy/data.txt".parse::<VirtualPath>().unwrap(),
        )
        .unwrap();

    assert_ne!(copy, src);
    assert_ne!(copy_file, file);
    assert_eq!(engine.read(None, copy_file).unwrap().unwrap(), b"hello");

    engine.write(None, copy_file, b"changed".to_vec()).unwrap();
    assert_eq!(engine.read(None, file).unwrap().unwrap(), b"hello");
}

#[test]
fn copy_into_own_subtree_is_rejected() {
    let engine = new_engine();
    let root = engine.root();
    let a = engine.create_directory(None, root, name("a")).unwrap();
    let b = engine.create_directory(None, a, name("b")).unwrap();

    assert!(matches!(
        engine.copy_object(None, a, a, name("a2")),
        Err(Error::CyclicCopy(_))
    ));
    assert!(matches!(
        engine.copy_object(None, a, b, name("a2")),
        Err(Error::CyclicCopy(_))
    ));
}

#[test]
fn delete_removes_subtree_deepest_first() {
    let engine = new_engine();
    let root = engine.root();
    let dir = engine.create_directory(None, root, name("dir")).unwrap();
    let file = engine.create_file(None, dir, name("f"), None).unwrap();
    let nested = engine.create_directory(None, dir, name("nested")).unwrap();
    let leaf = engine
        .create_file(None, nested, name("leaf"), None)
        .unwrap();

    let deleted: Arc<std::sync::Mutex<Vec<engine::ObjectId>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));
    let deleted_clone = Arc::clone(&deleted);
    engine.subscribe(EventType::ObjectDeleted, move |event| {
        deleted_clone.lock().unwrap().push(event.object);
    });

    engine.delete(None, dir).unwrap();

    assert!(!engine.exists(dir));
    assert!(!engine.exists(file));
    assert!(!engine.exists(nested));
    assert!(!engine.exists(leaf));
    let order = deleted.lock().unwrap();
    assert_eq!(&*order, &[file, leaf, nested, dir]);
}

#[test]
fn duplicate_names_are_rejected() {
    let engine = new_engine();
    let root = engine.root();
    engine.create_file(None, root, name("a"), None).unwrap();
    assert!(matches!(
        engine.create_file(None, root, name("a"), None),
        Err(Error::NameAlreadyExists { .. })
    ));
}

#[test]
fn metadata_only_files_report_declared_size() {
    let engine = new_engine();
    let root = engine.root();
    let opaque = engine
        .create_file(None, root, name("opaque.bundle"), None)
        .unwrap();
    engine
        .update_metadata(
            None,
            opaque,
            &MetadataPatch {
                declared_size: Some(Some(4096)),
                ..MetadataPatch::default()
            },
        )
        .unwrap();
    assert_eq!(engine.size(None, opaque).unwrap(), 4096);

    engine.write(None, opaque, vec![1, 2, 3]).unwrap();
    assert_eq!(engine.size(None, opaque).unwrap(), 3);
}

// ----------------------------------------------------------------------
// Events
// ----------------------------------------------------------------------

#[test]
fn events_fire_synchronously_before_the_mutation_returns() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine
        .create_file(None, root, name("file.txt"), None)
        .unwrap();
    let report = engine
        .create_file(None, root, name("SCORING_REPORT"), None)
        .unwrap();

    let engine_clone = Arc::clone(&engine);
    engine.subscribe(EventType::ObjectWritten, move |event| {
        if event.object == file {
            engine_clone
                .write(
                    None,
                    report,
                    format!("scored after {:?}", event.event_type).into_bytes(),
                )
                .unwrap();
        }
    });

    engine.write(None, file, b"new contents".to_vec()).unwrap();

    let report_contents = engine.read(None, report).unwrap().unwrap();
    assert_eq!(report_contents, b"scored after ObjectWritten");
}

#[test]
fn subscribing_during_dispatch_does_not_deadlock() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine.create_file(None, root, name("a.txt"), None).unwrap();

    let engine_clone = Arc::clone(&engine);
    engine.subscribe(EventType::ObjectWritten, move |_| {
        engine_clone.subscribe(EventType::ObjectWritten, |_| {});
    });

    engine.write(None, file, vec![1]).unwrap();
    assert_eq!(engine.subscribe(EventType::ObjectCreated, |_| {}).get(), 3);
}

#[test]
fn read_emits_object_read_events() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine
        .create_file(None, root, name("f"), Some(b"x".to_vec()))
        .unwrap();

    let reads = Arc::new(AtomicUsize::new(0));
    let reads_clone = Arc::clone(&reads);
    engine.subscribe(EventType::ObjectRead, move |_| {
        reads_clone.fetch_add(1, Ordering::Relaxed);
    });

    engine.read(None, file).unwrap();
    engine.read(None, file).unwrap();
    assert_eq!(reads.load(Ordering::Relaxed), 2);
}

#[test]
fn unsubscribing_stops_events() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine.create_file(None, root, name("f"), None).unwrap();

    let writes = Arc::new(AtomicUsize::new(0));
    let writes_clone = Arc::clone(&writes);
    let subscription = engine.subscribe(EventType::ObjectWritten, move |_| {
        writes_clone.fetch_add(1, Ordering::Relaxed);
    });

    engine.write(None, file, vec![1]).unwrap();
    engine.unsubscribe(subscription);
    engine.write(None, file, vec![2]).unwrap();
    assert_eq!(writes.load(Ordering::Relaxed), 1);
}

#[test]
fn metadata_events_fire_for_patches() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine.create_file(None, root, name("f"), None).unwrap();

    let owner_events = Arc::new(AtomicUsize::new(0));
    let owner_events_clone = Arc::clone(&owner_events);
    engine.subscribe(EventType::OwnerChanged, move |_| {
        owner_events_clone.fetch_add(1, Ordering::Relaxed);
    });

    engine
        .set_owner(None, file, Some(engine::ActorId::new(1000)))
        .unwrap();
    assert_eq!(owner_events.load(Ordering::Relaxed), 1);
    assert_eq!(
        engine.metadata(None, file).unwrap().owner(),
        Some(engine::ActorId::new(1000))
    );

    engine
        .update_metadata(
            None,
            file,
            &MetadataPatch {
                version: Some(Some("1.0".to_owned())),
                extensions: [(
                    "kind".to_owned(),
                    Some(MetadataValue::String("bundle".to_owned())),
                )]
                .into(),
                ..MetadataPatch::default()
            },
        )
        .unwrap();
    let metadata = engine.metadata(None, file).unwrap();
    assert_eq!(metadata.version(), Some("1.0"));
    assert_eq!(
        metadata.extension("kind"),
        Some(&MetadataValue::String("bundle".to_owned()))
    );
}

// ----------------------------------------------------------------------
// Authorization
// ----------------------------------------------------------------------

#[test]
fn denied_operations_fail_without_mutating_state() {
    let engine = Arc::new(Engine::with_virtual_clock(Box::new(DenyAll)));
    let root = engine.root();

    let events = Arc::new(AtomicUsize::new(0));
    let events_clone = Arc::clone(&events);
    engine.subscribe(None, move |_| {
        events_clone.fetch_add(1, Ordering::Relaxed);
    });

    let denied: Vec<Result<(), Error>> = vec![
        engine.create_file(None, root, name("f"), None).map(|_| ()),
        engine.create_directory(None, root, name("d")).map(|_| ()),
        engine.read(None, root).map(|_| ()),
        engine.metadata(None, root).map(|_| ()),
        engine.delete(None, root).map(|_| ()),
    ];
    for result in denied {
        assert!(matches!(result, Err(Error::NotAuthorized { .. })));
    }
    assert_eq!(events.load(Ordering::Relaxed), 0);
}

#[test]
fn lookup_authorizes_traversal_before_the_final_object() {
    // A policy that denies only directory-execute: path resolution must
    // consult it for every component stepped through, before any check of
    // the final object.
    struct DenyTraversal;
    impl AuthorizationPolicy for DenyTraversal {
        fn authorize(&self, request: &AuthorizationRequest<'_>) -> AuthorizationResult {
            match request.operation {
                engine::Operation::Execute => AuthorizationResult::Denied {
                    reason: Some("traversal forbidden".to_owned()),
                },
                _ => AuthorizationResult::Allowed,
            }
        }
    }

    let engine = Arc::new(Engine::with_virtual_clock(Box::new(DenyTraversal)));
    let root = engine.root();
    let dir = engine.create_directory(None, root, name("dir")).unwrap();
    engine.create_file(None, dir, name("f"), None).unwrap();

    // Resolving / itself steps through nothing.
    engine
        .lookup(None, &"/".parse::<VirtualPath>().unwrap())
        .expect("the root has no components to traverse");

    let error = engine
        .lookup(None, &"/dir/f".parse::<VirtualPath>().unwrap())
        .expect_err("traversal through dir is denied");
    assert!(matches!(
        error,
        Error::NotAuthorized {
            operation: engine::Operation::Execute,
            ..
        }
    ));
}

#[test]
fn change_owner_is_a_distinct_operation() {
    struct NoOwnerChanges;
    impl AuthorizationPolicy for NoOwnerChanges {
        fn authorize(&self, request: &AuthorizationRequest<'_>) -> AuthorizationResult {
            match request.operation {
                engine::Operation::ChangeOwner => AuthorizationResult::Denied {
                    reason: Some("owner changes forbidden".to_owned()),
                },
                _ => AuthorizationResult::Allowed,
            }
        }
    }

    let engine = Arc::new(Engine::with_virtual_clock(Box::new(NoOwnerChanges)));
    let root = engine.root();
    let file = engine.create_file(None, root, name("f"), None).unwrap();

    let owner_change = engine.set_owner(None, file, Some(engine::ActorId::new(7)));
    assert!(matches!(owner_change, Err(Error::NotAuthorized { .. })));

    let metadata_change = engine.touch(None, file);
    assert!(metadata_change.is_ok());
}

#[test]
fn create_with_options_sets_owner_and_authorization_atomically() {
    let engine = new_engine();
    let root = engine.root();
    let options = CreateOptions {
        owner: Some(engine::ActorId::new(501)),
        authorization: {
            let mut data = AuthorizationData::new();
            data.insert("mode", "755");
            data
        },
    };
    let file = engine
        .create_file_with_options(None, root, name("f"), Some(b"x".to_vec()), options)
        .unwrap();

    let metadata = engine.metadata(None, file).unwrap();
    assert_eq!(metadata.owner(), Some(engine::ActorId::new(501)));
    assert_eq!(metadata.authorization().get("mode"), Some("755"));
}

#[test]
fn replace_file_with_options_commits_content_and_metadata_together() {
    let engine = new_engine();
    let file = engine
        .create_file(None, engine.root(), name("f"), Some(b"old".to_vec()))
        .unwrap();
    let mut authorization = AuthorizationData::new();
    authorization.insert("mode", "600");
    engine
        .replace_file_with_options(
            None,
            file,
            b"new".to_vec(),
            CreateOptions {
                owner: Some(engine::ActorId::new(501)),
                authorization,
            },
        )
        .unwrap();

    assert_eq!(engine.read(None, file).unwrap().unwrap(), b"new");
    let metadata = engine.metadata(None, file).unwrap();
    assert_eq!(metadata.owner(), Some(engine::ActorId::new(501)));
    assert_eq!(metadata.authorization().get("mode"), Some("600"));
}

#[test]
fn create_with_options_is_authorization_checked_like_create() {
    let engine = Arc::new(Engine::with_virtual_clock(Box::new(DenyAll)));
    let result = engine.create_directory_with_options(
        None,
        engine.root(),
        name("d"),
        CreateOptions::default(),
    );
    assert!(matches!(result, Err(Error::NotAuthorized { .. })));
}

#[test]
fn copy_events_carry_the_source() {
    let engine = new_engine();
    let root = engine.root();
    let dir = engine.create_directory(None, root, name("dir")).unwrap();
    engine.create_file(None, dir, name("f"), None).unwrap();

    let copies: Arc<std::sync::Mutex<Vec<engine::ObjectEvent>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));
    let copies_clone = Arc::clone(&copies);
    engine.subscribe(EventType::ObjectCopied, move |event| {
        copies_clone.lock().unwrap().push(event.clone());
    });

    let backup = engine.create_directory(None, root, name("backup")).unwrap();
    engine
        .copy_object(None, dir, backup, name("dir_copy"))
        .unwrap();

    let copy_event = &copies.lock().unwrap()[0];
    assert_eq!(
        copy_event.data.get("source"),
        Some(&MetadataValue::Unsigned(dir.get()))
    );
}

// ----------------------------------------------------------------------
// Detached namespaces
// ----------------------------------------------------------------------

#[test]
fn detached_namespaces_are_invisible_from_the_root() {
    let engine = new_engine();
    let root = engine.root();
    let namespace = engine
        .create_detached_namespace(None, name("processes"))
        .unwrap();
    let proc = engine
        .create_file(None, namespace.id(), name("4812"), None)
        .unwrap();

    assert!(engine.exists(proc));
    assert!(matches!(
        engine.lookup(None, &"/processes/4812".parse::<VirtualPath>().unwrap()),
        Err(Error::PathNotFound(_))
    ));
    assert!(engine.list(None, root).unwrap().is_empty());

    engine.write(None, proc, b"running".to_vec()).unwrap();
    assert_eq!(engine.read(None, proc).unwrap().unwrap(), b"running");
}

#[test]
fn detach_and_attach_move_objects_between_tree_and_store() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine.create_file(None, root, name("f"), None).unwrap();
    let mnt = engine.create_directory(None, root, name("mnt")).unwrap();

    engine.detach_object(None, file).unwrap();
    assert_eq!(engine.parent(None, file).unwrap(), None);
    assert!(matches!(
        engine.lookup(None, &"/f".parse::<VirtualPath>().unwrap()),
        Err(Error::PathNotFound(_))
    ));

    engine.attach_object(None, file, mnt).unwrap();
    assert_eq!(
        engine
            .lookup(None, &"/mnt/f".parse::<VirtualPath>().unwrap())
            .unwrap(),
        file
    );
}

// ----------------------------------------------------------------------
// Time (virtual clock)
// ----------------------------------------------------------------------

#[test]
fn virtual_clock_is_frozen_until_advanced() {
    let engine = new_engine();
    let root = engine.root();

    engine.set_time(Timestamp::from_nanos(1_000));
    let file = engine.create_file(None, root, name("f"), None).unwrap();
    let created = engine.metadata(None, file).unwrap().created();
    assert_eq!(created, Timestamp::from_nanos(1_000));

    engine.advance_time(Duration::from_secs(10));
    engine.write(None, file, vec![1]).unwrap();
    let metadata = engine.metadata(None, file).unwrap();
    assert_eq!(metadata.created(), created);
    assert_eq!(metadata.modified(), Timestamp::from_nanos(10_000_001_000));
}

#[test]
fn read_does_not_update_access_time() {
    let engine = new_engine();
    let root = engine.root();
    let file = engine.create_file(None, root, name("f"), None).unwrap();

    engine.advance_time(Duration::from_secs(60));
    engine.read(None, file).unwrap();

    let metadata = engine.metadata(None, file).unwrap();
    assert_eq!(metadata.accessed(), metadata.created());
}

#[test]
fn suspended_time_advances_locally_but_not_the_shared_timeline() {
    // A background-style launch: work runs synchronously, but
    // the virtual time it consumes is booked against the work itself, so
    // the machine-wide timeline never moves backwards.
    let engine = new_engine();
    engine.set_time(Timestamp::from_nanos(1_000));

    let (observed, consumed) = Engine::suspend_time(|| {
        engine.advance_time(Duration::from_secs(30));
        engine.time()
    });
    assert_eq!(observed, Timestamp::from_nanos(30_000_001_000));
    assert_eq!(consumed, Duration::from_secs(30));

    // The shared clock is exactly where it was before the launch.
    assert_eq!(engine.time(), Timestamp::from_nanos(1_000));
}

#[test]
fn nested_suspensions_each_report_their_own_consumed_time() {
    let engine = new_engine();

    let (outer_result, outer_elapsed) = Engine::suspend_time(|| {
        engine.advance_time(Duration::from_secs(5));
        let (inner_result, inner_elapsed) = Engine::suspend_time(|| {
            engine.advance_time(Duration::from_secs(2));
            engine.time()
        });
        assert_eq!(inner_result, Timestamp::from_nanos(7_000_000_000));
        assert_eq!(inner_elapsed, Duration::from_secs(2));
        engine.advance_time(Duration::from_secs(1));
        "outer"
    });
    assert_eq!(outer_result, "outer");
    assert_eq!(
        outer_elapsed,
        Duration::from_secs(8),
        "the enclosing scope also covers the time its inner scope ran"
    );

    assert_eq!(engine.time(), Timestamp::ZERO);
}

#[test]
fn suspension_does_not_leak_when_the_closure_panics() {
    let engine = new_engine();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = Engine::suspend_time(|| {
            engine.advance_time(Duration::from_secs(9));
            panic!("a crashing command must not strand the timeline");
        });
    }));
    assert!(result.is_err());

    // The book was folded back and discarded: time advances normally.
    engine.advance_time(Duration::from_secs(1));
    assert_eq!(engine.time(), Timestamp::from_nanos(1_000_000_000));
}

// ----------------------------------------------------------------------
// Symbolic links
// ----------------------------------------------------------------------

#[test]
fn lookup_follows_symlinks_to_their_targets() {
    let engine = new_engine();
    let root = engine.root();
    let private = engine
        .create_directory(None, root, name("private"))
        .unwrap();
    let etc = engine.create_directory(None, private, name("etc")).unwrap();
    engine
        .create_file(None, etc, name("hosts"), Some(b"127.0.0.1".to_vec()))
        .unwrap();

    engine
        .create_symlink(None, root, name("etc"), "/private/etc".to_owned())
        .unwrap();

    let hosts = engine.lookup(None, &"/etc/hosts".parse().unwrap()).unwrap();
    assert_eq!(
        engine.read(None, hosts).unwrap(),
        Some(b"127.0.0.1".to_vec()),
        "reading through the link reaches the target"
    );
    let resolved_etc = engine.lookup(None, &"/etc".parse().unwrap()).unwrap();
    assert_eq!(
        resolved_etc, etc,
        "the final component follows too (stat semantics)"
    );
    assert_eq!(engine.children(None, resolved_etc).unwrap().len(), 1);
}

#[test]
fn relative_symlinks_resolve_against_the_link_parent() {
    let engine = new_engine();
    let root = engine.root();
    let a = engine.create_directory(None, root, name("a")).unwrap();
    engine
        .create_file(None, a, name("f"), Some(vec![1]))
        .unwrap();
    engine
        .create_symlink(None, a, name("link"), "f".to_owned())
        .unwrap();

    let object = engine.lookup(None, &"/a/link".parse().unwrap()).unwrap();
    assert_eq!(engine.read(None, object).unwrap(), Some(vec![1]));
}

#[test]
fn symlink_loops_fail_with_the_depth_error() {
    let engine = new_engine();
    let root = engine.root();
    let a = engine.create_directory(None, root, name("a")).unwrap();
    engine
        .create_symlink(None, a, name("loop"), "/a/loop".to_owned())
        .unwrap();

    assert!(matches!(
        engine.lookup(None, &"/a/loop".parse().unwrap()),
        Err(Error::SymlinkLoop(_))
    ));
}

#[test]
fn symlink_operations_follow_stat_semantics() {
    let engine = new_engine();
    let root = engine.root();
    let d = engine.create_directory(None, root, name("d")).unwrap();
    let target = engine
        .create_file(None, d, name("f"), Some(vec![1, 2]))
        .unwrap();
    let link = engine
        .create_symlink(None, root, name("link"), "/d/f".to_owned())
        .unwrap();

    // The link object itself: read_link reports the target text and
    // is_link is true.
    assert_eq!(
        engine.read_link(None, link).unwrap(),
        Some("/d/f".to_owned())
    );
    assert!(engine.is_link(None, link).unwrap());
    // stat-style operations follow: size reports the target's size.
    assert_eq!(engine.size(None, link).unwrap(), 2);
    // stat-style operations follow.
    assert_eq!(engine.size(None, target).unwrap(), 2);
    assert_eq!(engine.read(None, link).unwrap(), Some(vec![1, 2]));
    engine.write(None, link, vec![3]).unwrap();
    assert_eq!(engine.read(None, target).unwrap(), Some(vec![3]));
    engine.append(None, link, vec![4]).unwrap();
    assert_eq!(engine.read(None, target).unwrap(), Some(vec![3, 4]));
    engine.touch(None, link).unwrap();
    // lstat-style: lookup_no_follow returns the link itself.
    assert_eq!(
        engine
            .lookup_no_follow(None, &"/link".parse().unwrap())
            .unwrap(),
        link
    );
    assert!(!engine.is_link(None, target).unwrap());
}

#[test]
fn deleting_a_symlink_removes_the_link_not_the_target() {
    let engine = new_engine();
    let root = engine.root();
    let d = engine.create_directory(None, root, name("d")).unwrap();
    let _target = engine
        .create_file(None, d, name("f"), Some(vec![1]))
        .unwrap();
    let link = engine
        .create_symlink(None, root, name("link"), "/d/f".to_owned())
        .unwrap();

    engine.delete(None, link).unwrap();
    assert!(engine.lookup(None, &"/link".parse().unwrap()).is_err());
    assert!(engine.lookup(None, &"/d/f".parse().unwrap()).is_ok());
}

#[test]
fn resolve_links_walks_a_chain_of_links() {
    let engine = new_engine();
    let root = engine.root();
    let target = engine
        .create_file(None, root, name("f"), Some(vec![1]))
        .unwrap();
    let _link = engine
        .create_symlink(None, root, name("one"), "/f".to_owned())
        .unwrap();
    let link_two = engine
        .create_symlink(None, root, name("two"), "/one".to_owned())
        .unwrap();

    assert_eq!(engine.resolve_links(link_two).unwrap(), target);
    assert_eq!(engine.resolve_links(target).unwrap(), target);
}