tinystore 0.2.0-rc.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
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
use std::fmt;
use std::marker::PhantomData;
#[cfg(any(feature = "sql", feature = "wire"))]
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use rusqlite::Connection;

use super::cells::{self, Cell, MAX_VALUE};
use super::encrypted::Encrypted;
use super::engine::{Revision, next_version};
#[cfg(feature = "replication")]
use super::forward;
use super::key_call::KeyCall;
use super::path::Key;
use super::renewals::Renewal;
use super::scope::{Kind, Scope};
use super::value::{self, Raw, Value};
use crate::clock::{from_unix_millis, millis};
use crate::engine::Home;
#[cfg(any(feature = "sql", feature = "wire"))]
use crate::engine::SharedFile;
use crate::sqlite::Tx;
use crate::{Error, ErrorKind, Result, Store, unix_millis};

/// Keys a clear deletes in one transaction; a larger branch is marked cleared
/// and maintenance deletes it a batch at a time.
const CLEAR_BOUND: usize = 10_000;

/// Keys a page holds at most.
pub const PAGE_KEYS: usize = 1000;

/// An idle key is renewed once a thirtieth of its term has passed since it
/// last was, and before its read returns when it has less than a minute left.
const REFRESHES: i64 = 30;
const RENEW_AT_ONCE: i64 = 60_000;

/// A bucket being opened: its name, its type, how its keys expire, whether
/// its values are encrypted.
#[must_use = "a bucket opens with open()"]
pub struct BucketBuilder<V> {
    home: Home,
    name: String,
    expiry: Expiry,
    encrypted: bool,
    _value: PhantomData<fn() -> V>,
}

/// How a bucket's keys expire when a write does not say.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Expiry {
    Never,
    /// A span after the key was written.
    Ttl(Duration),
    /// A span after the key was last read or written.
    Idle(Duration),
}

impl Store {
    /// A bucket of values of type `V` by key, in the store's kv.db; the engine
    /// opens with the first handle.
    pub fn bucket<V: Value>(&self, name: &str) -> BucketBuilder<V> {
        BucketBuilder::new(Home::Store(self.clone()), name)
    }
}

impl<V: Value> BucketBuilder<V> {
    /// A bucket kept where `home` says, which a write passed on names.
    #[cfg(feature = "replication")]
    pub(crate) fn lent(home: Home, name: &str) -> Self {
        BucketBuilder::new(home, name)
    }

    fn new(home: Home, name: &str) -> Self {
        BucketBuilder { home, name: name.to_owned(), expiry: Expiry::Never, encrypted: false, _value: PhantomData }
    }

    /// A bucket kept in a file another engine lends, a database's.
    #[cfg(any(feature = "sql", feature = "wire"))]
    pub(crate) fn in_file(shared: Arc<SharedFile>, name: &str) -> Self {
        BucketBuilder::new(Home::Shared(shared), name)
    }
}

impl<V: Value> BucketBuilder<V> {
    /// Keys expire this long after they are written, unless a write says
    /// otherwise.
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.expiry = Expiry::Ttl(ttl);
        self
    }

    /// Keys expire this long after they were last read or written.
    pub fn idle(mut self, idle: Duration) -> Self {
        self.expiry = Expiry::Idle(idle);
        self
    }

    /// Keeps every value sealed with the store's encryption key, as a password
    /// or a token is kept: the file holds what nobody reads without the key,
    /// and a value copied under another key does not open. A key is not
    /// sealed, so a secret is a value and never a key. A name keeps whether
    /// it is encrypted: it opens the same way every time.
    ///
    /// ```no_run
    /// # fn main() -> tinystore::Result<()> {
    /// # let store = tinystore::Store::open("data", Default::default())?;
    /// let passwords = store.bucket::<String>("source-passwords").encrypted().open()?;
    /// passwords.set("source-42", &"hunter2".to_owned())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypted(mut self) -> Self {
        self.encrypted = true;
        self
    }

    pub fn open(self) -> Result<Bucket<V>> {
        check_expiry(self.expiry).map_err(|error| error.within(format!("kv bucket {}", self.name)))?;
        let kind = if self.encrypted { Kind::Encrypted } else { Kind::Values };
        let scope = Scope::open(&self.home, &self.name, kind)?;
        let encrypted = self.encrypted.then(|| Encrypted::of(&scope)).transpose()?;
        Ok(Bucket { encrypted, ..Bucket::new(scope, self.expiry) })
    }
}

/// Values of one type by key. A handle is cheap to clone and to keep; `under`
/// gives the same bucket seen from a branch.
pub struct Bucket<V> {
    pub(crate) scope: Scope,
    expiry: Expiry,
    /// What seals its rows, when the bucket is encrypted.
    encrypted: Option<Encrypted>,
    _value: PhantomData<fn() -> V>,
}

/// A key's value with what a conditional write needs.
#[derive(Clone, Debug, PartialEq)]
pub struct Entry<V> {
    pub key: String,
    pub value: V,
    pub version: Version,
    pub expires_at: Option<SystemTime>,
}

/// The revision of kv.db that wrote a value. It never repeats, across deletes,
/// expiry and restarts, and it compares only for equality.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Version(i64);

impl Version {
    #[cfg(any(feature = "wire", feature = "replication"))]
    pub(crate) fn new(revision: i64) -> Version {
        Version(revision)
    }

