tinystore 0.12.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
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
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs::{self, File, OpenOptions, TryLockError};
use std::path::{Path, PathBuf};
#[cfg(any(
    feature = "kv",
    feature = "jobs",
    feature = "sql",
    feature = "records",
    feature = "metrics",
    feature = "replication",
    all(feature = "search", feature = "async")
))]
use std::sync::Weak;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};

#[cfg(feature = "kv")]
use crate::encryption::{self, EncryptionKey, Keyring, SealedIn};
use crate::engine::{Claim, Engine, Handling, Host, Wake};
use crate::probe::Probe;
use crate::schedule::Scheduler;
#[cfg(any(feature = "kv", feature = "jobs"))]
use crate::sqlite::File as EngineFile;
use crate::sync::lock;
use crate::{Clock, Durability, Error, ErrorKind, Memory, Result, SystemClock};

/// How a store opens.
pub struct Options {
    /// Bytes all engines' work may hold at once; `None` leaves each engine to
    /// its own per-call bounds.
    pub memory: Option<u64>,
    /// Where the store and every engine read the time; the system's clock when
    /// `None`.
    pub clock: Option<Arc<dyn Clock>>,
    /// Whether the store runs periodic work, expiry and maintenance among it.
    /// Tests turn it off and run each engine's maintenance themselves.
    pub background: bool,
    /// How far a commit of the store's files goes before it returns: `kv.db`,
    /// `jobs.db`, and every database that does not say its own. `None` leaves
    /// each engine its own, which for these is [`Durability::Full`].
    pub durability: Option<Durability>,
    /// Bytes of the disk the store keeps free: a file that would leave less is
    /// a `Limit` error and leaves nothing. 1 GiB unless said; 0 keeps none.
    pub keep_free: u64,
    /// The file of the store's encryption key, which seals the values of its
    /// encrypted buckets: 64 hex digits, as `openssl rand -hex 32` writes. The
    /// store reads it and never makes it. `None` is `encryption.key` in the
    /// store's directory, which the store makes the first time it needs one.
    pub encryption_key_file: Option<PathBuf>,
    /// The files of the store's older keys, which open the values they
    /// sealed and seal nothing new: a key being rotated out, until
    /// `reseal` has sealed every value again, or one found after a restore
    /// that left it out. Each file must be there.
    pub older_encryption_keys: Vec<PathBuf>,
    /// Makes the store a node, which keeps a log of each file it writes for
    /// other nodes to copy; `None` is a store alone.
    #[cfg(feature = "replication")]
    pub node: Option<crate::replication::Node>,
    /// Measures the store into its own `metrics.db`, under names that start
    /// with `tinystore_`: its commits, their waits, its files, its memory and
    /// the machine it runs on, as docs/guides/metrics/self-metrics.md lists them. `None`
    /// unless asked for.
    #[cfg(feature = "metrics")]
    pub self_metrics: Option<crate::metrics::SelfMetrics>,
    /// The metrics series the store holds at most: a new series past them is
    /// a `Limit` error, and a series kept no longer gives its place back.
    /// 100,000 unless said; docs/guides/metrics/ingesting.md says what one costs.
    #[cfg(feature = "metrics")]
    pub max_series: u64,
    /// Lets the `tinystore` command line write to this store while the
    /// program runs: the store listens on a socket, or on Windows a named
    /// pipe, that only the user it runs as may reach, and names it in
    /// `server/SERVE` until it closes. Off unless asked for.
    #[cfg(feature = "local")]
    pub cli: bool,
}

/// The disk a store keeps free unless its options say otherwise.
pub(crate) const KEEP_FREE: u64 = 1 << 30;

/// The metrics series a store holds unless its options say otherwise.
#[cfg(feature = "metrics")]
pub(crate) const MAX_SERIES: u64 = 100_000;

impl Default for Options {
    fn default() -> Self {
        Self {
            memory: None,
            clock: None,
            background: true,
            durability: None,
            keep_free: KEEP_FREE,
            encryption_key_file: None,
            older_encryption_keys: Vec::new(),
            #[cfg(feature = "replication")]
            node: None,
            #[cfg(feature = "metrics")]
            self_metrics: None,
            #[cfg(feature = "metrics")]
            max_series: MAX_SERIES,
            #[cfg(feature = "local")]
            cli: false,
        }
    }
}

impl fmt::Debug for Options {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let f = &mut f.debug_struct("Options");
        let f = f
            .field("memory", &self.memory)
            .field("clock", &self.clock.as_ref().map(|_| "custom"))
            .field("background", &self.background)
            .field("durability", &self.durability)
            .field("keep_free", &self.keep_free)
            .field("encryption_key_file", &self.encryption_key_file)
            .field("older_encryption_keys", &self.older_encryption_keys);
        #[cfg(feature = "replication")]
        let f = f.field("node", &self.node);
        #[cfg(feature = "metrics")]
        let f = f.field("self_metrics", &self.self_metrics).field("max_series", &self.max_series);
        #[cfg(feature = "local")]
        let f = f.field("cli", &self.cli);
        f.finish()
    }
}

/// One directory of engine files, held by one store at a time through its
/// `LOCK`. Engines open against a store and close with it, the last opened
/// first: at `close`, or when the last clone of the store is dropped.
#[derive(Clone)]
pub struct Store {
    inner: Arc<Inner>,
}

/// A store that its engines reach without keeping it open: an engine holds
/// this, so that dropping the application's last handle closes the store.
#[derive(Clone, Debug)]
#[cfg(any(
    feature = "kv",
    feature = "jobs",
    feature = "sql",
    feature = "records",
    feature = "metrics",
    feature = "replication",
    all(feature = "search", feature = "async")
))]
pub(crate) struct WeakStore(Weak<Inner>);

#[cfg(any(
    feature = "kv",
    feature = "jobs",
    feature = "sql",
    feature = "records",
    feature = "metrics",
    feature = "replication",
    all(feature = "search", feature = "async")
))]
impl WeakStore {
    pub(crate) fn upgrade(&self) -> Option<Store> {
        self.0.upgrade().map(|inner| Store { inner })
    }
}

/// Engines open on a file, each by its type.
pub(crate) type Engines = HashMap<TypeId, Arc<dyn Any + Send + Sync>>;

