vcon-server 0.4.15

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
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
//! The store conformance suite: every outcome of every Store call that a
//! caller can see, written once against Store's public interface, and run
//! on every backend combination. A backend passes when this suite does;
//! the races and crash points that need the local backend's hooks stay in
//! Store's own tests.

use std::collections::BTreeSet;
use std::sync::{Arc, Mutex};

use base64::Engine;
use time::OffsetDateTime;
use uuid::Uuid;
use vcon::read::{Inspection, Limits, inspect};

use crate::backend::Objects;
use crate::clock::Clock;
use crate::envelope::Key;
use crate::ids::VersionId;
use crate::retention::Retention;
use crate::store::pending::{WRITE_LEASE, Writers};
use crate::store::{Caller, Created, Cursor, ExamineError, ListQuery, Store, StoreError};

/// A clock a test moves by hand.
pub(crate) struct TestClock(Mutex<OffsetDateTime>);

impl TestClock {
    pub(crate) fn at(now: OffsetDateTime) -> Arc<TestClock> {
        Arc::new(TestClock(Mutex::new(now)))
    }

    pub(crate) fn set(&self, now: OffsetDateTime) {
        *self.0.lock().expect("clock") = now;
    }
}

impl Clock for TestClock {
    fn now(&self) -> OffsetDateTime {
        *self.0.lock().expect("clock")
    }
}

/// What the suite needs of a backend combination: a new, empty Store for
/// each check, all on `clock`, and the same Store opened again.
pub(crate) trait Harness {
    /// A new tenant's Store, empty, opened with start-up recovery.
    fn fresh(&self, clock: Arc<TestClock>) -> Fresh;
}

/// Writes an object under any name, as a crash or another program would
/// leave it.
pub(crate) type Plant = Box<dyn Fn(&str, &[u8])>;

/// `Plant`, shared by the closures that need it.
pub(crate) type SharedPlant = Arc<dyn Fn(&str, &[u8])>;

/// What the storage holds, by name, sorted.
pub(crate) type Held = Box<dyn Fn() -> Vec<String>>;

/// Something done to one version's sealed bytes around the Store.
pub(crate) type Touch = Box<dyn Fn(VersionId)>;

/// A Store from `Harness::fresh`, a way to open it again, and its storage
/// reached around it, so a check can see what is really kept.
pub(crate) struct Fresh {
    pub(crate) store: Store,
    pub(crate) reopen: Box<dyn Fn() -> Store>,
    /// What the storage holds, by name, sorted: each object's name, and
    /// with pack storage the version id of each row of each pack file.
    pub(crate) held: Held,
    /// Removes a version's sealed bytes around the Store: its object, or
    /// the pack file that holds its row.
    pub(crate) lose: Touch,
    /// Replaces a version's sealed bytes around the Store with bytes that
    /// are not them: its object, or the pack file that holds its row.
    pub(crate) alter: Touch,
    /// Plants an object around the Store.
    pub(crate) plant: Plant,
    /// The same Store opened again, without start-up recovery, on objects
    /// it cannot read: every read fails, and not as an absent object
    /// (local: files the process may not read; S3: a service that does not
    /// answer).
    pub(crate) unreadable: Box<dyn Fn() -> Store>,
}

/// The moment every check starts at: 2026-10-23 12:00 UTC.
pub(crate) const START: OffsetDateTime = match OffsetDateTime::from_unix_timestamp(1_792_756_800) {
    Ok(at) => at,
    Err(_) => panic!("a valid time"),
};