    #[cfg(any(feature = "wire", feature = "replication"))]
    pub(crate) fn revision(self) -> i64 {
        self.0
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl std::str::FromStr for Version {
    type Err = Error;

    fn from_str(text: &str) -> Result<Self> {
        text.parse().map(Version).map_err(|_| Error::invalid(format!("{text:?} is not a version")))
    }
}

/// One page of a branch's keys, in the byte order of their text.
#[derive(Clone, Debug, PartialEq)]
pub struct Page<V> {
    pub entries: Vec<Entry<V>>,
    /// The key the next page starts after, when there is more.
    pub next: Option<String>,
}

/// What a call on one key asks beside its key and value: a new expiry, and a
/// version the key must still be at.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct WriteOptions {
    pub(crate) expires: Option<Expires>,
    pub(crate) if_version: Option<Version>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Expires {
    In(Duration),
    At(SystemTime),
}

impl WriteOptions {
    pub(crate) fn ttl(mut self, ttl: Duration) -> Self {
        self.expires = Some(Expires::In(ttl));
        self
    }

    pub(crate) fn expires_at(mut self, time: SystemTime) -> Self {
        self.expires = Some(Expires::At(time));
        self
    }

    pub(crate) fn if_version(mut self, version: Version) -> Self {
        self.if_version = Some(version);
        self
    }

    fn expires(self, now: i64) -> Option<i64> {
        self.expires.map(|expires| match expires {
            Expires::In(span) => now.saturating_add(millis(span)),
            Expires::At(time) => unix_millis(time),
        })
    }
}

/// How a write treats the key it finds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Put {
    Always,
    OnlyNew,
}

/// What a write left: whether it wrote, and the version and expiry the key
/// has now, its own when a create found a live key there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Stamp {
    pub(crate) written: bool,
    pub(crate) version: Version,
    pub(crate) expires: Option<i64>,
}

/// A write as a closure the group commit or a transaction runs.
pub(crate) trait Work<T>: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static {}

impl<T, F: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static> Work<T> for F {}

impl<V: Value> Bucket<V> {
    /// Writes `value` under `key`. A key that is there keeps its ttl; a new one
    /// takes the bucket's, and an idle key lives its span from the write.
    pub fn set(&self, key: impl Key, value: &V) -> Result<()> {
        self.put(&key.text(), value, WriteOptions::default(), Put::Always).map(|_| ())
    }

    /// Writes `value` only when `key` is not there, and says whether it did; an
    /// expired key is not there. A key that is there is `false`, never an error.
    pub fn create(&self, key: impl Key, value: &V) -> Result<bool> {
        self.put(&key.text(), value, WriteOptions::default(), Put::OnlyNew)
    }

    /// A call on `key` with what it asks beside its value, a new expiry or a
    /// version the key must still be at, run by its last step:
    /// `sessions.key(&token).if_version(seen).set(&next)`.
    pub fn key(&self, key: impl Key) -> KeyCall<'_, V> {
        KeyCall::new(self, None, key.text().into_owned())
    }

    pub fn get(&self, key: impl Key) -> Result<Option<V>> {
        Ok(self.entry(key)?.map(|entry| entry.value))
    }

    /// The value with its version and expiry.
    pub fn entry(&self, key: impl Key) -> Result<Option<Entry<V>>> {
        let key = key.text();
        let found = self.read_cell(&key)?;
        found.map(|cell| self.entry_of(&key, cell)).transpose()
    }

    /// Reads `key` and removes it in one commit: of two callers taking the same
    /// key, one gets the value. A value that no longer reads as the bucket's
    /// type is `Corrupt`, and stays.
    pub fn take(&self, key: impl Key) -> Result<Option<V>> {
        let key = key.text();
        #[cfg(feature = "replication")]
        if self.is_copy() {
            let cell = self.take_at_home(&key, WriteOptions::default())?;
            return cell.map(|cell| decode::<V>(&cell.raw)).transpose();
        }
        let work = self.take_work(&key, WriteOptions::default())?;
        self.scope.write(&key, 0, work)
    }

    /// One page of this branch's own keys, after `after` when it continues
    /// another; `limit` keys at most, one at least, and never more than
    /// [`PAGE_KEYS`].
    pub fn list(&self, limit: usize, after: Option<&str>) -> Result<Page<V>> {
        let limit = limit.clamp(1, PAGE_KEYS);
        let rows = self
            .scope
            .kv
            .file()
            .read(|connection| self.page_rows(connection, limit, after))
            .map_err(|error| error.within(self.scope.shown_branch()))?;
        self.page_of(rows, limit)
    }

    /// Every key of this branch, a page at a time. No snapshot is held between
    /// pages, so a slow loop keeps no reader, and a key written meanwhile may
    /// or may not be met.
    pub fn all(&self) -> All<V> {
        All { bucket: self.clone(), page: Vec::new().into_iter(), next: None, done: false }
    }

    fn put(&self, key: &str, value: &V, options: WriteOptions, put: Put) -> Result<bool> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            let call = forward::Call::Put { raw: self.encode(key, value)?, put, options };
            return Ok(forward::stamp(&self.pass_on(key, call)?)?.written);
        }
        let (bytes, work) = self.put_work(key, self.encode(key, value)?, options, put)?;
        Ok(self.scope.write(key, bytes, work)?.written)
    }

    pub(crate) fn encode(&self, key: &str, value: &V) -> Result<Raw> {
        value::encode(value).map_err(|mismatch| {
            Error::invalid(format!("a value it cannot keep: {mismatch}")).within(self.scope.shown_key(key))
        })
    }

    /// `take` with `options`, without waiting: `done` gets the value once the
    /// commit ends. A value that no longer reads as `V` fails it, and stays.
    #[cfg(feature = "async")]
    pub(crate) fn take_then(
        &self,
        key: &str,
        options: WriteOptions,
        done: impl FnOnce(Result<Option<V>>) + Send + 'static,
    ) {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            let decoded = |cell: Result<Option<Cell>>| cell?.map(|cell| decode::<V>(&cell.raw)).transpose();
            return self.take_cell_then(key, options, move |cell| done(decoded(cell)));
        }
        self.scope.submit_made(key, 0, self.take_work(key, options), done);
    }

    pub(crate) fn take_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<V>> + use<V>> {
        let take = self.take_cell_work(key, options)?;
        Ok(move |tx: &Tx<'_>, revision: &Revision| {
            let cell = take(tx, revision)?;
            cell.map(|cell| decode::<V>(&cell.raw)).transpose()
        })
    }

    pub(crate) fn entry_of(&self, key: &str, cell: Cell) -> Result<Entry<V>> {
        Ok(Entry {
            key: key.to_owned(),
            value: decode(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)))?,
            version: Version(cell.version),
            expires_at: cell.expires.map(from_unix_millis),
        })
    }

    /// Entries of the rows a page read, refused when one is not this branch's.
    pub(crate) fn page_of(&self, rows: Vec<(Vec<u8>, Cell)>, limit: usize) -> Result<Page<V>> {
        let branch = self.scope.branch()?;
        let full = rows.len() == limit;
        let mut entries = Vec::with_capacity(rows.len());
        for (path, cell) in rows {
            let key = branch.key_of(&path)?;
            entries.push(self.entry_of(&key, cell)?);
        }
        let next = if full { entries.last().map(|entry| entry.key.clone()) } else { None };
        Ok(Page { entries, next })
    }
}