struct Inner {
    dir: PathBuf,
    lock: Mutex<Option<File>>,
    clock: Arc<dyn Clock>,
    memory: Arc<Memory>,
    /// What ends the patience of the waits that hold no thread, as a
    /// reservation of memory an awaited call waits for.
    #[cfg(feature = "async")]
    timer: Arc<crate::timer::Timer>,
    /// What the store measures of itself goes through, heard only when it
    /// was opened with `self_metrics`.
    probe: Arc<Probe>,
    scheduler: Scheduler,
    engines: Mutex<Vec<Arc<dyn Engine>>>,
    /// The engine of each kind this store has open, which every handle of that
    /// engine shares: one `kv.db` writer however many buckets open.
    open: Mutex<Engines>,
    /// Shared with each claim's release, which must not keep the store open.
    claims: Arc<Mutex<HashSet<String>>>,
    /// Every file's, which a backup shuts while the reads of its moment begin.
    gate: Arc<crate::sqlite::Gate>,
    /// The engines' own files, kv.db and jobs.db, which the store's
    /// transaction is a transaction of one of.
    #[cfg(any(feature = "kv", feature = "jobs"))]
    files: Mutex<Vec<Arc<EngineFile>>>,
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search"
        )),
        expect(dead_code, reason = "only an engine of files reads it, and channels keep none")
    )]
    durability: Option<Durability>,
    keep_free: u64,
    #[cfg(feature = "metrics")]
    max_series: u64,
    #[cfg(feature = "kv")]
    encryption_key_file: Option<PathBuf>,
    #[cfg(feature = "kv")]
    older_encryption_keys: Vec<PathBuf>,
    /// The keys, once a handle needed them: a store that seals nothing reads
    /// no key and makes none.
    #[cfg(feature = "kv")]
    encryption_key: Mutex<Option<Arc<Keyring>>>,
    /// The node the store is, its logs, copies and links; `None` in a store
    /// alone.
    #[cfg(feature = "replication")]
    node: Option<Arc<crate::replication::State>>,
    /// Opened beside the process that holds the directory: it reads only.
    beside: bool,
    /// What marks the threads that run the handlers its close waits for.
    handling: Handling,
    /// The command line's endpoint, when the store was opened with `cli`:
    /// stopped first at the close, so that `SERVE` goes before `LOCK`.
    #[cfg(feature = "local")]
    endpoint: Mutex<Option<crate::local::Endpoint>>,
    closed: AtomicBool,
}

impl Store {
    /// Opens the store in `dir`, creating the directory when it is missing.
    /// Another store holding the directory, in this process or another, makes
    /// it an `InUse` error.
    pub fn open(dir: impl AsRef<Path>, options: Options) -> Result<Store> {
        let dir = absolute(dir.as_ref())?;
        let lock = take_lock(&dir)?;
        refuse_half_restored(&dir)?;
        remove_left_snapshots(&dir);
        #[cfg(feature = "local")]
        let cli = options.cli;
        let store = Self::open_with(dir, options, Some(lock))?;
        #[cfg(feature = "local")]
        if cli {
            store.listen_for_the_command_line()?;
        }
        Ok(store)
    }

    /// Whether the store was opened with `cli`, and its endpoint still serves.
    #[cfg(feature = "local")]
    pub(crate) fn serves_the_command_line(&self) -> bool {
        lock(&self.inner.endpoint).is_some()
    }

    /// Starts the command line's endpoint, or closes the store and says why
    /// not, as a pipe name another process squats on.
    #[cfg(feature = "local")]
    fn listen_for_the_command_line(&self) -> Result<()> {
        match crate::local::Endpoint::start(self) {
            Ok(endpoint) => {
                *lock(&self.inner.endpoint) = Some(endpoint);
                Ok(())
            }
            Err(error) => {
                let _ = self.close();
                Err(Error::io(format!("{}: its endpoint for the command line", self.describe()), error))
            }
        }
    }

    /// Opens the store in `dir` to read beside the process that holds it, a
    /// server or a program: no lock taken, no background work, each file read
    /// through readers alone, none written and none checkpointed. A write is
    /// refused, `Invalid`, and a file the store does not hold is `NotFound`
    /// rather than made. What the holder commits meanwhile, a read sees.
    pub fn open_beside(dir: impl AsRef<Path>) -> Result<Store> {
        if !dir.as_ref().is_dir() {
            return Err(Error::not_found(format!("store {}: no such directory", dir.as_ref().display())));
        }
        let dir = absolute(dir.as_ref())?;
        refuse_half_restored(&dir)?;
        Self::open_with(dir, Options { background: false, ..Options::default() }, None)
    }

    fn open_with(dir: PathBuf, options: Options, lock: Option<File>) -> Result<Store> {
        #[cfg(feature = "metrics")]
        if options.max_series == 0 {
            return Err(Error::invalid(format!("store {}: a max_series of 0, which holds no series", dir.display())));
        }
        let beside = lock.is_none();
        #[cfg(feature = "metrics")]
        let self_metrics = options.self_metrics.filter(|_| !beside);
        let probe = Arc::new(Probe::default());
        let limit = options.memory.unwrap_or(u64::MAX);
        #[cfg(feature = "async")]
        let timer = Arc::new(crate::timer::Timer::new());
        let inner = Inner {
            lock: Mutex::new(lock),
            clock: options.clock.unwrap_or_else(|| Arc::new(SystemClock)),
            #[cfg(feature = "async")]
            memory: Memory::on(limit, Arc::clone(&timer)),
            #[cfg(not(feature = "async"))]
            memory: Memory::new(limit),
            #[cfg(feature = "async")]
            timer,
            scheduler: Scheduler::new(options.background, Arc::clone(&probe)),
            probe,
            engines: Mutex::new(Vec::new()),
            open: Mutex::new(HashMap::new()),
            claims: Arc::default(),
            gate: Arc::default(),
            #[cfg(any(feature = "kv", feature = "jobs"))]
            files: Mutex::new(Vec::new()),
            durability: options.durability,
            keep_free: options.keep_free,
            #[cfg(feature = "metrics")]
            max_series: options.max_series,
            #[cfg(feature = "kv")]
            encryption_key_file: options.encryption_key_file,
            #[cfg(feature = "kv")]
            older_encryption_keys: options.older_encryption_keys,
            #[cfg(feature = "kv")]
            encryption_key: Mutex::new(None),
            #[cfg(feature = "replication")]
            node: options
                .node
                .map(|node| crate::replication::State::new(&dir, node, options.keep_free).map(Arc::new))
                .transpose()?,
            beside,
            handling: Handling::new(),
            #[cfg(feature = "local")]
            endpoint: Mutex::new(None),
            closed: AtomicBool::new(false),
            dir,
        };
        let store = Store { inner: Arc::new(inner) };
        #[cfg(feature = "replication")]
        if let Some(node) = &store.inner.node {
            node.start(&store)?;
        }
        // before any engine, so that every file is measured from its first commit
        #[cfg(feature = "metrics")]
        if let Some(asked) = self_metrics {
            crate::metrics::measure_the_store(&store, asked)?;
        }
        Ok(store)
    }

