tinystore 0.1.1

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
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, SealedIn};
use crate::engine::{Claim, Engine, 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>,
    /// 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,
}

/// 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,
            #[cfg(feature = "replication")]
            node: None,
            #[cfg(feature = "metrics")]
            self_metrics: None,
            #[cfg(feature = "metrics")]
            max_series: MAX_SERIES,
        }
    }
}

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);
        #[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);
        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(
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "records",
            feature = "metrics",
            feature = "replication",
            feature = "search",
            all(feature = "sql", feature = "async")
        )),
        expect(dead_code, reason = "a database's file holds its store for its guests, and sql alone has none")
    )]
    Weak<Inner>,
);

#[cfg(any(
    feature = "kv",
    feature = "jobs",
    feature = "sql",
    feature = "records",
    feature = "metrics",
    feature = "replication",
    all(feature = "search", feature = "async")
))]
impl WeakStore {
    #[cfg_attr(
        not(any(
            feature = "kv",
            feature = "jobs",
            feature = "records",
            feature = "metrics",
            feature = "replication",
            feature = "search",
            all(feature = "sql", feature = "async")
        )),
        expect(dead_code, reason = "a database's file holds its store for its guests, and sql alone has none")
    )]
    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>>>,
    /// 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",
            feature = "backup"
        )),
        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>,
    /// The key, once a handle needed it: a store that seals nothing reads no
    /// key and makes none.
    #[cfg(feature = "kv")]
    encryption_key: Mutex<Option<Arc<EncryptionKey>>>,
    /// 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,
    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)?;
        Self::open_with(dir, options, Some(lock))
    }

    /// 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())?;
        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(),
            #[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")]
            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,
            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> {
        let path = self.inner.dir.join(name);
        let probe = Some(self.inner.probe.for_file(crate::probe::label(name)));
        let config = crate::sqlite::Config { memory: Some(Arc::clone(&self.inner.memory)), probe, ..config };
        if self.inner.beside {
            if !path.exists() {
                return Err(Error::not_found(format!("{}: it holds no {name}", self.describe())));
            }
            return crate::sqlite::File::open_copy(path, 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 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",
            feature = "backup"
        )),
        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 key: the one 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<EncryptionKey>> {
        self.read_encryption_key(Some(sealed_in))
    }

    /// The store's encryption key, which is 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<EncryptionKey>> {
        self.read_encryption_key(None)
    }

    /// The key, 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<EncryptionKey>> {
        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 key = Arc::new(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)?,
        });
        *kept = Some(Arc::clone(&key));
        Ok(key)
    }

    /// 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",
                    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.
    pub fn close(&self) -> Result<()> {
        if crate::sqlite::in_a_transaction() {
            let why =
                "a close from inside a transaction would wait for the writer the transaction holds: close after it";
            return Err(Error::invalid(why).within(self.describe()));
        }
        self.inner.close()
    }

    #[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()))
    }

    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<()> {
        self.refuse_when_closed("an engine opening")?;
        lock(&self.inner.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<()> {
        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)),
    }
}

/// 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.
fn held_by(dir: &Path, what: String) -> String {
    if dir.join("server").join("SERVE").is_file() {
        let dir = dir.display();
        format!("{what}: a tinystore server holds it; connect to it, or stop it first with `tinystore stop {dir}`")
    } else {
        format!("{what}: another store holds it")
    }
}

#[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: 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
    // 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();
    }
}