/// What a bucket does whatever its type: the calls that make no value, and
/// the row-level ones the wire's handles use.
impl<V> Bucket<V> {
    pub(crate) fn new(scope: Scope, expiry: Expiry) -> Bucket<V> {
        Bucket { scope, expiry, encrypted: None, _value: PhantomData }
    }

    /// The same bucket seen from the branch `owner` names under this one:
    /// `sessions.under(user_id).clear()` signs a user out everywhere.
    pub fn under(&self, owner: impl Key) -> Bucket<V> {
        Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.under(owner), self.expiry) }
    }

    pub fn has(&self, key: impl Key) -> Result<bool> {
        let key = key.text();
        if matches!(self.expiry, Expiry::Idle(_)) {
            return Ok(self.read_cell(&key)?.is_some());
        }
        let (id, path, now) = (self.scope.id, self.scope.path(&key)?, self.scope.now());
        self.scope.read(&key, |connection| cells::has(connection, id, &path, now))
    }

    /// Removes `key` and says whether a live key was there.
    pub fn delete(&self, key: impl Key) -> Result<bool> {
        self.remove(&key.text(), WriteOptions::default())
    }

    /// Gives a live key a new expiry, `ttl` from now, as Redis's EXPIRE does,
    /// keeping its value and version; says whether the key was there.
    pub fn expire(&self, key: impl Key, ttl: Duration) -> Result<bool> {
        self.expire_as(&key.text(), WriteOptions::default().ttl(ttl))
    }

    /// Gives a live key the expiry `options` names, at the version they name.
    pub(crate) fn expire_as(&self, key: &str, options: WriteOptions) -> Result<bool> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return forward::found(&self.pass_on(key, forward::Call::Expire(options))?);
        }
        let work = self.expire_work(key, options)?;
        self.scope.write(key, 0, work)
    }

    /// Removes every key of this branch and of the branches under it, at once
    /// for every reader, however many there are.
    pub fn clear(&self) -> Result<()> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self.pass_on("", forward::Call::Clear).map(drop);
        }
        let work = clear_work(&self.scope)?;
        let revision = self.scope.kv.revision();
        let shown = self.scope.shown_branch();
        self.scope.kv.file().write(0, move |tx| work(tx, &revision)).map_err(|error| error.within(shown))
    }

    /// `clear` without waiting for its commit.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn clear_then(&self, done: impl FnOnce(Result<()>) + Send + 'static) {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self.pass_on_then("", forward::Call::Clear, |_| Ok(()), done);
        }
        let work = match clear_work(&self.scope) {
            Ok(work) => work,
            Err(error) => return done(Err(error)),
        };
        let (revision, shown) = (self.scope.kv.revision(), self.scope.shown_branch());
        let answered = move |cleared: Result<()>| done(cleared.map_err(|error| error.within(shown)));
        self.scope.kv.file().submit(0, move |tx| work(tx, &revision), answered);
    }

    /// Writes a row's value under `key`, as `put` says, and stamps it.
    #[cfg(any(feature = "wire", feature = "replication"))]
    pub(crate) fn put_raw(&self, key: &str, raw: Raw, options: WriteOptions, put: Put) -> Result<Stamp> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self
                .pass_on(key, forward::Call::Put { raw, put, options })
                .and_then(|bytes| forward::stamp(&bytes));
        }
        let (bytes, work) = self.put_work(key, raw, options, put)?;
        self.scope.write(key, bytes, work)
    }

    /// `put_raw` without waiting: `done` gets the stamp once the commit ends.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn put_raw_then(
        &self,
        key: &str,
        (raw, options, put): (Raw, WriteOptions, Put),
        done: impl FnOnce(Result<Stamp>) + Send + 'static,
    ) {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self.pass_on_then(key, forward::Call::Put { raw, put, options }, forward::stamp, done);
        }
        match self.put_work(key, raw, options, put) {
            Ok((bytes, work)) => self.scope.submit(key, bytes, work, done),
            Err(error) => done(Err(error)),
        }
    }

    /// The write a put commits, and the bytes it adds to its commit.
    pub(crate) fn put_work(
        &self,
        key: &str,
        raw: Raw,
        options: WriteOptions,
        put: Put,
    ) -> Result<(usize, impl Work<Stamp> + use<V>)> {
        self.put_work_as(key, raw, options, put, true)
    }

    /// A put's write, its value sealed first when `seal` says and the bucket
    /// is encrypted, or written as it was sealed already.
    fn put_work_as(
        &self,
        key: &str,
        raw: Raw,
        options: WriteOptions,
        put: Put,
        seal: bool,
    ) -> Result<(usize, impl Work<Stamp> + use<V>)> {
        if raw.len() > MAX_VALUE {
            let too_large = Error::limit(format!("a value of {} bytes, over {MAX_VALUE}", raw.len()));
            return Err(too_large.within(self.scope.shown_key(key)));
        }
        let now = self.scope.now();
        let path = self.scope.path(key)?;
        let raw =
            if seal { self.kept(&path, raw).map_err(|error| error.within(self.scope.shown_key(key)))? } else { raw };
        let bytes = raw.len();
        let cell = PutCell {
            id: self.scope.id,
            path,
            raw,
            now,
            put,
            if_version: options.if_version,
            given: options.expires(now),
            default: self.default_expires(now),
            // a write is a use of an idle key, which lives on from it; a key with a ttl keeps its own
            keeps_its_expiry: !matches!(self.expiry, Expiry::Idle(_)),
        };
        let encrypted = self.encrypted.clone();
        let work = move |tx: &Tx<'_>, revision: &Revision| {
            if let Some(encrypted) = &encrypted {
                encrypted.claim(tx)?;
            }
            cell.write(tx, revision)
        };
        Ok((bytes, work))
    }

    /// Removes a live key, at the version asked when one is, and says whether
    /// one was there.
    pub(crate) fn remove(&self, key: &str, options: WriteOptions) -> Result<bool> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return forward::found(&self.pass_on(key, forward::Call::Remove(options))?);
        }
        let work = self.remove_work(key, options)?;
        self.scope.write(key, 0, work)
    }

    /// `remove` without waiting: `done` hears once the commit ends.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn remove_then(
        &self,
        key: &str,
        options: WriteOptions,
        done: impl FnOnce(Result<bool>) + Send + 'static,
    ) {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self.pass_on_then(key, forward::Call::Remove(options), forward::found, done);
        }
        self.scope.submit_made(key, 0, self.remove_work(key, options), done);
    }

    /// `expire_as` without waiting: `done` hears once the commit ends.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn expire_then(
        &self,
        key: &str,
        options: WriteOptions,
        done: impl FnOnce(Result<bool>) + Send + 'static,
    ) {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self.pass_on_then(key, forward::Call::Expire(options), forward::found, done);
        }
        self.scope.submit_made(key, 0, self.expire_work(key, options), done);
    }

    /// The delete of a key. It reads no value, so a key whose value no longer
    /// opens, sealed with a key the store has lost, can still be deleted.
    pub(crate) fn remove_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
        let now = self.scope.now();
        let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
        Ok(move |tx: &Tx<'_>, _: &Revision| {
            let Some(found) = live_at(tx, id, &path, now, if_version)? else {
                return Ok(false);
            };
            cells::remove(tx, id, &path, found.spill)?;
            Ok(true)
        })
    }

    /// `take_cell_work` without waiting: `done` gets the cell once the commit
    /// ends. The async API takes through it on a copy alone.
    #[cfg(any(feature = "wire", all(feature = "async", feature = "replication")))]
    pub(crate) fn take_cell_then(
        &self,
        key: &str,
        options: WriteOptions,
        done: impl FnOnce(Result<Option<Cell>>) + Send + 'static,
    ) {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            match self.unsealer(key) {
                Ok(read) => self.pass_on_then(key, forward::Call::Take(options), read, done),
                Err(error) => done(Err(error)),
            }
            return;
        }
        self.scope.submit_made(key, 0, self.take_cell_work(key, options), done);
    }

    /// The take of a key: its delete, which hands back the cell it removed. A
    /// cell that does not open fails the take, and stays.
    pub(crate) fn take_cell_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<Cell>> + use<V>> {
        let now = self.scope.now();
        let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
        let encrypted = self.encrypted.clone();
        Ok(move |tx: &Tx<'_>, _: &Revision| {
            let Some(found) = live_at(tx, id, &path, now, if_version)? else {
                return Ok(None);
            };
            let cell = cells::live(tx, id, &path, now)?;
            cells::remove(tx, id, &path, found.spill)?;
            cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose()
        })
    }

    pub(crate) fn expire_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
        let now = self.scope.now();
        let expires = options
            .expires(now)
            .ok_or_else(|| Error::invalid("an expiry needs a ttl or a time").within(self.scope.shown_key(key)))?;
        let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
        Ok(move |tx: &Tx<'_>, _: &Revision| {
            if live_at(tx, id, &path, now, if_version)?.is_none() {
                return Ok(false);
            }
            cells::set_expires(tx, id, &path, Some(expires))?;
            Ok(true)
        })
    }

    /// Reads a live cell on a reader, renewing an idle key when it is due.
    pub(crate) fn read_cell(&self, key: &str) -> Result<Option<Cell>> {
        let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
        let read = |connection: &Connection| {
            let found = cells::live(connection, id, &path, now)?;
            found.map(|cell| opened(self.encrypted.as_ref(), &path, cell)).transpose()
        };
        let found = self.scope.read(key, read)?;
        Ok(found.map(|cell| self.renew(key, path, cell, now)))
    }

    /// Reads a live cell inside a transaction, renewing an idle key in it.
    pub(crate) fn read_cell_in(&self, tx: &Tx<'_>, key: &str) -> Result<Option<Cell>> {
        let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
        let Some(cell) = cells::live(tx, id, &path, now)? else {
            return Ok(None);
        };
        let mut cell = opened(self.encrypted.as_ref(), &path, cell)?;
        if let Some(renewal) = self.renewal_due(&cell, now)
            && cells::renew(tx, id, &path, (renewal.version, renewal.seen), renewal.until)?
        {
            cell.expires = Some(renewal.until);
        }
        Ok(Some(cell))
    }

    /// One page of this branch's own rows, each with its key, read in one
    /// snapshot; the wire's pages, whose values stay rows.
    #[cfg(feature = "wire")]
    pub(crate) fn list_rows(&self, limit: usize, after: Option<&str>) -> Result<Vec<(String, Cell)>> {
        let limit = limit.clamp(1, PAGE_KEYS);
        let rows = self
            .scope
            .kv
            .file()
            .read(|connection| self.page_rows(connection, limit, after))
            .map_err(|error| error.within(self.scope.shown_branch()))?;
        self.keyed(rows)
    }

    /// Rows of this branch by path, each with its key instead.
    #[cfg(feature = "wire")]
    pub(crate) fn keyed(&self, rows: Vec<(Vec<u8>, Cell)>) -> Result<Vec<(String, Cell)>> {
        let branch = self.scope.branch()?;
        rows.into_iter().map(|(path, cell)| Ok((branch.key_of(&path)?, cell))).collect()
    }

    /// A page of this branch's own rows on `connection`, by path.
    pub(crate) fn page_rows(
        &self,
        connection: &Connection,
        limit: usize,
        after: Option<&str>,
    ) -> Result<Vec<(Vec<u8>, Cell)>> {
        let (from, past) = self.scope.branch()?.own_keys_after(after);
        let rows = cells::page(connection, self.scope.id, (&from, &past), self.scope.now(), limit)?;
        let read = |(path, cell): (Vec<u8>, Cell)| {
            let cell = opened(self.encrypted.as_ref(), &path, cell)?;
            Ok((path, cell))
        };
        rows.into_iter().map(read).collect()
    }

    /// The row as the file keeps it: sealed when the bucket is encrypted.
    fn kept(&self, path: &[u8], raw: Raw) -> Result<Raw> {
        match &self.encrypted {
            Some(encrypted) => encrypted.seal(path, &raw),
            None => Ok(raw),
        }
    }

    /// Renews a due idle key: with the next flush of renewals, or before the
    /// read returns when the key has less than a minute left. A renewal that
    /// cannot be written now waits for the flush. A copy's renewals are its
    /// home's to write, and go there.
    fn renew(&self, key: &str, path: Vec<u8>, mut cell: Cell, now: i64) -> Cell {
        let Some(renewal) = self.renewal_due(&cell, now) else {
            return cell;
        };
        #[cfg(feature = "replication")]
        if self.is_copy() {
            if self.renew_at_home(key, path, renewal, now) {
                cell.expires = Some(renewal.until);
            }
            return cell;
        }
        let renewals = self.scope.kv.renewals();
        if renewal.seen - now >= RENEW_AT_ONCE {
            renewals.ask(self.scope.id, path, renewal);
            return cell;
        }
        let (id, written_path) = (self.scope.id, path.clone());
        let at_once = move |tx: &Tx<'_>, _: &Revision| {
            cells::renew(tx, id, &written_path, (renewal.version, renewal.seen), renewal.until)
        };
        match self.scope.write(key, 0, at_once) {
            Ok(true) => cell.expires = Some(renewal.until),
            Ok(false) => {}
            // a point read refused its write here runs again on the pool, which renews the key
            Err(_) if crate::polled::waits_refused() => {}
            Err(_) => renewals.ask(self.scope.id, path, renewal),
        }
        cell
    }

    fn renewal_due(&self, cell: &Cell, now: i64) -> Option<Renewal> {
        let Expiry::Idle(term) = self.expiry else {
            return None;
        };
        let (term, expires) = (millis(term), cell.expires?);
        if expires - now > term - term / REFRESHES {
            return None;
        }
        Some(Renewal { version: cell.version, seen: expires, until: now.saturating_add(term) })
    }

    fn default_expires(&self, now: i64) -> Option<i64> {
        match self.expiry {
            Expiry::Never => None,
            Expiry::Ttl(span) | Expiry::Idle(span) => Some(now.saturating_add(millis(span))),
        }
    }
}