    pub fn dir(&self) -> &Path {
        &self.inner.dir
    }

    /// Whether the store was opened beside its holder, to read only.
    pub fn is_beside(&self) -> bool {
        self.inner.beside
    }

    /// Opens an engine's SQLite file, `name` inside the store's directory, its
    /// commits logged when the store is a node.
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search"
        )),
        expect(dead_code, reason = "only an engine of files opens one, and channels keep none")
    )]
    pub(crate) fn open_file(&self, name: &str, config: crate::sqlite::Config) -> Result<crate::sqlite::File> {
        if self.inner.beside {
            return self.open_to_read(name, config);
        }
        let path = self.inner.dir.join(name);
        let config = self.file_config(name, config);
        #[cfg(feature = "replication")]
        if let Some(node) = &self.inner.node {
            let config =
                crate::sqlite::Config { catch_up: Some(crate::replication::catching_up(self, name)), ..config };
            // the route is chosen and the file opened on one side of a change of
            // the route: a takeover, a hand-over or a snapshot taken again
            let _opening = node.wait_to_open(name).map_err(|error| error.within(self.describe()))?;
            if node.is_new(name) && node.uses_catalog() {
                return self.open_new_in_the_catalog(node, name, config);
            }
            if node.takes(name) {
                node.wait_ready(name).map_err(|error| error.within(self.describe()))?;
                return Ok(node.opened(name, crate::sqlite::File::open_copy(path, config)?));
            }
            if crate::replication::is_copy(&node.log_dir(name)) {
                return Ok(node.opened(name, crate::sqlite::File::open_copy(path, config)?));
            }
            let file = crate::sqlite::File::open_observed(path, config, Some(node.open_log(name)?))?;
            return Ok(node.opened(name, file));
        }
        crate::sqlite::File::open(path, config)
    }

    /// Opens the file `name` inside the store's directory to read it, as a
    /// store beside its holder reads each file: through readers alone, none
    /// written and none checkpointed, by no engine's claim. A file the store
    /// does not hold is `NotFound` rather than made.
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search"
        )),
        expect(dead_code, reason = "only an engine of files opens one, and channels keep none")
    )]
    pub(crate) fn open_to_read(&self, name: &str, config: crate::sqlite::Config) -> Result<crate::sqlite::File> {
        self.holds(name)?;
        crate::sqlite::File::open_copy(self.inner.dir.join(name), self.file_config(name, config))
    }

    /// `config` with what the store gives each file it opens: its memory, the
    /// gate a backup's moment shuts and the file's own probe.
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search"
        )),
        expect(dead_code, reason = "only an engine of files opens one, and channels keep none")
    )]
    fn file_config(&self, name: &str, config: crate::sqlite::Config) -> crate::sqlite::Config {
        let probe = Some(self.inner.probe.for_file(crate::probe::label(name)));
        let (memory, gate) = (Some(Arc::clone(&self.inner.memory)), Some(Arc::clone(&self.inner.gate)));
        crate::sqlite::Config { memory, probe, gate, ..config }
    }

    /// Refuses the file `name` inside the store's directory, `NotFound`, while
    /// the store does not hold it: what may only read, a store beside its
    /// holder or a connection that only reads, makes none.
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search"
        )),
        expect(dead_code, reason = "only an engine of files opens one, and channels keep none")
    )]
    pub(crate) fn holds(&self, name: &str) -> Result<()> {
        if self.inner.dir.join(name).exists() {
            return Ok(());
        }
        Err(Error::not_found(format!("{}: it holds no {name}", self.describe())))
    }

    /// Opens a file no node of the store's held before it: written here once
    /// this node's claim in the catalog won, copied from its home otherwise.
    #[cfg(feature = "replication")]
    fn open_new_in_the_catalog(
        &self,
        node: &Arc<crate::replication::State>,
        name: &str,
        config: crate::sqlite::Config,
    ) -> Result<crate::sqlite::File> {
        let path = self.inner.dir.join(name);
        match node.claim(self, name).map_err(|error| error.within(self.describe()))? {
            crate::replication::Claimed::Here => {
                let file = crate::sqlite::File::open_observed(path, config, Some(node.open_log(name)?))?;
                return Ok(node.opened(name, file));
            }
            crate::replication::Claimed::At(address) => node.take_directly(self, name, &address)?,
            crate::replication::Claimed::From if !node.takes(name) => {
                return Err(Error::new(
                    crate::ErrorKind::Unavailable,
                    format!("{name}: its home serves nothing other nodes reach, and this node takes from none"),
                )
                .within(self.describe()));
            }
            crate::replication::Claimed::From => {}
        }
        node.wait_ready(name).map_err(|error| error.within(self.describe()))?;
        Ok(node.opened(name, crate::sqlite::File::open_copy(path, config)?))
    }

    /// The directory of the log of the store's file `name`; a store that is
    /// no node keeps none.
    #[cfg(feature = "replication")]
    pub(crate) fn log_of(&self, name: &str) -> Result<PathBuf> {
        let node = self.inner.node.as_ref().ok_or_else(|| {
            Error::invalid(format!("{}: a store that is no node keeps no log: open it with a node", self.describe()))
        })?;
        Ok(node.log_dir(name))
    }

    /// The node the store is, if it is one.
    #[cfg(feature = "replication")]
    pub(crate) fn node(&self) -> Option<&Arc<crate::replication::State>> {
        self.inner.node.as_ref()
    }

    /// What a node's links wait on for the next entry of its logs.
    #[cfg(feature = "replication")]
    pub(crate) fn node_notify(&self) -> Arc<crate::replication::Notify> {
        self.inner.node.as_ref().map_or_else(Arc::default, |node| Arc::clone(&node.notify))
    }

    /// The bounds of a node's logs, a copy's as a home's, so that the disk
    /// the store keeps free reaches both.
    #[cfg(feature = "replication")]
    pub(crate) fn node_bounds(&self) -> crate::replication::Bounds {
        self.inner.node.as_ref().map_or_else(Default::default, |node| node.bounds())
    }

    /// Tells every engine open that a commit of its home was applied to the
    /// copy `name`.
    #[cfg(feature = "replication")]
    pub(crate) fn applied(&self, name: &str) {
        let engines = lock(&self.inner.engines).clone();
        for engine in engines {
            engine.applied(name);
        }
    }

    /// What the store's options said of its files' commits, for an engine
    /// that opens one.
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search"
        )),
        expect(dead_code, reason = "only an engine of files reads it, and channels keep none")
    )]
    pub(crate) fn durability(&self) -> Option<Durability> {
        self.inner.durability
    }

    /// The file its options named for its encryption key, if they named one.
    #[cfg(all(feature = "kv", any(feature = "wire", feature = "backup")))]
    pub(crate) fn encryption_key_file(&self) -> Option<&Path> {
        self.inner.encryption_key_file.as_deref()
    }

    /// The bytes of the disk the store keeps free, as its options said.
    pub fn keep_free(&self) -> u64 {
        self.inner.keep_free
    }

    /// The metrics series the store holds at most, as its options said.
    #[cfg(feature = "metrics")]
    pub fn max_series(&self) -> u64 {
        self.inner.max_series
    }

    /// The store's encryption keys. The one that seals is in the file its
    /// options named, or in `encryption.key` of its directory, which the
    /// store makes when it is not there and `sealed_in` finds no value of
    /// its directory sealed with a key. For a bucket that holds nothing
    /// sealed yet.
    #[cfg(feature = "kv")]
    pub(crate) fn encryption_key(&self, sealed_in: SealedIn) -> Result<Arc<Keyring>> {
        self.read_encryption_key(Some(sealed_in))
    }

    /// The store's encryption keys, which are there already: a key lost is
    /// not replaced, since values sealed with it open with no other.
    #[cfg(feature = "kv")]
    pub(crate) fn encryption_key_there(&self) -> Result<Arc<Keyring>> {
        self.read_encryption_key(None)
    }

    /// The keys, the sealing one made only by a call that says how to find
    /// what is sealed.
    #[cfg(feature = "kv")]
    fn read_encryption_key(&self, make: Option<SealedIn>) -> Result<Arc<Keyring>> {
        self.refuse_when_closed("its encryption key")?;
        let mut kept = lock(&self.inner.encryption_key);
        if let Some(key) = &*kept {
            return Ok(Arc::clone(key));
        }
        let own = self.inner.dir.join(encryption::FILE);
        // a store opened beside its holder never makes the key file: it reads
        // the key there, as any other file
        let sealing = match (&self.inner.encryption_key_file, make) {
            (Some(file), _) => EncryptionKey::read(file)?,
            (None, Some(sealed_in)) if !self.inner.beside => self.read_or_make_key(&own, sealed_in)?,
            (None, _) => EncryptionKey::read(&own)?,
        };
        let older = self.inner.older_encryption_keys.iter().map(|file| {
            EncryptionKey::read(file).map_err(|error| error.within("one of the store's older encryption keys"))
        });
        let ring = Arc::new(Keyring::of(sealing, older.collect::<Result<Vec<_>>>()?));
        *kept = Some(Arc::clone(&ring));
        Ok(ring)
    }

    /// The files of the store's older keys, as its options named them.
    #[cfg(all(feature = "kv", feature = "wire"))]
    pub(crate) fn older_encryption_keys(&self) -> &[PathBuf] {
        &self.inner.older_encryption_keys
    }

    /// The key of `own`, made when it is not there, unless values of the
    /// store's directory are sealed with a key, in a file open or not: that
    /// key was lost, a backup left it out or it was deleted, and a new one
    /// would seal what the lost one cannot open once it is put back.
    #[cfg(feature = "kv")]
    fn read_or_make_key(&self, own: &Path, sealed_in: SealedIn) -> Result<EncryptionKey> {
        if !own.exists()
            && let Some(id) = sealed_in(&self.inner.dir)?
        {
            return Err(Error::new(
                ErrorKind::Io,
                format!(
                    "the encryption key {}: not there, and values sealed with the key {id} remain: \
                     put the key back, since the store makes no other while they do, or put a new one there, \
                     which seals new values beside them",
                    own.display()
                ),
            ));
        }
        EncryptionKey::read_or_make(own)
    }

    pub fn now(&self) -> SystemTime {
        self.inner.clock.now()
    }

    /// Tells every engine that a test moved the store's clock by hand, so
    /// that what sleeps until a time reads it again: a worker waiting for a
    /// job due in an hour runs it once the clock is an hour on.
    pub fn clock_moved(&self) {
        let engines = lock(&self.inner.engines).clone();
        for engine in engines {
            engine.clock_moved();
        }
    }

    pub fn memory(&self) -> &Arc<Memory> {
        &self.inner.memory
    }

    /// What rings the deadlines of the waits that hold no thread, as an
    /// awaited wait for an index to be ready looks again at its status.
    #[cfg(all(feature = "async", feature = "search"))]
    pub(crate) fn timer(&self) -> &Arc<crate::timer::Timer> {
        &self.inner.timer
    }

    /// What the store measures of itself goes through.
    #[allow(dead_code, reason = "each engine reports what it measures: a store of none of them reads it not")]
    pub(crate) fn probe(&self) -> &Arc<Probe> {
        &self.inner.probe
    }

    /// Stops background work, waiting for the task under way, then every
    /// handler the engines run, a queue's or a channel's, waiting for those
    /// running; then closes every engine, the last opened first, and lets go
    /// of the directory. The first engine that fails to close is the error;
    /// the others still close. A second call does nothing, and neither does
    /// the last clone's drop after. From inside a transaction it is
    /// `Invalid`: it would wait for the writer the transaction holds. So it is
    /// from inside one of the handlers it waits for, a worker's, a schedule's
    /// or a subscription's, blocking or awaited: it would wait for the handler
    /// that calls it. Such a handler returns first, or stops its worker or its
    /// subscription, whose stop returns at once there.
    pub fn close(&self) -> Result<()> {
        self.refuse_where_a_close_would_wait_for_itself()?;
        self.inner.close()
    }

    /// Refuses a close from inside a transaction, which holds a writer the
    /// close waits for, or from inside a handler of this store's, which the
    /// close waits for too.
    pub(crate) fn refuse_where_a_close_would_wait_for_itself(&self) -> Result<()> {
        let why = if crate::sqlite::in_a_transaction() {
            "a close from inside a transaction would wait for the writer the transaction holds: close after it"
        } else if self.inner.handling.on_this_thread() {
            "a close from inside a handler would wait for the handler that calls it: close after it returns, \
             or stop its worker or subscription, whose stop returns at once there"
        } else {
            return Ok(());
        };
        Err(Error::invalid(why).within(self.describe()))
    }

    /// What marks the threads that run the handlers this store's close waits
    /// for, as they run them.
    #[cfg(any(feature = "jobs", feature = "channels"))]
    pub(crate) fn handling(&self) -> Handling {
        self.inner.handling
    }

    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "search",
            feature = "backup"
        )),
        expect(dead_code, reason = "only an engine of files reads the clock, and channels keep none")
    )]
    pub(crate) fn clock(&self) -> Arc<dyn Clock> {
        Arc::clone(&self.inner.clock)
    }

    #[cfg(any(
        feature = "kv",
        feature = "sql",
        feature = "records",
        feature = "metrics",
        feature = "replication",
        all(feature = "jobs", feature = "async"),
        all(feature = "search", feature = "async")
    ))]
    pub(crate) fn downgrade(&self) -> WeakStore {
        WeakStore(Arc::downgrade(&self.inner))
    }

    /// Keeps an engine's own file among those [`Store::tx`] may be a
    /// transaction of.
    #[cfg(any(feature = "kv", feature = "jobs"))]
    pub(crate) fn keep_file(&self, file: &Arc<EngineFile>) {
        lock(&self.inner.files).push(Arc::clone(file));
    }

    #[cfg(any(feature = "kv", feature = "jobs"))]
    pub(crate) fn engine_files(&self) -> Vec<Arc<EngineFile>> {
        lock(&self.inner.files).clone()
    }

    /// Every engine the store has open, and the names they hold in its
    /// directory: what a snapshot asks to copy their own.
    #[cfg(feature = "backup")]
    pub(crate) fn engines_open(&self) -> Result<EnginesOpen> {
        self.refuse_when_closed("a snapshot")?;
        let _opening = lock(&self.inner.open);
        Ok((lock(&self.inner.engines).clone(), lock(&self.inner.claims).clone()))
    }

    /// What holds every file of the store still for a snapshot's moment.
    #[cfg(feature = "backup")]
    pub(crate) fn gate(&self) -> &crate::sqlite::Gate {
        &self.inner.gate
    }

    fn describe(&self) -> String {
        self.inner.describe()
    }

    /// The engine of type `E` that `kept` holds, or the one `open` makes,
    /// attached to the store and kept there.
    pub(crate) fn kept_or_opened<E: Engine>(
        &self,
        kept: &Mutex<Engines>,
        open: impl FnOnce(&Store) -> Result<Arc<E>>,
    ) -> Result<Arc<E>> {
        let mut kept = lock(kept);
        if let Some(engine) = kept.get(&TypeId::of::<E>()) {
            let engine = Arc::clone(engine);
            return Ok(engine.downcast::<E>().expect("an engine is kept under its own type"));
        }
        let engine = open(self)?;
        self.attach(Arc::clone(&engine) as Arc<dyn Engine>)?;
        kept.insert(TypeId::of::<E>(), Arc::clone(&engine) as Arc<dyn Any + Send + Sync>);
        Ok(engine)
    }

    pub(crate) fn refuse_when_closed(&self, what: &str) -> Result<()> {
        if self.inner.closed.load(Ordering::SeqCst) {
            return Err(Error::closed(format!("{}: {what}", self.describe())));
        }
        Ok(())
    }
}