/// A check of the suite, by name.
type Check = (&'static str, fn(&dyn Harness));

/// Every check, in order; each panics with its name on failure.
pub(crate) fn run(harness: &dyn Harness) {
    let checks: [Check; 24] = [
        ("create_then_get", create_then_get),
        (
            "reads_at_once_are_each_answered_and_recorded",
            reads_at_once_are_each_answered_and_recorded,
        ),
        ("create_same_conflict_gone", create_same_conflict_gone),
        ("forms_read_back", forms_read_back),
        ("replace_rules", replace_rules),
        ("delete_and_get", delete_and_get),
        ("purge_timing_and_hold", purge_timing_and_hold),
        ("legal_reads_and_restore", legal_reads_and_restore),
        ("list_pages", list_pages),
        ("audit_records_and_pages", audit_records_and_pages),
        ("rewrap_moves_every_key", rewrap_moves_every_key),
        ("check_and_counts", check_and_counts),
        ("reopen_keeps_everything", reopen_keeps_everything),
        ("purge_removes_the_object", purge_removes_the_object),
        (
            "recovery_removes_only_garbage",
            recovery_removes_only_garbage,
        ),
        (
            "purge_of_a_lost_object_finishes",
            purge_of_a_lost_object_finishes,
        ),
        (
            "a_lost_or_altered_object_is_damage",
            a_lost_or_altered_object_is_damage,
        ),
        (
            "an_object_the_storage_cannot_read_is_a_failure",
            an_object_the_storage_cannot_read_is_a_failure,
        ),
        (
            "a_create_under_way_keeps_its_object_through_recovery",
            a_create_under_way_keeps_its_object_through_recovery,
        ),
        (
            "a_replace_under_way_keeps_its_object_through_recovery",
            a_replace_under_way_keeps_its_object_through_recovery,
        ),
        (
            "a_create_past_its_lease_is_refused_and_leaves_nothing",
            a_create_past_its_lease_is_refused_and_leaves_nothing,
        ),
        (
            "a_replace_past_its_lease_is_refused_and_keeps_the_old_version",
            a_replace_past_its_lease_is_refused_and_keeps_the_old_version,
        ),
        (
            "recovery_with_no_other_writer_takes_a_stopped_write_for_a_leftover",
            recovery_with_no_other_writer_takes_a_stopped_write_for_a_leftover,
        ),
        (
            "a_write_that_ended_leaves_no_pending_row",
            a_write_that_ended_leaves_no_pending_row,
        ),
    ];
    for (name, check) in checks {
        crate::stderr::line(&format!("conformance: {name}"));
        check(harness);
    }
}

fn caller() -> Caller {
    Caller {
        key: Key::generate().expect("key").id(),
    }
}

/// An unsigned vCon of `uuid`.
pub(crate) fn vcon(uuid: &str, subject: &str) -> (Inspection, Vec<u8>) {
    let body = format!(
        r#"{{"uuid": "{uuid}", "created_at": "2026-10-23T12:00:00Z", "subject": "{subject}", "parties": []}}"#
    )
    .into_bytes();
    (found(&body), body)
}

fn found(body: &[u8]) -> Inspection {
    inspect(body, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a valid vCon")
}

fn uuid(n: u8) -> String {
    format!("01a07da8-c2bb-83e5-b9a2-279e0d16bc{n:02x}")
}

fn new_version(store: &Store, who: &Caller, uuid: &str, subject: &str) -> (VersionId, Vec<u8>) {
    let (found, body) = vcon(uuid, subject);
    match store.create(who, &found, &body) {
        Ok(Created::New(version)) => (version, body),
        other => panic!("a new vCon, got {other:?}"),
    }
}

/// Runs `write` on a thread of its own, stops it between its object and
/// its last transaction, runs `during` while it is stopped, and returns
/// what the write returned.
fn stopped<T: Send>(
    store: &Store,
    write: impl FnOnce(&Store) -> T + Send,
    during: impl FnOnce(),
) -> T {
    let (stopped, at_stop) = std::sync::mpsc::channel();
    let (go, on_go) = std::sync::mpsc::channel::<()>();
    store.on_between(Box::new(move || {
        stopped.send(()).expect("the test waits");
        on_go.recv().expect("the test lets the write go on");
    }));
    std::thread::scope(|scope| {
        // Owned here, so a failed check in `during` drops it while the
        // scope unwinds: the write's wait then ends, and the scope's join
        // does not wait for ever.
        let go = go;
        let writer = scope.spawn(|| write(store));
        at_stop
            .recv_timeout(std::time::Duration::from_secs(60))
            .expect("the write stops between its object and its row");
        during();
        go.send(()).expect("the write waits");
        writer.join().expect("the write ends")
    })
}

/// The objects held besides `kept`, as `held` gives them.
fn others(held: &Held, kept: &[VersionId]) -> Vec<String> {
    let kept: Vec<String> = kept.iter().map(ToString::to_string).collect();
    held().into_iter().filter(|n| !kept.contains(n)).collect()
}

/// A nanosecond count as the time it is.
fn plus(at: OffsetDateTime, nanos: i64) -> OffsetDateTime {
    at + time::Duration::nanoseconds(nanos)
}

fn a_create_under_way_keeps_its_object_through_recovery(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let (found, body) = vcon(&uuid(1), "first");
    let created = stopped(
        &f.store,
        |store| store.create(&who, &found, &body),
        || {
            clock.set(plus(START, WRITE_LEASE - 1));
            f.store.recover(Writers::Maybe).expect("recovers");
            assert_eq!(
                others(&f.held, &[]).len(),
                1,
                "a_create_under_way_keeps_its_object_through_recovery: the write's object"
            );
        },
    );
    let Ok(Created::New(version)) = created else {
        panic!("a_create_under_way_keeps_its_object_through_recovery: created, got {created:?}");
    };
    assert_eq!(
        f.store
            .get(&who, Uuid::parse_str(&uuid(1)).expect("uuid"))
            .expect("reads")
            .body,
        body,
        "a_create_under_way_keeps_its_object_through_recovery: the vCon reads back"
    );
    assert_eq!(
        (f.held)(),
        vec![version.to_string()],
        "a_create_under_way_keeps_its_object_through_recovery: its object alone"
    );
}

fn a_replace_under_way_keeps_its_object_through_recovery(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let (first, _) = new_version(&f.store, &who, &uuid(1), "first");
    let (found, body) = vcon(&uuid(1), "second");
    let replaced = stopped(
        &f.store,
        |store| store.replace(&who, first, &found, &body),
        || {
            f.store.recover(Writers::Maybe).expect("recovers");
            assert_eq!(
                others(&f.held, &[first]).len(),
                1,
                "a_replace_under_way_keeps_its_object_through_recovery: the write's object"
            );
        },
    );
    let second = replaced.unwrap_or_else(|e| {
        panic!("a_replace_under_way_keeps_its_object_through_recovery: replaced, got {e:?}")
    });
    assert_eq!(
        f.store
            .get(&who, Uuid::parse_str(&uuid(1)).expect("uuid"))
            .expect("reads")
            .body,
        body,
        "a_replace_under_way_keeps_its_object_through_recovery: the new version reads back"
    );
    let mut both = vec![first.to_string(), second.to_string()];
    both.sort();
    assert_eq!(
        (f.held)(),
        both,
        "a_replace_under_way_keeps_its_object_through_recovery: the two versions' objects"
    );
}

fn a_create_past_its_lease_is_refused_and_leaves_nothing(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let (found, body) = vcon(&uuid(1), "first");
    let created = stopped(
        &f.store,
        |store| store.create(&who, &found, &body),
        || {
            clock.set(plus(START, WRITE_LEASE));
            f.store.recover(Writers::Maybe).expect("recovers");
            assert_eq!(
                (f.held)(),
                Vec::<String>::new(),
                "a_create_past_its_lease_is_refused_and_leaves_nothing: recovery removed it"
            );
        },
    );
    assert!(
        matches!(created, Err(StoreError::Io)),
        "a_create_past_its_lease_is_refused_and_leaves_nothing: refused, got {created:?}"
    );
    assert!(
        matches!(
            f.store.get(&who, Uuid::parse_str(&uuid(1)).expect("uuid")),
            Err(StoreError::NotFound)
        ),
        "a_create_past_its_lease_is_refused_and_leaves_nothing: no row names it"
    );
    assert_eq!(
        (f.held)(),
        Vec::<String>::new(),
        "a_create_past_its_lease_is_refused_and_leaves_nothing: no object"
    );
}

fn a_replace_past_its_lease_is_refused_and_keeps_the_old_version(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let (first, old) = new_version(&f.store, &who, &uuid(1), "first");
    let (found, body) = vcon(&uuid(1), "second");
    let replaced = stopped(
        &f.store,
        |store| store.replace(&who, first, &found, &body),
        || {
            clock.set(plus(START, 2 * WRITE_LEASE));
            f.store.recover(Writers::Maybe).expect("recovers");
        },
    );
    assert!(
        matches!(replaced, Err(StoreError::Io)),
        "a_replace_past_its_lease_is_refused_and_keeps_the_old_version: refused, got {replaced:?}"
    );
    assert_eq!(
        f.store
            .get(&who, Uuid::parse_str(&uuid(1)).expect("uuid"))
            .expect("reads")
            .body,
        old,
        "a_replace_past_its_lease_is_refused_and_keeps_the_old_version: the old version is current"
    );
    assert_eq!(
        (f.held)(),
        vec![first.to_string()],
        "a_replace_past_its_lease_is_refused_and_keeps_the_old_version: the old object alone"
    );
}

fn recovery_with_no_other_writer_takes_a_stopped_write_for_a_leftover(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (found, body) = vcon(&uuid(1), "first");
    let created = stopped(
        &f.store,
        |store| store.create(&who, &found, &body),
        || {
            f.store.recover(Writers::None).expect("recovers");
            assert_eq!(
                (f.held)(),
                Vec::<String>::new(),
                "recovery_with_no_other_writer_takes_a_stopped_write_for_a_leftover: removed"
            );
        },
    );
    assert!(
        matches!(created, Err(StoreError::Io)),
        "recovery_with_no_other_writer_takes_a_stopped_write_for_a_leftover: refused, got \
         {created:?}"
    );
    assert!(
        matches!(
            f.store.get(&who, Uuid::parse_str(&uuid(1)).expect("uuid")),
            Err(StoreError::NotFound)
        ),
        "recovery_with_no_other_writer_takes_a_stopped_write_for_a_leftover: no row"
    );
}

fn a_write_that_ended_leaves_no_pending_row(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let (first, _) = new_version(&f.store, &who, &uuid(1), "first");
    let (found, body) = vcon(&uuid(1), "other");
    assert!(
        matches!(
            f.store.create(&who, &found, &body),
            Err(StoreError::Conflict)
        ),
        "a_write_that_ended_leaves_no_pending_row: a refused create"
    );
    let (found, body) = vcon(&uuid(2), "second");
    let racing = stopped(
        &f.store,
        |store| store.create(&who, &found, &body),
        || {
            let (found, body) = vcon(&uuid(2), "winner");
            f.store
                .create(&who, &found, &body)
                .expect("the other create wins");
        },
    );
    assert!(
        matches!(racing, Err(StoreError::Conflict)),
        "a_write_that_ended_leaves_no_pending_row: the create that lost, got {racing:?}"
    );
    assert_eq!(
        f.store.pending_writes().expect("reads"),
        vec![],
        "a_write_that_ended_leaves_no_pending_row: no row is left by a created, a refused or a \
         lost write"
    );
    clock.set(plus(START, 3 * WRITE_LEASE));
    f.store.recover(Writers::Maybe).expect("recovers");
    assert_eq!(
        others(&f.held, &[first]).len(),
        1,
        "a_write_that_ended_leaves_no_pending_row: the winner's object is kept"
    );
}

fn create_then_get(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (version, body) = new_version(&f.store, &who, &uuid(1), "first");
    let stored = f
        .store
        .get(&who, Uuid::parse_str(&uuid(1)).expect("uuid"))
        .expect("reads");
    assert_eq!(
        (stored.version, stored.body),
        (version, body),
        "create_then_get: (stored.version, stored.body)"
    );
    let absent = Uuid::parse_str(&uuid(2)).expect("uuid");
    assert_eq!(
        f.store.get(&who, absent),
        Err(StoreError::NotFound),
        "create_then_get: f.store.get(&who, absent)"
    );
}

fn create_same_conflict_gone(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (version, body) = new_version(&f.store, &who, &uuid(1), "first");
    let (found, _) = vcon(&uuid(1), "first");
    assert_eq!(
        f.store.create(&who, &found, &body),
        Ok(Created::Same(version)),
        "create_same_conflict_gone: f.store.create(&who, &found, &body)"
    );
    let (other, other_body) = vcon(&uuid(1), "other");
    assert_eq!(
        f.store.create(&who, &other, &other_body),
        Err(StoreError::Conflict),
        "create_same_conflict_gone: f.store.create(&who, &other, &other_body)"
    );
    f.store
        .delete(&who, found.uuid, Retention::Years(7))
        .expect("deletes");
    assert_eq!(
        f.store.create(&who, &found, &body),
        Err(StoreError::Gone),
        "create_same_conflict_gone: f.store.create(&who, &found, &body)"
    );
}

fn forms_read_back(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (_, inner) = vcon(&uuid(2), "signed");
    let signed = format!(
        r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
    )
    .into_bytes();
    let encrypted = format!(
        r#"{{"unprotected": {{"uuid": "{}"}}, "ciphertext": "x", "recipients": []}}"#,
        uuid(3)
    )
    .into_bytes();
    for (body, form) in [
        (signed, vcon::Form::Signed),
        (encrypted, vcon::Form::Encrypted),
    ] {
        let found = found(&body);
        f.store.create(&who, &found, &body).expect("stored");
        let stored = f.store.get(&who, found.uuid).expect("reads");
        assert_eq!(
            (stored.form, stored.body),
            (form, body.clone()),
            "forms_read_back: (stored.form, stored.body)"
        );
        assert_eq!(
            f.store.replace(&who, stored.version, &found, &body),
            Err(StoreError::Immutable),
            "forms_read_back: f.store.replace(&who, stored.version, &found, &body)"
        );
    }
}

fn replace_rules(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let (absent, absent_body) = vcon(&uuid(9), "absent");
    assert_eq!(
        f.store
            .replace(&who, VersionId::generate(), &absent, &absent_body),
        Err(StoreError::NotFound),
        "replace_rules: f.store .replace(&who, VersionId::generate(), &absent, &a..."
    );
    let (first, _) = new_version(&f.store, &who, &uuid(1), "first");
    let (found, second) = vcon(&uuid(1), "second");
    assert_eq!(
        f.store
            .replace(&who, VersionId::generate(), &found, &second),
        Err(StoreError::PreconditionFailed),
        "replace_rules: f.store .replace(&who, VersionId::generate(), &found, &se..."
    );
    clock.set(START + time::Duration::seconds(1));
    let next = f
        .store
        .replace(&who, first, &found, &second)
        .expect("replaces");
    assert_eq!(
        f.store.get(&who, found.uuid).expect("reads").version,
        next,
        "replace_rules: f.store.get(&who, found.uuid).expect(\"reads\").version"
    );
    let kept = f.store.legal_versions(&who, found.uuid).expect("lists");
    assert_eq!(
        kept.iter()
            .map(|v| (v.version, v.current))
            .collect::<Vec<_>>(),
        [(first, false), (next, true)],
        "replace_rules: kept.iter().map(|v| (v.version, v.current)).collect::<Vec..."
    );
    f.store
        .delete(&who, found.uuid, Retention::Years(7))
        .expect("deletes");
    assert_eq!(
        f.store.replace(&who, next, &found, &second),
        Err(StoreError::Gone),
        "replace_rules: f.store.replace(&who, next, &found, &second)"
    );
}

fn delete_and_get(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    new_version(&f.store, &who, &uuid(1), "first");
    let id = Uuid::parse_str(&uuid(1)).expect("uuid");
    f.store
        .delete(&who, id, Retention::Years(7))
        .expect("deletes");
    assert_eq!(
        f.store.get(&who, id),
        Err(StoreError::Gone),
        "delete_and_get: f.store.get(&who, id)"
    );
    assert_eq!(
        f.store.delete(&who, id, Retention::Years(7)),
        Ok(()),
        "deleting again succeeds"
    );
    let never = Uuid::parse_str(&uuid(2)).expect("uuid");
    assert_eq!(
        f.store.delete(&who, never, Retention::Years(7)),
        Err(StoreError::NotFound),
        "delete_and_get: f.store.delete(&who, never, Retention::Years(7))"
    );
}

fn purge_timing_and_hold(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let days = Retention::Days(1);
    let (version, _) = new_version(&f.store, &who, &uuid(1), "first");
    let id = Uuid::parse_str(&uuid(1)).expect("uuid");
    f.store.delete(&who, id, days).expect("deletes");
    clock.set(START + time::Duration::days(1) - time::Duration::seconds(1));
    assert_eq!(
        f.store.purge_due(days).expect("sweeps").purged,
        0,
        "purge_timing_and_hold: f.store.purge_due(days).expect(\"sweeps\").purged"
    );
    f.store.set_hold(&who, id, true).expect("holds");
    clock.set(START + time::Duration::days(2));
    assert_eq!(f.store.purge_due(days).expect("sweeps").purged, 0, "held");
    f.store.set_hold(&who, id, false).expect("releases");
    assert_eq!(
        f.store.purge_due(days).expect("sweeps").purged,
        1,
        "purge_timing_and_hold: f.store.purge_due(days).expect(\"sweeps\").purged"
    );
    assert_eq!(
        f.store.legal_get(&who, id, Some(version)),
        Err(StoreError::Gone),
        "purge_timing_and_hold: f.store.legal_get(&who, id, Some(version))"
    );
    assert_eq!(
        f.store.check(),
        Ok(Vec::new()),
        "purge_timing_and_hold: f.store.check()"
    );
    assert_eq!(
        f.store.counts().expect("counts").versions,
        0,
        "purge_timing_and_hold: f.store.counts().expect(\"counts\").versions"
    );
    // Retention zero erases inside the delete.
    new_version(&f.store, &who, &uuid(2), "second");
    let second = Uuid::parse_str(&uuid(2)).expect("uuid");
    f.store
        .delete(&who, second, Retention::Days(0))
        .expect("deletes");
    assert_eq!(
        f.store.counts().expect("counts").versions,
        0,
        "purge_timing_and_hold: f.store.counts().expect(\"counts\").versions"
    );
}

fn legal_reads_and_restore(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (version, body) = new_version(&f.store, &who, &uuid(1), "first");
    let id = Uuid::parse_str(&uuid(1)).expect("uuid");
    f.store
        .delete(&who, id, Retention::Years(7))
        .expect("deletes");
    let read = f.store.legal_get(&who, id, None).expect("legal read");
    assert!(read.deleted, "legal_reads_and_restore: read.deleted");
    assert_eq!(
        read.stored.body, body,
        "legal_reads_and_restore: read.stored.body"
    );
    assert_eq!(
        f.store.restore(&who, id),
        Ok(version),
        "legal_reads_and_restore: f.store.restore(&who, id)"
    );
    assert_eq!(
        f.store.restore(&who, id),
        Err(StoreError::NotDeleted),
        "legal_reads_and_restore: f.store.restore(&who, id)"
    );
    assert_eq!(
        f.store.get(&who, id).expect("live again").body,
        body,
        "legal_reads_and_restore: f.store.get(&who, id).expect(\"live again\").body"
    );
    let never = Uuid::parse_str(&uuid(2)).expect("uuid");
    assert_eq!(
        f.store.legal_get(&who, never, None).map(|_| ()),
        Err(StoreError::NotFound),
        "legal_reads_and_restore: f.store.legal_get(&who, never, None).map(|_| ())"
    );
    assert_eq!(
        f.store.set_hold(&who, never, true),
        Err(StoreError::NotFound),
        "legal_reads_and_restore: f.store.set_hold(&who, never, true)"
    );
}

fn list_pages(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    for n in 1..=5 {
        clock.set(START + time::Duration::seconds(i64::from(n)));
        new_version(&f.store, &who, &uuid(n), "listed");
    }
    let mut seen = Vec::new();
    let mut cursor: Option<Cursor> = None;
    loop {
        let text = cursor.map(|c| c.to_string());
        let query = ListQuery::new(Some(2), text.as_deref(), None, None).expect("a query");
        let page = f.store.list(&who, &query).expect("lists");
        seen.extend(page.vcons.iter().map(|v| v.uuid.to_string()));
        match page.next {
            Some(next) => cursor = Some(next),
            None => break,
        }
    }
    let newest_first: Vec<String> = (1..=5).rev().map(uuid).collect();
    assert_eq!(seen, newest_first, "list_pages: seen");
}

fn audit_records_and_pages(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    new_version(&f.store, &who, &uuid(1), "first");
    let id = Uuid::parse_str(&uuid(1)).expect("uuid");
    f.store.get(&who, id).expect("reads");
    let mut out = Vec::new();
    f.store.export(None, &mut out).expect("exports");
    let actions: Vec<String> = String::from_utf8(out)
        .expect("UTF-8")
        .lines()
        .map(|l| {
            let v: serde_json::Value = serde_json::from_str(l).expect("JSON");
            format!("{} {}", v["action"].as_str().expect("action"), v["status"])
        })
        .collect();
    assert_eq!(
        actions,
        ["create 201", "read 200"],
        "audit_records_and_pages: actions"
    );
    let query = crate::audit::AuditQuery::new(Some(1), Some(1)).expect("a query");
    let page = f.store.audit_page(&who, &query).expect("a page");
    assert_eq!(
        String::from_utf8(page).expect("UTF-8").lines().count(),
        1,
        "audit_records_and_pages: String::from_utf8(page).expect(\"UTF-8\").lines().count()"
    );
}

/// Reads at once from eight threads, of three vCons, one of them deleted
/// first: each read is answered as it would be alone and recorded once.
/// Reads that reach their record together share one commit, each in a
/// part of its own (store/group.rs), so this runs that path on every
/// backend.
fn reads_at_once_are_each_answered_and_recorded(h: &dyn Harness) {
    const THREADS: usize = 8;
    const EACH: usize = 12;
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (_, a) = new_version(&f.store, &who, &uuid(1), "a");
    let (_, b) = new_version(&f.store, &who, &uuid(2), "b");
    new_version(&f.store, &who, &uuid(3), "c");
    let ids: Vec<Uuid> = (1..=3)
        .map(|n| Uuid::parse_str(&uuid(n)).expect("uuid"))
        .collect();
    f.store
        .delete(&who, ids[2], Retention::Years(7))
        .expect("deletes");
    std::thread::scope(|scope| {
        for t in 0..THREADS {
            let (store, who, ids, a, b) = (&f.store, &who, &ids, &a, &b);
            scope.spawn(move || {
                for i in 0..EACH {
                    let id = ids[(t + i) % 3];
                    let got = store.get(who, id).map(|s| s.body);
                    let want = match (t + i) % 3 {
                        0 => Ok(a.clone()),
                        1 => Ok(b.clone()),
                        _ => Err(StoreError::Gone),
                    };
                    assert_eq!(got, want, "reads_at_once: thread {t} read {i}");
                }
            });
        }
    });
    let mut out = Vec::new();
    f.store.export(None, &mut out).expect("exports");
    let mut reads = [0_usize; 2];
    for line in String::from_utf8(out).expect("UTF-8").lines() {
        let v: serde_json::Value = serde_json::from_str(line).expect("JSON");
        if v["action"] == "read" {
            match v["status"].as_u64() {
                Some(200) => reads[0] += 1,
                Some(410) => reads[1] += 1,
                other => panic!("reads_at_once: a read recorded as {other:?}"),
            }
        }
    }
    let gone = (0..THREADS)
        .flat_map(|t| (0..EACH).map(move |i| (t + i) % 3))
        .filter(|&n| n == 2)
        .count();
    assert_eq!(
        reads,
        [THREADS * EACH - gone, gone],
        "reads_at_once: one record for each read, by its outcome"
    );
}

fn rewrap_moves_every_key(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    for n in 1..=3 {
        new_version(&f.store, &who, &uuid(n), "kept");
    }
    let new = Key::generate().expect("key");
    assert_eq!(
        f.store.rewrap(&new, 2),
        Ok(2),
        "rewrap_moves_every_key: f.store.rewrap(&new, 2)"
    );
    assert_eq!(
        f.store.rows_under_other_keys(),
        Ok(2),
        "rewrap_moves_every_key: f.store.rows_under_other_keys()"
    );
    assert_eq!(
        f.store.rewrap(&new, 2),
        Ok(1),
        "rewrap_moves_every_key: f.store.rewrap(&new, 2)"
    );
    assert_eq!(
        f.store.rewrap(&new, 2),
        Ok(0),
        "rewrap_moves_every_key: f.store.rewrap(&new, 2)"
    );
    assert_eq!(
        f.store.rows_under_other_keys(),
        Ok(3),
        "rewrap_moves_every_key: f.store.rows_under_other_keys()"
    );
}

fn check_and_counts(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    new_version(&f.store, &who, &uuid(1), "first");
    let id = Uuid::parse_str(&uuid(1)).expect("uuid");
    f.store.set_hold(&who, id, true).expect("holds");
    let counts = f.store.counts().expect("counts");
    assert_eq!(
        (counts.versions, counts.held),
        (1, 1),
        "check_and_counts: (counts.versions, counts.held)"
    );
    assert_eq!(
        f.store.check(),
        Ok(Vec::new()),
        "check_and_counts: f.store.check()"
    );
}

fn reopen_keeps_everything(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (version, body) = new_version(&f.store, &who, &uuid(1), "first");
    drop(f.store);
    let store = (f.reopen)();
    let stored = store
        .get(&who, Uuid::parse_str(&uuid(1)).expect("uuid"))
        .expect("reads after reopening");
    assert_eq!(
        (stored.version, stored.body),
        (version, body),
        "reopen_keeps_everything: (stored.version, stored.body)"
    );
}

/// `Fresh::held`, `lose` and `alter` for `objects` and, if the Store has
/// them, `packs`. A pack file is read whole for the version ids of its
/// rows; with every version packed alone (the packer runs after every
/// write), losing or altering a version's file touches no other version.
pub(crate) fn blobs(
    objects: Arc<dyn Objects>,
    packs: Option<Arc<dyn crate::backend::Packs>>,
    plant: SharedPlant,
) -> (Held, Touch, Touch) {
    let files = {
        let packs = packs.clone();
        move || -> Vec<(String, Vec<VersionId>)> {
            let Some(packs) = &packs else {
                return Vec::new();
            };
            packs
                .list()
                .expect("lists the pack files")
                .into_iter()
                .filter(|name| crate::backend::pack::parse_name(name).is_some())
                .map(|name| {
                    let size = packs.size(&name).expect("a length").expect("there");
                    let bytes = packs.read(&name, 0, size).expect("reads the file");
                    let versions = crate::backend::pack::tests::versions_in(&bytes);
                    (name, versions)
                })
                .collect()
        }
    };
    let files = Arc::new(files);
    let held = {
        let (objects, files) = (objects.clone(), files.clone());
        Box::new(move || {
            let mut names = objects.list().expect("lists the objects");
            for (_, versions) in files() {
                names.extend(versions.iter().map(VersionId::to_string));
            }
            names.sort();
            names
        })
    };
    let file_of = {
        let files = files.clone();
        move |version: VersionId| {
            files()
                .into_iter()
                .find(|(_, versions)| versions.contains(&version))
                .map(|(name, versions)| {
                    assert_eq!(versions.len(), 1, "{name} holds this version alone");
                    name
                })
        }
    };
    let lose = {
        let (objects, packs, file_of) = (objects.clone(), packs.clone(), file_of.clone());
        Box::new(move |version: VersionId| match (file_of(version), &packs) {
            (Some(name), Some(packs)) => packs.remove(&name).expect("removes the file"),
            _ => objects
                .remove_name(&version.to_string())
                .expect("removes the object"),
        })
    };
    let alter = Box::new(move |version: VersionId| match (file_of(version), &packs) {
        (Some(name), Some(packs)) => {
            packs.remove(&name).expect("removes the file");
            assert!(
                packs.put_new(&name, b"not a pack file").expect("writes"),
                "the name is free again"
            );
        }
        _ => plant(&version.to_string(), b"not a sealed body"),
    });
    (held, lose, alter)
}

/// A purged version's object is gone from the storage, not only from the
/// catalog: after a sweep, and when retention zero erases in the delete.
fn purge_removes_the_object(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let days = Retention::Days(1);
    let (swept, _) = new_version(&f.store, &who, &uuid(1), "first");
    let (erased, _) = new_version(&f.store, &who, &uuid(2), "second");
    let (live, _) = new_version(&f.store, &who, &uuid(3), "third");
    let mut all = vec![swept.to_string(), erased.to_string(), live.to_string()];
    all.sort();
    assert_eq!((f.held)(), all, "purge_removes_the_object: one object each");
    let first = Uuid::parse_str(&uuid(1)).expect("uuid");
    f.store.delete(&who, first, days).expect("deletes");
    clock.set(START + time::Duration::days(2));
    assert_eq!(
        f.store.purge_due(days).expect("sweeps").purged,
        1,
        "purge_removes_the_object: the sweep purges the deleted version"
    );
    let second = Uuid::parse_str(&uuid(2)).expect("uuid");
    f.store
        .delete(&who, second, Retention::Days(0))
        .expect("deletes");
    assert_eq!(
        (f.held)(),
        [live.to_string()],
        "purge_removes_the_object: only the live version's object is kept"
    );
}

/// Start-up recovery applies the catalog rule: an object with no row, and
/// a temporary one, is garbage and removed; a version with a row keeps its
/// object; a name that is not a version id is not the server's and stays.
fn recovery_removes_only_garbage(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (version, body) = new_version(&f.store, &who, &uuid(1), "first");
    let garbage = VersionId::generate().to_string();
    let temporary = format!("{}.tmp", VersionId::generate());
    let foreign = "not-a-version";
    for name in [garbage.as_str(), temporary.as_str(), foreign] {
        (f.plant)(name, b"no row names this");
    }
    drop(f.store);
    let store = (f.reopen)();
    let mut expected = vec![version.to_string(), foreign.to_owned()];
    expected.sort();
    assert_eq!(
        (f.held)(),
        expected,
        "recovery_removes_only_garbage: the objects left after recovery"
    );
    assert_eq!(
        store
            .get(&who, Uuid::parse_str(&uuid(1)).expect("uuid"))
            .expect("reads")
            .body,
        body,
        "recovery_removes_only_garbage: the stored vCon reads back"
    );
}

/// A purge whose object was already lost (removed by hand, or by a purge
/// cut off after its commit) still purges: the row goes, the sweep goes
/// on, and nothing is left for `check` to report.
fn purge_of_a_lost_object_finishes(h: &dyn Harness) {
    let clock = TestClock::at(START);
    let f = h.fresh(clock.clone());
    let who = caller();
    let days = Retention::Days(1);
    let (lost, _) = new_version(&f.store, &who, &uuid(1), "first");
    new_version(&f.store, &who, &uuid(2), "second");
    for n in [1, 2] {
        let id = Uuid::parse_str(&uuid(n)).expect("uuid");
        f.store.delete(&who, id, days).expect("deletes");
    }
    (f.lose)(lost);
    clock.set(START + time::Duration::days(2));
    assert_eq!(
        f.store.purge_due(days).map(|r| r.purged),
        Ok(2),
        "purge_of_a_lost_object_finishes: both versions are purged"
    );
    assert_eq!(
        f.store.check(),
        Ok(Vec::new()),
        "purge_of_a_lost_object_finishes: f.store.check()"
    );
    assert!(
        (f.held)().is_empty(),
        "purge_of_a_lost_object_finishes: no object is left"
    );
}

/// Every read that opens a version answers `expected` for `uuid(n)`,
/// whose current version is `version`: get, a create of the same body,
/// and the legal reads of its current version and of `version` by id.
fn reads_answer(
    store: &Store,
    who: &Caller,
    n: u8,
    version: VersionId,
    expected: StoreError,
    check: &str,
) {
    let (found, body) = vcon(&uuid(n), "first");
    let id = found.uuid;
    assert_eq!(store.get(who, id).err(), Some(expected), "{check}: get");
    assert_eq!(
        store.create(who, &found, &body).err(),
        Some(expected),
        "{check}: create of the same body"
    );
    for asked in [None, Some(version)] {
        assert_eq!(
            store.legal_get(who, id, asked).err(),
            Some(expected),
            "{check}: legal_get {asked:?}"
        );
    }
}

/// Damage is the stored data itself gone bad: an object a row names that
/// the storage no longer holds, or one that does not open. Each read
/// answers Damaged, and `examine` lists exactly those versions.
fn a_lost_or_altered_object_is_damage(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (lost, _) = new_version(&f.store, &who, &uuid(1), "first");
    let (altered, _) = new_version(&f.store, &who, &uuid(2), "first");
    new_version(&f.store, &who, &uuid(3), "first");
    (f.lose)(lost);
    (f.alter)(altered);
    let check = "a_lost_or_altered_object_is_damage";
    reads_answer(&f.store, &who, 1, lost, StoreError::Damaged, check);
    reads_answer(&f.store, &who, 2, altered, StoreError::Damaged, check);
    let mut expected = vec![lost, altered];
    expected.sort_by_key(|v| v.0);
    assert_eq!(
        f.store
            .examine(Retention::Years(7), START, START)
            .map(|e| e.damaged),
        Ok(expected),
        "{check}: examine lists the lost and the altered version"
    );
}

/// A read the storage fails (it cannot be reached, refuses, or does not
/// answer) says nothing about the stored data: each read answers Io, not
/// Damaged, and `examine` fails rather than list a sound version as
/// damaged.
fn an_object_the_storage_cannot_read_is_a_failure(h: &dyn Harness) {
    let f = h.fresh(TestClock::at(START));
    let who = caller();
    let (version, _) = new_version(&f.store, &who, &uuid(1), "first");
    drop(f.store);
    let store = (f.unreadable)();
    let check = "an_object_the_storage_cannot_read_is_a_failure";
    reads_answer(&store, &who, 1, version, StoreError::Io, check);
    let examined = store.examine(Retention::Years(7), START, START).err();
    assert!(
        matches!(examined, Some(ExamineError::Objects { .. })),
        "{check}: examine fails as the storage's, not the catalog's: {examined:?}"
    );
    drop(store);
    let (found, body) = vcon(&uuid(1), "first");
    assert_eq!(
        (f.reopen)().create(&who, &found, &body),
        Ok(Created::Same(version)),
        "{check}: the version reads again once the storage does"
    );
}

/// The local backend on a temporary directory.
#[cfg(test)]
mod local {
    use super::*;
    use crate::backend::local::LocalObjects;
    use crate::envelope;
    use crate::fs::OsFs;
    use crate::ids::TenantId;

    struct Local(tempfile::TempDir);

    impl Harness for Local {
        fn fresh(&self, clock: Arc<TestClock>) -> Fresh {
            let dir = self.0.path().join(TenantId::generate().to_string());
            std::fs::create_dir(&dir).expect("tenant directory");
            let key = Key::generate().expect("key");
            let master = Key::generate().expect("master");
            let ctx = envelope::Context::Tenant {
                tenant: TenantId([0x11; 16]),
            };
            let wrapped = envelope::wrap(&master, &ctx, &key);
            let objects_dir = dir.join("objects");
            let open = std::rc::Rc::new(move || {
                let key = envelope::unwrap(&master, &ctx, &wrapped).expect("unwraps");
                Store::open(
                    &dir,
                    TenantId([0x11; 16]),
                    key,
                    Arc::new(OsFs),
                    clock.clone(),
                )
                .expect("opens")
            });
            let store = open();
            let plant_dir = objects_dir.clone();
            let plant: SharedPlant = Arc::new(move |name, bytes| {
                std::fs::write(plant_dir.join(name), bytes).expect("plants an object file");
            });
            let (held, lose, alter) = blobs(
                Arc::new(LocalObjects::new(objects_dir.clone(), Arc::new(OsFs))),
                None,
                plant.clone(),
            );
            let unreadable_dir = objects_dir.clone();
            let reopen = open.clone();
            let readable_dir = objects_dir.clone();
            Fresh {
                store,
                reopen: Box::new(move || {
                    // Readable again, if `unreadable` made them not.
                    use std::os::unix::fs::PermissionsExt;
                    for entry in std::fs::read_dir(&readable_dir).expect("objects") {
                        let path = entry.expect("an entry").path();
                        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
                            .expect("chmod");
                    }
                    reopen()
                }),
                unreadable: Box::new(move || {
                    // Each object file mode 000 until the next open.
                    use std::os::unix::fs::PermissionsExt;
                    let store = open();
                    for entry in std::fs::read_dir(&unreadable_dir).expect("objects") {
                        let path = entry.expect("an entry").path();
                        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))
                            .expect("chmod");
                    }
                    store
                }),
                held,
                lose,
                alter,
                plant: Box::new(move |name, bytes| plant(name, bytes)),
            }
        }
    }

    #[test]
    fn the_local_backend_conforms() {
        run(&Local(tempfile::tempdir().expect("temp dir")));
    }
}