impl Bucket<()> {
    /// Adds `key` to a bucket of keys alone, a set, and says whether it was new:
    /// `seen.add(event_id)` is false for an event already handled.
    pub fn add(&self, key: impl Key) -> Result<bool> {
        self.create(key, &())
    }
}

/// A write on a copy of the bucket's file, which its home takes.
#[cfg(feature = "replication")]
impl<V> Bucket<V> {
    pub(crate) fn is_copy(&self) -> bool {
        self.scope.kv.file().is_copy()
    }

    /// Passes a call on `key` to the home of the copy, and gives its answer's
    /// bytes once this copy holds the commit that made it.
    pub(crate) fn pass_on(&self, key: &str, call: forward::Call) -> Result<Vec<u8>> {
        let shown = || self.scope.shown_key(key);
        let call = self.sealed(key, call).map_err(|error| error.within(shown()))?;
        self.scope.pass_on(&self.handle(), key, &call)
    }

    /// The handle a call on this bucket is made on at its home.
    fn handle(&self) -> forward::Handle {
        let name = self.scope.name().to_owned();
        let database = self.scope.kv.lent_by().and_then(crate::replication::database_of).map(str::to_owned);
        forward::Handle::Bucket { name, expiry: self.expiry, encrypted: self.encrypted.is_some(), database }
    }