impl Host for Store {
    fn engine<E: Engine>(&self, open: impl FnOnce(&Store) -> Result<Arc<E>>) -> Result<Arc<E>> {
        self.refuse_when_closed("an engine opening")?;
        self.kept_or_opened(&self.inner.open, |store| crate::sqlite::own_work(|| open(store)))
    }

    fn attach(&self, engine: Arc<dyn Engine>) -> Result<()> {
        // The check and the push hold the list's lock, which `close` takes
        // only after it marks the store closed: an engine is in the list
        // `close` takes, or refused here, never pushed onto a list taken.
        let mut engines = lock(&self.inner.engines);
        if let Err(closed) = self.refuse_when_closed("an engine opening") {
            drop(engines);
            // what it opened is closed here, since the store's close never sees it
            engine.stop();
            if let Err(error) = engine.close() {
                tracing::warn!(target: "tinystore", %error, "an engine opened as its store closed did not close");
            }
            return Err(closed);
        }
        engines.push(engine);
        Ok(())
    }

    fn every(&self, name: &str, period: Duration, work: impl FnMut() -> Result<()> + Send + 'static) -> Result<Wake> {
        self.refuse_when_closed(name)?;
        self.inner.scheduler.add(name, period, Box::new(work))
    }

    fn claim(&self, name: &str) -> Result<Claim> {
        self.refuse_when_closed(name)?;
        if !lock(&self.inner.claims).insert(name.to_owned()) {
            return Err(Error::new(ErrorKind::InUse, format!("{}: {name} is already open", self.describe())));
        }
        let claims = Arc::clone(&self.inner.claims);
        let release = Box::new(move |name: &str| {
            lock(&claims).remove(name);
        });
        Ok(Claim::new(name, self.inner.dir.join(name), release))
    }
}