/// The local catalog and objects with Parquet storage in a directory, a
/// pack run after every write that adds a version.
#[cfg(all(test, feature = "s3"))]
mod packed_local {
    use std::sync::atomic::Ordering;

    use super::*;
    use crate::backend::local::{LocalCatalog, LocalObjects};
    use crate::envelope;
    use crate::fs::OsFs;
    use crate::ids::TenantId;
    use crate::store::packed::tests::DirPacks;
    use crate::store::packer::PackPlan;

    struct PackedLocal(tempfile::TempDir);

    /// A pack run that leaves each version alone in its file, so losing or
    /// altering one version's file touches no other: no merging, which
    /// compaction's own tests cover.
    pub(crate) fn alone() -> PackPlan {
        PackPlan {
            merge_below: 0,
            ..PackPlan::with_limit(1 << 20)
        }
    }

    impl Harness for PackedLocal {
        fn fresh(&self, clock: Arc<TestClock>) -> Fresh {
            let tenant = TenantId::generate();
            let dir = self.0.path().join(tenant.to_string());
            let objects_dir = dir.join("objects");
            std::fs::create_dir_all(&objects_dir).expect("tenant directory");
            let key = Key::generate().expect("key");
            let master = Key::generate().expect("master");
            let ctx = envelope::Context::Tenant { tenant };
            let wrapped = envelope::wrap(&master, &ctx, &key);
            let packs = DirPacks::new();
            let objects: Arc<dyn Objects> =
                Arc::new(LocalObjects::new(objects_dir.clone(), Arc::new(OsFs)));
            let open = {
                let (packs, objects) = (packs.clone(), objects.clone());
                std::rc::Rc::new(move |recover: bool| {
                    let key = envelope::unwrap(&master, &ctx, &wrapped).expect("unwraps");
                    let catalog_key = envelope::catalog_key(&key).expect("catalog key");
                    let catalog = LocalCatalog::open(&dir.join("catalog.sqlite"), catalog_key)
                        .expect("catalog");
                    let mut store = Store::open_on(
                        tenant,
                        key,
                        Box::new(catalog),
                        objects.clone(),
                        Some(packs.clone()),
                        Arc::new(OsFs),
                        clock.clone(),
                        recover,
                    )
                    .expect("opens");
                    store.pack_after_every_write(alone());
                    store
                })
            };
            let plant_dir = objects_dir.clone();
            let plant: SharedPlant = Arc::new(move |name, bytes| {
                std::fs::write(plant_dir.join(name), bytes).expect("plants an object file");
            });
            let (held, lose, alter) = blobs(objects, Some(packs.clone()), plant.clone());
            let (reopen, unreadable) = (open.clone(), open.clone());
            let (readable, unreachable) = (packs.clone(), packs);
            Fresh {
                store: open(true),
                reopen: Box::new(move || {
                    readable.fail_reads.store(false, Ordering::SeqCst);
                    reopen(true)
                }),
                unreadable: Box::new(move || {
                    let store = unreadable(false);
                    unreachable.fail_reads.store(true, Ordering::SeqCst);
                    store
                }),
                held,
                lose,
                alter,
                plant: Box::new(move |name, bytes| plant(name, bytes)),
            }
        }
    }

    /// 4.1, without a service: the suite on Parquet storage in a
    /// directory.
    #[test]
    fn the_local_catalog_with_parquet_storage_conforms() {
        run(&PackedLocal(tempfile::tempdir().expect("temp dir")));
    }
}