    /// Asks the home of the copy for a due renewal, as the home's own reads
    /// renew a key, and says whether the home renewed it before this returned:
    /// with the next pass of renewals, or at once when the key has less than a
    /// minute left. That waits for the home's answer, a few seconds at most,
    /// and neither for a link nor for this copy to hold the renewal. A store
    /// opened beside the process that holds it passes nothing on.
    fn renew_at_home(&self, key: &str, path: Vec<u8>, renewal: Renewal, now: i64) -> bool {
        let (Ok(store), Ok(branch)) = (self.scope.kv.store(), self.scope.branch()) else { return false };
        if store.is_beside() {
            return false;
        }
        let request = forward::encode(&self.handle(), branch.owners(), key, &forward::Call::Renew(renewal));
        let renewals = self.scope.kv.renewals();
        if renewal.seen - now >= RENEW_AT_ONCE {
            renewals.pass(self.scope.id, path, renewal, request);
            return false;
        }
        renewals.pass_now(&store, (self.scope.id, path), renewal, request) == Some(true)
    }

    /// Renews `key` for a read on a copy, as this node's own reads do: with
    /// the next flush, or at once when it has less than a minute left; says
    /// whether it renewed it now. A node that holds a copy passes it on as its
    /// own reads do.
    pub(crate) fn renew_as(&self, key: &str, renewal: Renewal) -> Result<bool> {
        let (id, path) = (self.scope.id, self.scope.path(key)?);
        if self.is_copy() {
            return Ok(self.renew_at_home(key, path, renewal, self.scope.now()));
        }
        if renewal.seen - self.scope.now() >= RENEW_AT_ONCE {
            self.scope.kv.renewals().ask(id, path, renewal);
            return Ok(false);
        }
        self.scope.write(key, 0, move |tx: &Tx<'_>, _: &Revision| {
            cells::renew(tx, id, &path, (renewal.version, renewal.seen), renewal.until)
        })
    }

    /// The call as it crosses the link: an encrypted bucket's value sealed
    /// here, and a take asking for the value sealed on its way back.
    fn sealed(&self, key: &str, call: forward::Call) -> Result<forward::Call> {
        let Some(encrypted) = &self.encrypted else {
            return Ok(call);
        };
        match call {
            forward::Call::Put { raw, put, options } => {
                let raw = encrypted.seal(&self.scope.path(key)?, &raw)?;
                Ok(forward::Call::PutSealed { raw, key_id: encrypted.key_id(), put, options })
            }
            forward::Call::Take(options) => Ok(forward::Call::TakeSealed { options, key_id: encrypted.key_id() }),
            call => Ok(call),
        }
    }

    /// Takes a key at the home of the copy: an encrypted bucket's value comes
    /// back sealed and opens here.
    pub(crate) fn take_at_home(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
        let answer = self.pass_on(key, forward::Call::Take(options))?;
        self.unsealer(key)?(&answer)
    }

    /// What reads a take's answer from the home: its cell, opened with the
    /// bucket's key where it is encrypted.
    fn unsealer(&self, key: &str) -> Result<impl FnOnce(&[u8]) -> Result<Option<Cell>> + Send + 'static + use<V>> {
        let (encrypted, path, shown) = (self.encrypted.clone(), self.scope.path(key)?, self.scope.shown_key(key));
        Ok(move |answer: &[u8]| {
            let cell = forward::cell(answer)?;
            cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose().map_err(|error| error.within(shown))
        })
    }

    /// Takes a key for a copy that shares this store's key, `key_id`, its
    /// value sealed again for the way back.
    pub(crate) fn take_sealed(&self, key: &str, options: WriteOptions, key_id: &str) -> Result<Option<Cell>> {
        let encrypted = self.shared_key(key, key_id)?;
        if self.is_copy() {
            let call = forward::Call::TakeSealed { options, key_id: key_id.to_owned() };
            return forward::cell(&self.pass_on(key, call)?);
        }
        let path = self.scope.path(key)?;
        let taken = self.scope.write(key, 0, self.take_cell_work(key, options)?)?;
        let seal = |mut cell: Cell| -> Result<Cell> {
            cell.raw = encrypted.seal(&path, &cell.raw)?;
            Ok(cell)
        };
        taken.map(seal).transpose().map_err(|error| error.within(self.scope.shown_key(key)))
    }

    /// This bucket's key, which a copy sealed with `key_id`: a copy and its
    /// home share one.
    fn shared_key(&self, key: &str, key_id: &str) -> Result<&Encrypted> {
        let Some(encrypted) = &self.encrypted else {
            return Err(
                Error::invalid("a sealed value for a bucket that is not encrypted").within(self.scope.shown_key(key))
            );
        };
        if encrypted.key_id() != key_id {
            return Err(Error::invalid(format!(
                "a value sealed with the key {key_id}, and this store's is {}: a copy and its home share one key",
                encrypted.key_id()
            ))
            .within(self.scope.shown_key(key)));
        }
        Ok(encrypted)
    }

    /// Writes a value a copy sealed with `key_id`, which must be this store's
    /// key for the bucket, as it is.
    pub(crate) fn put_sealed(
        &self,
        key: &str,
        raw: Raw,
        key_id: &str,
        options: WriteOptions,
        put: Put,
    ) -> Result<Stamp> {
        self.shared_key(key, key_id)?;
        let (bytes, work) = self.put_work_as(key, raw, options, put, false)?;
        self.scope.write(key, bytes, work)
    }

    /// Claims a once's key at the home of the copy these answers are kept in.
    pub(crate) fn once_claim(&self, key: &str) -> Result<forward::Claimed> {
        forward::claimed(&self.pass_on_once(key, &forward::Call::OnceClaim)?)
    }

    /// Keeps at the home what a run it handed over answered.
    pub(crate) fn once_keep(&self, key: &str, token: u64, answer: Option<Raw>) -> Result<()> {
        self.pass_on_once(key, &forward::Call::OnceKeep { token, answer }).map(drop)
    }

    fn pass_on_once(&self, key: &str, call: &forward::Call) -> Result<Vec<u8>> {
        let shown = || self.scope.shown_key(key);
        let keep = match self.expiry {
            Expiry::Ttl(keep) => crate::clock::millis(keep) as u64,
            _ => return Err(Error::internal("once's answers kept for no span").within(shown())),
        };
        let handle = forward::Handle::Once { name: self.scope.name().to_owned(), keep };
        self.scope.pass_on(&handle, key, call).map_err(|error| error.within(shown()))
    }

    /// Takes a key's cell, at the home where the bucket's file is a copy.
    pub(crate) fn take_cell(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
        if self.is_copy() {
            return self.take_at_home(key, options);
        }
        let work = self.take_cell_work(key, options)?;
        self.scope.write(key, 0, work)
    }

    /// `pass_on` without waiting, on a thread of its own: `done` gets what
    /// `read` makes of the answer.
    #[cfg(any(feature = "wire", feature = "async"))]
    fn pass_on_then<T: Send + 'static>(
        &self,
        key: &str,
        call: forward::Call,
        read: impl FnOnce(&[u8]) -> Result<T> + Send + 'static,
        done: impl FnOnce(Result<T>) + Send + 'static,
    ) {
        let (bucket, key) = (self.untyped(), key.to_owned());
        std::thread::spawn(move || done(bucket.pass_on(&key, call).and_then(|bytes| read(&bytes))));
    }
}