impl Inner {
    fn close(&self) -> Result<()> {
        // before the store refuses anything, so that the calls its command
        // line clients have under way may finish (STORE-13)
        #[cfg(feature = "local")]
        {
            let endpoint = lock(&self.endpoint).take();
            if let Some(mut endpoint) = endpoint {
                endpoint.stop();
            }
        }
        if self.closed.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        #[cfg(feature = "replication")]
        if let Some(node) = &self.node {
            node.stop();
        }
        self.scheduler.stop();
        let engines = std::mem::take(&mut *lock(&self.engines));
        // a handler writes engines opened after its own, so none closes before every handler ended
        for engine in engines.iter().rev() {
            engine.stop();
        }
        let mut first_failure = None;
        for engine in engines.iter().rev() {
            if let Err(error) = engine.close() {
                first_failure.get_or_insert(error);
            }
        }
        lock(&self.open).clear();
        #[cfg(any(feature = "kv", feature = "jobs"))]
        lock(&self.files).clear();
        // a reservation still waiting for memory is answered closed
        #[cfg(feature = "async")]
        self.timer.stop();
        drop(lock(&self.lock).take());
        first_failure.map_or(Ok(()), |error| Err(error.within(self.describe())))
    }

    fn describe(&self) -> String {
        format!("store {}", self.dir.display())
    }
}