impl<V> Bucket<V> {
    /// The same bucket as rows, whose calls make no value of `V`.
    #[cfg(any(all(feature = "wire", feature = "replication"), feature = "async"))]
    pub(crate) fn untyped(&self) -> Bucket<()> {
        Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
    }
}

impl<V> Clone for Bucket<V> {
    fn clone(&self) -> Self {
        Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
    }
}

impl<V> fmt::Debug for Bucket<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Bucket({:?})", self.scope)
    }
}

impl<V> fmt::Debug for BucketBuilder<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "BucketBuilder({})", self.name)
    }
}

/// Every key of a branch, a page at a time.
pub struct All<V> {
    bucket: Bucket<V>,
    page: std::vec::IntoIter<Entry<V>>,
    next: Option<String>,
    done: bool,
}

impl<V: Value> Iterator for All<V> {
    type Item = Result<Entry<V>>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(entry) = self.page.next() {
                return Some(Ok(entry));
            }
            if self.done {
                return None;
            }
            match self.bucket.list(PAGE_KEYS, self.next.as_deref()) {
                Ok(page) => {
                    self.done = page.next.is_none();
                    self.next = page.next;
                    self.page = page.entries.into_iter();
                }
                Err(error) => {
                    self.done = true;
                    return Some(Err(error));
                }
            }
        }
    }
}

impl<V> fmt::Debug for All<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "All({:?})", self.bucket.scope)
    }
}

/// The clear of a scope's branch: every key under it deleted when they are few,
/// else the branch marked cleared at a new version, which hides them at once.
pub(crate) fn clear_work(scope: &Scope) -> Result<impl Work<()> + use<>> {
    let branch = scope.branch()?;
    let (id, prefix, everything) = (scope.id, branch.prefix().to_vec(), branch.everything());
    Ok(move |tx: &Tx<'_>, revision: &Revision| {
        // a bucket cleared whole holds no value of any key, and takes the key of its next write
        if prefix.is_empty() {
            cells::keep_bucket_key(tx, id, None)?;
        }
        if cells::delete_under(tx, id, (&everything.0, &everything.1), CLEAR_BOUND)? {
            return Ok(());
        }
        let cleared = next_version(revision, tx)?;
        cells::mark_cleared(tx, id, &prefix, cleared)
    })
}

/// A cell of the file as a caller reads it: opened when its bucket is
/// encrypted.
fn opened(encrypted: Option<&Encrypted>, path: &[u8], mut cell: Cell) -> Result<Cell> {
    if let Some(encrypted) = encrypted {
        cell.raw = encrypted.open(path, &cell.raw)?;
    }
    Ok(cell)
}