impl Drop for Inner {
    /// Closes a store its application dropped without closing, so that what
    /// engines hold in memory is written and the directory is let go.
    fn drop(&mut self) {
        if let Err(error) = self.close() {
            tracing::warn!(target: "tinystore", %error, "a store dropped without close did not close cleanly");
        }
    }
}

impl fmt::Debug for Store {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.describe())
    }
}

fn absolute(dir: &Path) -> Result<PathBuf> {
    if dir.as_os_str().is_empty() {
        return Err(Error::invalid("store: a directory with no name"));
    }
    let dir = std::path::absolute(dir).map_err(|error| Error::io(format!("store {}", dir.display()), error))?;
    if let Err(error) = fs::create_dir_all(&dir) {
        return Err(match file_in_the_way(&dir) {
            Some(file) if file == dir => Error::invalid(format!("store {} is a file, not a directory", dir.display())),
            Some(file) => {
                Error::invalid(format!("store {}: {} is a file, not a directory", dir.display(), file.display()))
            }
            None => Error::io(format!("store {}", dir.display()), error),
        });
    }
    Ok(dir)
}

/// The first of a directory and the folders above it that is there, when it
/// is a file: what kept the directory from being made. The system's own error
/// says neither which, nor, on Windows, that it is a file at all.
fn file_in_the_way(dir: &Path) -> Option<&Path> {
    let (found, there) = dir.ancestors().find_map(|path| fs::metadata(path).ok().map(|there| (path, there)))?;
    (!there.is_dir()).then_some(found)
}

/// The engines a store has open, and the names they hold in its directory.
#[cfg(feature = "backup")]
pub(crate) type EnginesOpen = (Vec<Arc<dyn Engine>>, HashSet<String>);

/// Takes the directory's `LOCK`. The lock belongs to the open file, so a
/// second store in the same process is refused like one in another process,
/// and the operating system lets go of it if the process dies.
pub(crate) fn take_lock(dir: &Path) -> Result<File> {
    let path = dir.join("LOCK");
    let what = || format!("store {}: LOCK", dir.display());
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
        .map_err(|error| Error::io(what(), error))?;
    match file.try_lock() {
        Ok(()) => Ok(file),
        Err(TryLockError::WouldBlock) => Err(Error::new(ErrorKind::InUse, held_by(dir, what()))),
        Err(TryLockError::Error(error)) => Err(Error::io(what(), error)),
    }
}

/// What a restore puts in the directory before any file of the backup's,
/// and removes once every one is synced: a directory that holds it is part
/// of a backup, its restore's process gone, and no store opens it.
pub(crate) const RESTORING: &str = "RESTORING";

/// What to do with a directory a restore did not finish in.
pub(crate) const HALF_RESTORED: &str = "a restore did not finish in it: remove the directory and restore again";

/// Refuses a directory a restore did not finish in, which a store would
/// otherwise open as though it held the whole backup.
fn refuse_half_restored(dir: &Path) -> Result<()> {
    if dir.join(RESTORING).exists() {
        return Err(Error::invalid(format!("store {}: {HALF_RESTORED}", dir.display())));
    }
    Ok(())
}

/// How the name of a backup's snapshot in the store's directory starts: a
/// copy of every engine's files, which holds a `LOCK` of its own while its
/// backup runs.
pub(crate) const SNAPSHOT: &str = ".snapshot-";

/// Removes the snapshots a backup's process left when it died, which nothing
/// else removes: copies of every file of the store, kept for ever otherwise.
/// A backup beside the holder copies into its directory too, so a snapshot
/// whose `LOCK` is held is a backup's still running, and stays.
fn remove_left_snapshots(dir: &Path) {
    let Ok(entries) = fs::read_dir(dir) else { return };
    for entry in entries.flatten() {
        let named = entry.file_name().to_str().is_some_and(|name| name.starts_with(SNAPSHOT));
        // the entry's own type: a link to a directory elsewhere is no snapshot
        if !named || !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
            continue;
        }
        let left = entry.path();
        if take_lock(&left).is_err() {
            continue;
        }
        // its lock let go before: Windows removes no directory with a file open
        if let Err(error) = fs::remove_dir_all(&left) {
            let snapshot = left.display();
            tracing::warn!(target: "tinystore", %error, %snapshot, "a backup's snapshot a dead process left stays");
        }
    }
}