/// A row read back as `V`; a row that is not one is corrupt.
pub(crate) fn decode<V: Value>(raw: &Raw) -> Result<V> {
    value::decode(raw)
        .map_err(|mismatch| Error::corrupt(format!("its value does not read as the bucket's type: {mismatch}")))
}

/// A put of one cell, made before it waits for the writer.
struct PutCell {
    id: i64,
    path: Vec<u8>,
    raw: Raw,
    now: i64,
    put: Put,
    if_version: Option<Version>,
    /// The expiry the call asks for.
    given: Option<i64>,
    /// The bucket's expiry, for a key the write makes.
    default: Option<i64>,
    /// A live key keeps the expiry it has where the call gives none.
    keeps_its_expiry: bool,
}

impl PutCell {
    /// Writes the cell in one statement where nothing the cell there holds
    /// can change the write: a set, not at a version, of a value small enough
    /// for its cell, whose expiry no live key keeps or is none, as a bucket's
    /// whose keys never expire. A key with a ttl keeps an expiry only a read
    /// says. The read first cost a set a third of its instructions (issue 7).
    fn write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
        let expires = self.given.or(self.default);
        let keeps = self.keeps_its_expiry && self.given.is_none();
        let alone = self.put == Put::Always && self.if_version.is_none() && !cells::spills(&self.raw);
        if alone && (!keeps || expires.is_none()) {
            let version = next_version(revision, tx)?;
            if cells::set(tx, self.id, &self.path, (version, expires), &self.raw, keeps)? {
                return Ok(Stamp { written: true, version: Version(version), expires });
            }
        }
        self.read_then_write(tx, revision)
    }

    /// Reads the cell, then writes it as what it holds says: a create of a
    /// key that is not there, a write at the version the key has, or one that
    /// deletes the row the cell's last value spilled to.
    fn read_then_write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
        let current = cells::current(tx, self.id, &self.path, self.now)?;
        let live = current.filter(|current| current.live);
        if let (Put::OnlyNew, Some(live)) = (self.put, live) {
            return Ok(Stamp { written: false, version: Version(live.version), expires: live.expires });
        }
        check_version(live.map(|live| live.version), self.if_version)?;
        let expires = self.given.or(match live {
            Some(live) if self.keeps_its_expiry => live.expires,
            _ => self.default,
        });
        let version = next_version(revision, tx)?;
        let spilled = current.and_then(|current| current.spill);
        cells::put(tx, self.id, &self.path, (version, expires), &self.raw, spilled)?;
        Ok(Stamp { written: true, version: Version(version), expires })
    }
}

/// The key's current cell when it is live and, if a version is asked, at that
/// version; a key that is not is a conflict when a version was asked.
fn live_at(tx: &Tx<'_>, id: i64, path: &[u8], now: i64, if_version: Option<Version>) -> Result<Option<cells::Current>> {
    let live = cells::current(tx, id, path, now)?.filter(|current| current.live);
    check_version(live.map(|live| live.version), if_version)?;
    Ok(live)
}

fn check_version(found: Option<i64>, wanted: Option<Version>) -> Result<()> {
    match wanted {
        Some(Version(wanted)) if found != Some(wanted) => Err(Error::new(
            ErrorKind::Conflict,
            match found {
                Some(found) => format!("at version {found}, not {wanted}"),
                None => format!("not there at version {wanted}"),
            },
        )),
        _ => Ok(()),
    }
}

pub(crate) fn check_expiry(expiry: Expiry) -> Result<()> {
    match expiry {
        Expiry::Ttl(span) | Expiry::Idle(span) if span.is_zero() => Err(Error::invalid("an expiry of zero")),
        _ => Ok(()),
    }
}

#[cfg(test)]
#[path = "bucket_tests.rs"]
mod tests;