/// Who holds the `LOCK`, as far as the directory says: a server publishes
/// `server/SERVE` while it serves, and a sidecar serves on after its last
/// client closed, so a program that opens the directory embedded next is
/// told how to let it go; a program that opened it with `cli` publishes one
/// too, `"embedded"`, and is named by its pid.
fn held_by(dir: &Path, what: String) -> String {
    let Ok(serve) = fs::read_to_string(dir.join("server").join("SERVE")) else {
        return format!("{what}: another store holds it");
    };
    let published: serde_json::Value = serde_json::from_str(&serve).unwrap_or_default();
    if published["embedded"] == true {
        let pid = &published["pid"];
        return format!("{what}: a program holds it inside its own process, pid {pid}");
    }
    let dir = dir.display();
    format!("{what}: a tinystore server holds it; connect to it, or stop it first with `tinystore stop {dir}`")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TestClock;

    struct Recorder {
        name: &'static str,
        closed: Arc<Mutex<Vec<&'static str>>>,
    }

    impl Engine for Recorder {
        fn close(&self) -> Result<()> {
            lock(&self.closed).push(self.name);
            Ok(())
        }
    }

    // contract: STORE-01
    #[test]
    #[cfg(all(feature = "kv", feature = "jobs", feature = "replication"))]
    fn a_store_opened_beside_its_holder_reads_what_it_commits_and_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let holder = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
        let sessions = holder.bucket::<String>("sessions").open().unwrap();
        sessions.set("a", &"first".to_owned()).unwrap();

        let beside = Store::open_beside(dir.path()).unwrap();
        assert!(beside.is_beside());
        let read = beside.bucket::<String>("sessions").open().unwrap();
        assert_eq!(read.get("a").unwrap().as_deref(), Some("first"));
        sessions.set("b", &"committed after".to_owned()).unwrap();
        assert_eq!(read.get("b").unwrap().as_deref(), Some("committed after"), "a read sees the holder's commits");
        let refused = read.set("c", &"no".to_owned()).unwrap_err();
        assert_eq!(refused.kind(), ErrorKind::Invalid, "{refused}");
        let missing = beside.queue::<String>("mail").open().unwrap_err();
        assert_eq!(missing.kind(), ErrorKind::NotFound, "a file it does not hold is not made: {missing}");
        assert!(!dir.path().join("jobs.db").exists());
        beside.close().unwrap();
        sessions.set("d", &"the holder writes on".to_owned()).unwrap();
        holder.close().unwrap();
        assert!(Store::open_beside(dir.path().join("nowhere")).is_err());
    }

    #[test]
    fn a_directory_opens_in_one_store_at_a_time() {
        let dir = tempfile::tempdir().unwrap();
        let first = Store::open(dir.path(), Options::default()).unwrap();
        let error = Store::open(dir.path(), Options::default()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InUse, "{error}");

        first.close().unwrap();
        let second = Store::open(dir.path(), Options::default()).unwrap();
        second.close().unwrap();
    }

    #[test]
    fn a_directory_a_server_holds_says_how_to_let_it_go() {
        let dir = tempfile::tempdir().unwrap();
        let server = Store::open(dir.path(), Options::default()).unwrap();
        std::fs::create_dir(dir.path().join("server")).unwrap();
        std::fs::write(dir.path().join("server").join("SERVE"), "{}").unwrap();
        let error = Store::open(dir.path(), Options::default()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InUse, "{error}");
        assert!(error.to_string().contains("a tinystore server holds it"), "{error}");
        assert!(error.to_string().contains(&format!("tinystore stop {}", dir.path().display())), "{error}");
        server.close().unwrap();
    }

    #[test]
    fn a_missing_directory_is_created() {
        let parent = tempfile::tempdir().unwrap();
        let dir = parent.path().join("a").join("b");
        let store = Store::open(&dir, Options::default()).unwrap();
        assert!(dir.join("LOCK").is_file());
        store.close().unwrap();
    }

    // contract: BAK-04
    #[test]
    fn an_open_removes_the_snapshot_a_dead_backup_left_and_keeps_one_running() {
        let dir = tempfile::tempdir().unwrap();
        let (dead, running) = (dir.path().join(".snapshot-dead"), dir.path().join(".snapshot-running"));
        for snapshot in [&dead, &running] {
            std::fs::create_dir_all(snapshot.join("sql")).unwrap();
            std::fs::write(snapshot.join("sql").join("app.db"), "a copy").unwrap();
        }
        let backing_up = take_lock(&running).unwrap();
        let programs = dir.path().join(".snapshot-notes.txt");
        std::fs::write(&programs, "a file of the program's").unwrap();

        Store::open_beside(dir.path()).unwrap().close().unwrap();
        assert!(dead.join("sql").join("app.db").is_file(), "a guest removes nothing");
        let store = Store::open(dir.path(), Options::default()).unwrap();
        assert!(!dead.exists(), "the snapshot of a backup whose process died is gone");
        assert!(running.join("sql").join("app.db").is_file(), "a backup still running keeps its snapshot");
        assert!(programs.is_file(), "a snapshot's directory goes, and nothing else");
        store.close().unwrap();
        drop(backing_up);
    }

    // contract: BAK-02
    #[test]
    fn a_directory_a_restore_did_not_finish_in_opens_neither_held_nor_beside() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("kv.db"), "the part of a backup restored").unwrap();
        std::fs::write(dir.path().join(RESTORING), "").unwrap();
        let said = format!("store {}: {HALF_RESTORED}: invalid", dir.path().display());
        let held = Store::open(dir.path(), Options::default()).unwrap_err();
        assert_eq!((held.kind(), held.to_string()), (ErrorKind::Invalid, said.clone()));
        let beside = Store::open_beside(dir.path()).unwrap_err();
        assert_eq!((beside.kind(), beside.to_string()), (ErrorKind::Invalid, said));
        assert!(dir.path().join("kv.db").is_file(), "the part restored stays for whoever looks");
    }

    // contract: ERR-02, ERR-03
    #[test]
    fn a_directory_that_is_a_file_or_sits_under_one_is_invalid_naming_the_file() {
        let parent = tempfile::tempdir().unwrap();
        let file = parent.path().join("data");
        std::fs::write(&file, "not a directory").unwrap();
        let itself = Store::open(&file, Options::default()).unwrap_err();
        assert_eq!(itself.kind(), ErrorKind::Invalid, "{itself}");
        assert_eq!(itself.to_string(), format!("store {} is a file, not a directory: invalid", file.display()));

        let under = file.join("store");
        let below = Store::open(&under, Options::default()).unwrap_err();
        assert_eq!(below.kind(), ErrorKind::Invalid, "{below}");
        let said = format!("store {}: {} is a file, not a directory: invalid", under.display(), file.display());
        assert_eq!(below.to_string(), said);
    }

    #[test]
    fn engines_close_the_last_opened_first() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options::default()).unwrap();
        let closed = Arc::new(Mutex::new(Vec::new()));
        for name in ["kv", "jobs", "records"] {
            let engine = Recorder { name, closed: Arc::clone(&closed) };
            store.attach(Arc::new(engine)).unwrap();
        }
        store.close().unwrap();
        assert_eq!(*lock(&closed), ["records", "jobs", "kv"]);
    }

    // contract: STORE-03
    #[test]
    fn an_engine_attached_while_the_store_closes_is_refused_and_closed() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
        let closed = Arc::new(Mutex::new(Vec::new()));
        let late: Arc<dyn Engine> = Arc::new(Recorder { name: "late", closed: Arc::clone(&closed) });
        // Held, so that the attach waits for the list while the store closes:
        // one that read the store open before it waited would push onto the
        // list `close` took, and nothing would close its engine.
        let list = lock(&store.inner.engines);
        let attaching = {
            let store = store.clone();
            std::thread::spawn(move || store.attach(late))
        };
        std::thread::sleep(Duration::from_millis(100));
        let closing = {
            let store = store.clone();
            std::thread::spawn(move || store.close())
        };
        while !store.inner.closed.load(Ordering::SeqCst) {
            std::thread::yield_now();
        }
        drop(list);
        let attached = attaching.join().unwrap();
        closing.join().unwrap().unwrap();
        assert_eq!(attached.map_err(|error| error.kind()), Err(ErrorKind::Closed), "a late handle answers closed");
        assert_eq!(*lock(&closed), ["late"], "the engine opened late is closed once");
    }

    // contract: STORE-03
    // contract: JOB-11
    #[test]
    #[cfg(all(feature = "kv", feature = "jobs"))]
    fn a_close_waits_for_the_handlers_running_while_every_engine_they_write_is_open() {
        use std::sync::mpsc;
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
        // the queue opens before the bucket its handler writes, so kv closes first
        let mail = store.queue::<String>("mail").open().unwrap();
        let sent = store.bucket::<String>("sent").open().unwrap();
        let (started, handler_started) = mpsc::channel();
        let (go_on, handler_goes_on) = mpsc::channel::<()>();
        let handler_goes_on = Mutex::new(handler_goes_on);
        let wrote = Arc::new(Mutex::new(None));
        let written = Arc::clone(&wrote);
        let _worker = mail
            .work(move |id: String, _| -> Result<()> {
                started.send(()).unwrap();
                lock(&handler_goes_on).recv().unwrap();
                let result = sent.set(&id, &"sent".to_owned());
                *lock(&written) = Some(result.as_ref().map_err(Error::kind).copied());
                result
            })
            .unwrap();
        mail.id("m-1").add(&"m-1".to_owned()).unwrap();
        handler_started.recv_timeout(Duration::from_secs(10)).unwrap();

        let closing = {
            let store = store.clone();
            std::thread::spawn(move || store.close())
        };
        while store.claim("a-probe").is_ok() {
            std::thread::yield_now();
        }
        // time for a close that closes the engines first to reach kv.db
        std::thread::sleep(Duration::from_millis(100));
        go_on.send(()).unwrap();
        closing.join().unwrap().unwrap();
        assert_eq!(*lock(&wrote), Some(Ok(())), "the handler wrote while kv.db was open");

        let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
        let sent = store.bucket::<String>("sent").open().unwrap();
        assert_eq!(sent.get("m-1").unwrap().as_deref(), Some("sent"));
        let job = store.queue::<String>("mail").open().unwrap().get("m-1").unwrap();
        let state = job.map(|job| job.state);
        assert!(state.is_none_or(|state| state == crate::jobs::State::Done), "the mail is sent once: {state:?}");
        store.close().unwrap();
    }

    // contract: STORE-03
    #[test]
    #[cfg(all(feature = "kv", feature = "channels"))]
    fn a_close_waits_for_a_channels_handler_while_the_bucket_it_writes_is_open() {
        use std::sync::mpsc;
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
        let orders = store.channel::<String>("orders").open().unwrap();
        let seen = store.bucket::<String>("seen").open().unwrap();
        let (started, handler_started) = mpsc::channel();
        let (go_on, handler_goes_on) = mpsc::channel::<()>();
        let (wrote, written) = mpsc::channel();
        let _subscription = orders
            .subscribe(move |message| {
                started.send(()).unwrap();
                handler_goes_on.recv().unwrap();
                wrote.send(seen.set(&message.value, &"seen".to_owned()).map_err(|error| error.kind())).unwrap();
            })
            .unwrap();
        orders.publish(&"o-1".to_owned()).unwrap();
        handler_started.recv_timeout(Duration::from_secs(10)).unwrap();

        let closing = {
            let store = store.clone();
            std::thread::spawn(move || store.close())
        };
        while store.claim("a-probe").is_ok() {
            std::thread::yield_now();
        }
        std::thread::sleep(Duration::from_millis(100));
        go_on.send(()).unwrap();
        closing.join().unwrap().unwrap();
        assert_eq!(written.recv().unwrap(), Ok(()), "the handler wrote while kv.db was open");
    }

    #[test]
    fn a_file_is_claimed_by_one_engine_until_it_lets_go() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options::default()).unwrap();
        let claim = store.claim("kv.db").unwrap();
        assert_eq!(claim.path(), store.dir().join("kv.db"));
        assert_eq!(store.claim("kv.db").unwrap_err().kind(), ErrorKind::InUse);
        drop(claim);
        store.claim("kv.db").unwrap();
        store.close().unwrap();
    }

    // contract: STORE-04
    #[test]
    fn a_store_dropped_without_close_closes_its_engines_and_lets_go() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options::default()).unwrap();
        let closed = Arc::new(Mutex::new(Vec::new()));
        store.attach(Arc::new(Recorder { name: "kv", closed: Arc::clone(&closed) })).unwrap();
        let clone = store.clone();
        drop(store);
        assert!(lock(&closed).is_empty(), "a clone still holds it open");
        drop(clone);
        assert_eq!(*lock(&closed), ["kv"]);
        Store::open(dir.path(), Options::default()).unwrap().close().unwrap();
    }

    #[test]
    fn a_closed_store_opens_nothing_more() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path(), Options::default()).unwrap();
        store.close().unwrap();
        assert_eq!(store.claim("kv.db").unwrap_err().kind(), ErrorKind::Closed);
        assert_eq!(store.every("kv: expiry", Duration::from_secs(1), || Ok(())).unwrap_err().kind(), ErrorKind::Closed);
        store.close().unwrap();
    }

    #[test]
    fn the_store_reads_the_clock_it_was_given() {
        let dir = tempfile::tempdir().unwrap();
        let clock = Arc::new(TestClock::new(SystemTime::UNIX_EPOCH + Duration::from_secs(60)));
        let options = Options { clock: Some(clock.clone()), ..Options::default() };
        let store = Store::open(dir.path(), options).unwrap();
        clock.advance(Duration::from_secs(1));
        assert_eq!(crate::unix_millis(store.now()), 61_000);
        store.close().unwrap();
    }
}