Skip to main content

tinystore/kv/
bucket.rs

1use std::fmt;
2use std::marker::PhantomData;
3use std::sync::Arc;
4use std::time::{Duration, SystemTime};
5
6use rusqlite::Connection;
7
8use super::cells::{self, Cell, MAX_VALUE};
9use super::encrypted::Encrypted;
10use super::engine::{Revision, next_version};
11#[cfg(feature = "replication")]
12use super::forward;
13use super::key_call::KeyCall;
14use super::path::Key;
15use super::renewals::Renewal;
16use super::scope::{Kind, Scope};
17use super::value::{self, Raw, Value};
18use crate::clock::{from_unix_millis, millis};
19use crate::engine::Home;
20#[cfg(any(feature = "sql", feature = "wire"))]
21use crate::engine::SharedFile;
22use crate::limits::VALUE_BYTES;
23use crate::sqlite::Tx;
24use crate::{Error, ErrorKind, Result, Store, unix_millis};
25
26/// Keys a clear deletes in one transaction; a larger branch is marked cleared
27/// and maintenance deletes it a batch at a time.
28const CLEAR_BOUND: usize = 10_000;
29
30/// Keys a page holds at most.
31pub const PAGE_KEYS: usize = 1000;
32
33/// Keys a count reads in one snapshot, so that a large branch holds no reader
34/// for long.
35const COUNT_KEYS: usize = 1 << 16;
36
37/// An idle key is renewed once a thirtieth of its term has passed since it
38/// last was, and before its read returns when it has less than a minute left.
39const REFRESHES: i64 = 30;
40const RENEW_AT_ONCE: i64 = 60_000;
41
42/// The tries an update makes while other writes race it before it gives up,
43/// as many as a config's change makes.
44pub(crate) const UPDATE_ATTEMPTS: usize = 8;
45
46/// A bucket being opened: its name, its type, how its keys expire, whether
47/// its values are encrypted.
48#[must_use = "a bucket opens with open()"]
49pub struct BucketBuilder<V> {
50    home: Home,
51    name: String,
52    expiry: Expiry,
53    encrypted: bool,
54    _value: PhantomData<fn() -> V>,
55}
56
57/// How a bucket's keys expire when a write does not say.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub(crate) enum Expiry {
60    Never,
61    /// A span after the key was written.
62    Ttl(Duration),
63    /// A span after the key was last read or written.
64    Idle(Duration),
65}
66
67impl Store {
68    /// A bucket of values of type `V` by key, in the store's kv.db; the engine
69    /// opens with the first handle.
70    pub fn bucket<V: Value>(&self, name: &str) -> BucketBuilder<V> {
71        BucketBuilder::new(Home::Store(self.clone()), name)
72    }
73}
74
75impl<V: Value> BucketBuilder<V> {
76    /// A bucket kept where `home` says, which a write passed on names.
77    #[cfg(feature = "replication")]
78    pub(crate) fn lent(home: Home, name: &str) -> Self {
79        BucketBuilder::new(home, name)
80    }
81
82    fn new(home: Home, name: &str) -> Self {
83        BucketBuilder { home, name: name.to_owned(), expiry: Expiry::Never, encrypted: false, _value: PhantomData }
84    }
85
86    /// A bucket kept in a file another engine lends, a database's.
87    #[cfg(any(feature = "sql", feature = "wire"))]
88    pub(crate) fn in_file(shared: Arc<SharedFile>, name: &str) -> Self {
89        BucketBuilder::new(Home::Shared(shared), name)
90    }
91}
92
93impl<V: Value> BucketBuilder<V> {
94    /// Keys expire this long after they are written, unless a write says
95    /// otherwise.
96    pub fn ttl(mut self, ttl: Duration) -> Self {
97        self.expiry = Expiry::Ttl(ttl);
98        self
99    }
100
101    /// Keys expire this long after they were last read or written.
102    pub fn idle(mut self, idle: Duration) -> Self {
103        self.expiry = Expiry::Idle(idle);
104        self
105    }
106
107    /// Keeps every value sealed with the store's encryption key, as a password
108    /// or a token is kept: the file holds what nobody reads without the key,
109    /// and a value copied under another key does not open. A key is not
110    /// sealed, so a secret is a value and never a key. A name keeps whether
111    /// it is encrypted: it opens the same way every time.
112    ///
113    /// ```no_run
114    /// # fn main() -> tinystore::Result<()> {
115    /// # let store = tinystore::Store::open("data", Default::default())?;
116    /// let passwords = store.bucket::<String>("source-passwords").encrypted().open()?;
117    /// passwords.set("source-42", &"hunter2".to_owned())?;
118    /// # Ok(())
119    /// # }
120    /// ```
121    pub fn encrypted(mut self) -> Self {
122        self.encrypted = true;
123        self
124    }
125
126    pub fn open(self) -> Result<Bucket<V>> {
127        check_expiry(self.expiry).map_err(|error| error.within(format!("kv bucket {}", self.name)))?;
128        let kind = if self.encrypted { Kind::Encrypted } else { Kind::Values };
129        let scope = Scope::open(&self.home, &self.name, kind)?;
130        let encrypted = self.encrypted.then(|| Encrypted::of(&scope)).transpose()?;
131        Ok(Bucket { encrypted, ..Bucket::new(scope, self.expiry) })
132    }
133}
134
135/// Values of one type by key. A handle is cheap to clone and to keep; `under`
136/// gives the same bucket seen from a branch.
137pub struct Bucket<V> {
138    pub(crate) scope: Scope,
139    expiry: Expiry,
140    /// What seals its rows, when the bucket is encrypted.
141    encrypted: Option<Encrypted>,
142    _value: PhantomData<fn() -> V>,
143}
144
145/// A key's value with what a conditional write needs.
146#[derive(Clone, Debug, PartialEq)]
147pub struct Entry<V> {
148    pub key: String,
149    pub value: V,
150    pub version: Version,
151    pub expires_at: Option<SystemTime>,
152}
153
154/// The revision of kv.db that wrote a value. It never repeats, across deletes,
155/// expiry and restarts, and it compares only for equality.
156#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
157pub struct Version(i64);
158
159impl Version {
160    #[cfg(any(feature = "wire", feature = "replication"))]
161    pub(crate) fn new(revision: i64) -> Version {
162        Version(revision)
163    }
164
165    #[cfg(any(feature = "wire", feature = "replication"))]
166    pub(crate) fn revision(self) -> i64 {
167        self.0
168    }
169}
170
171impl fmt::Display for Version {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        self.0.fmt(f)
174    }
175}
176
177impl std::str::FromStr for Version {
178    type Err = Error;
179
180    fn from_str(text: &str) -> Result<Self> {
181        text.parse().map(Version).map_err(|_| Error::invalid(format!("{text:?} is not a version")))
182    }
183}
184
185/// One page of a branch's keys, in the byte order of their text.
186#[derive(Clone, Debug, PartialEq)]
187pub struct Page<V> {
188    pub entries: Vec<Entry<V>>,
189    /// The key the next page starts after, when there is more.
190    pub next: Option<String>,
191}
192
193/// What a call on one key asks beside its key and value: a new expiry, and a
194/// version the key must still be at.
195#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
196pub(crate) struct WriteOptions {
197    pub(crate) expires: Option<Expires>,
198    pub(crate) if_version: Option<Version>,
199}
200
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub(crate) enum Expires {
203    In(Duration),
204    At(SystemTime),
205}
206
207impl WriteOptions {
208    pub(crate) fn ttl(mut self, ttl: Duration) -> Self {
209        self.expires = Some(Expires::In(ttl));
210        self
211    }
212
213    pub(crate) fn expires_at(mut self, time: SystemTime) -> Self {
214        self.expires = Some(Expires::At(time));
215        self
216    }
217
218    pub(crate) fn if_version(mut self, version: Version) -> Self {
219        self.if_version = Some(version);
220        self
221    }
222
223    fn expires(self, now: i64) -> Option<i64> {
224        self.expires.map(|expires| match expires {
225            Expires::In(span) => now.saturating_add(millis(span)),
226            Expires::At(time) => unix_millis(time),
227        })
228    }
229
230    /// The expiry of a key written at `now`. A ttl of zero is refused, as a
231    /// bucket's is: a span the program wrote, and never right. A time not
232    /// after now is written, the key gone at once: a time is data, and one a
233    /// moment ahead when the program took it may be past when this reads.
234    fn written_expires(self, now: i64) -> Result<Option<i64>> {
235        match self.expires {
236            Some(Expires::In(span)) if span.is_zero() => {
237                Err(Error::invalid("a ttl of zero, which writes a key already gone"))
238            }
239            _ => Ok(self.expires(now)),
240        }
241    }
242}
243
244/// How a write treats the key it finds.
245#[derive(Clone, Copy, Debug, PartialEq, Eq)]
246pub(crate) enum Put {
247    Always,
248    OnlyNew,
249}
250
251/// What a write left: whether it wrote, and the version and expiry the key
252/// has now, its own when a create found a live key there.
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub(crate) struct Stamp {
255    pub(crate) written: bool,
256    pub(crate) version: Version,
257    pub(crate) expires: Option<i64>,
258}
259
260/// What one try of an update makes of the key it read.
261pub(crate) enum Proposed<V> {
262    /// `change` wrote nothing: the value there, which the update answers.
263    Unchanged(Option<V>),
264    /// The value `change` made, and the write that keeps it.
265    Write(V, (Raw, WriteOptions, Put)),
266}
267
268/// Whether an update's write was kept: false when another write came first,
269/// so that the key is no longer at the version read, or a create found it.
270pub(crate) fn kept(written: Result<Stamp>) -> Result<bool> {
271    match written {
272        Ok(stamp) => Ok(stamp.written),
273        Err(error) if error.kind() == ErrorKind::Conflict => Ok(false),
274        Err(error) => Err(error),
275    }
276}
277
278/// A write as a closure the group commit or a transaction runs.
279pub(crate) trait Work<T>: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static {}
280
281impl<T, F: FnOnce(&Tx<'_>, &Revision) -> Result<T> + Send + 'static> Work<T> for F {}
282
283impl<V: Value> Bucket<V> {
284    /// Writes `value` under `key`. A key that is there keeps its ttl; a new one
285    /// takes the bucket's, and an idle key lives its span from the write.
286    pub fn set(&self, key: impl Key, value: &V) -> Result<()> {
287        self.put(&key.text(), value, WriteOptions::default(), Put::Always).map(|_| ())
288    }
289
290    /// Writes `value` only when `key` is not there, and says whether it did; an
291    /// expired key is not there. A key that is there is `false`, never an error.
292    pub fn create(&self, key: impl Key, value: &V) -> Result<bool> {
293        self.put(&key.text(), value, WriteOptions::default(), Put::OnlyNew)
294    }
295
296    /// Writes what `change` makes of the value under `key` without losing a
297    /// write made meanwhile: it reads the key, calls `change` with its value,
298    /// or `None` where there is none, and writes what `change` returns at the
299    /// version it read, or creates the key. When another write came first it
300    /// reads again and calls `change` again, eight tries at most, then fails
301    /// `Conflict`; so `change` may run more than once, and must change
302    /// nothing else. A `change` that returns `None` writes nothing. It answers
303    /// the value written, or the one there when nothing was.
304    ///
305    /// A key that is there keeps its expiry, and one it creates takes the
306    /// bucket's, as `set` and `create` do.
307    ///
308    /// ```no_run
309    /// # fn main() -> tinystore::Result<()> {
310    /// # let store = tinystore::Store::open("data", Default::default())?;
311    /// let pinned = store.bucket::<Vec<i64>>("pinned-courses").open()?;
312    /// // a phone and a laptop pinning at once both keep their course
313    /// pinned.update("97516", |courses| {
314    ///     let mut courses = courses.unwrap_or_default();
315    ///     courses.push(2518);
316    ///     Some(courses)
317    /// })?;
318    /// # Ok(())
319    /// # }
320    /// ```
321    pub fn update(&self, key: impl Key, mut change: impl FnMut(Option<V>) -> Option<V>) -> Result<Option<V>> {
322        let key = key.text();
323        for _ in 0..UPDATE_ATTEMPTS {
324            let found = self.read_cell(&key)?;
325            let (value, (raw, options, put)) = match self.proposed(&key, found, &mut change)? {
326                Proposed::Unchanged(current) => return Ok(current),
327                Proposed::Write(value, write) => (value, write),
328            };
329            if kept(self.put_raw(&key, raw, options, put))? {
330                return Ok(Some(value));
331            }
332        }
333        Err(self.raced(&key))
334    }
335
336    /// One try of an update, on what it read of `key`: the value there when
337    /// `change` makes none, else the value it makes and the write that keeps
338    /// it at the version read, or creates the key.
339    pub(crate) fn proposed(
340        &self,
341        key: &str,
342        found: Option<Cell>,
343        change: impl FnOnce(Option<V>) -> Option<V>,
344    ) -> Result<Proposed<V>> {
345        let decoded = |cell: &Cell| decode::<V>(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)));
346        let Some(next) = change(found.as_ref().map(decoded).transpose()?) else {
347            // `change` took the value it was given, so the one answered is decoded again
348            return Ok(Proposed::Unchanged(found.as_ref().map(decoded).transpose()?));
349        };
350        let raw = self.encode(key, &next)?;
351        let write = match found {
352            Some(cell) => (raw, WriteOptions::default().if_version(Version(cell.version)), Put::Always),
353            None => (raw, WriteOptions::default(), Put::OnlyNew),
354        };
355        Ok(Proposed::Write(next, write))
356    }
357
358    /// What an update answers once other writes came first each of its tries.
359    pub(crate) fn raced(&self, key: &str) -> Error {
360        let raced = Error::new(ErrorKind::Conflict, "other writes came first each time it was tried");
361        raced.within(self.scope.shown_key(key))
362    }
363
364    /// A call on `key` with what it asks beside its value, a new expiry or a
365    /// version the key must still be at, run by its last step:
366    /// `sessions.key(&token).if_version(seen).set(&next)`.
367    pub fn key(&self, key: impl Key) -> KeyCall<'_, V> {
368        KeyCall::new(self, None, key.text().into_owned())
369    }
370
371    pub fn get(&self, key: impl Key) -> Result<Option<V>> {
372        Ok(self.entry(key)?.map(|entry| entry.value))
373    }
374
375    /// The value with its version and expiry.
376    pub fn entry(&self, key: impl Key) -> Result<Option<Entry<V>>> {
377        let key = key.text();
378        let found = self.read_cell(&key)?;
379        found.map(|cell| self.entry_of(&key, cell)).transpose()
380    }
381
382    /// Reads `key` and removes it in one commit: of two callers taking the same
383    /// key, one gets the value. A value that no longer reads as the bucket's
384    /// type is `Corrupt`, and stays.
385    pub fn take(&self, key: impl Key) -> Result<Option<V>> {
386        let key = key.text();
387        #[cfg(feature = "replication")]
388        if self.is_copy() {
389            let cell = self.take_at_home(&key, WriteOptions::default())?;
390            return cell.map(|cell| decode::<V>(&cell.raw)).transpose();
391        }
392        let work = self.take_work(&key, WriteOptions::default())?;
393        self.scope.write(&key, 0, work)
394    }
395
396    /// One page of this branch's own keys, after `after` when it continues
397    /// another; `limit` keys at most, one at least, and never more than
398    /// [`PAGE_KEYS`].
399    pub fn list(&self, limit: usize, after: Option<&str>) -> Result<Page<V>> {
400        let limit = limit.clamp(1, PAGE_KEYS);
401        let rows = self
402            .scope
403            .kv
404            .file()
405            .read(|connection| self.page_rows(connection, limit, after))
406            .map_err(|error| error.within(self.scope.shown_branch()))?;
407        self.page_of(rows, limit)
408    }
409
410    /// Every key of this branch, a page at a time. No snapshot is held between
411    /// pages, so a slow loop keeps no reader, and a key written meanwhile may
412    /// or may not be met.
413    pub fn all(&self) -> All<V> {
414        All { bucket: self.clone(), page: Vec::new().into_iter(), next: None, done: false }
415    }
416
417    fn put(&self, key: &str, value: &V, options: WriteOptions, put: Put) -> Result<bool> {
418        Ok(self.put_raw(key, self.encode(key, value)?, options, put)?.written)
419    }
420
421    pub(crate) fn encode(&self, key: &str, value: &V) -> Result<Raw> {
422        value::encode(value).map_err(|mismatch| {
423            Error::invalid(format!("a value it cannot keep: {mismatch}")).within(self.scope.shown_key(key))
424        })
425    }
426
427    /// `take` with `options`, without waiting: `done` gets the value once the
428    /// commit ends. A value that no longer reads as `V` fails it, and stays.
429    #[cfg(feature = "async")]
430    pub(crate) fn take_then(
431        &self,
432        key: &str,
433        options: WriteOptions,
434        done: impl FnOnce(Result<Option<V>>) + Send + 'static,
435    ) {
436        #[cfg(feature = "replication")]
437        if self.is_copy() {
438            let decoded = |cell: Result<Option<Cell>>| cell?.map(|cell| decode::<V>(&cell.raw)).transpose();
439            return self.take_cell_then(key, options, move |cell| done(decoded(cell)));
440        }
441        self.scope.submit_made(key, 0, self.take_work(key, options), done);
442    }
443
444    pub(crate) fn take_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<V>> + use<V>> {
445        let take = self.take_cell_work(key, options)?;
446        Ok(move |tx: &Tx<'_>, revision: &Revision| {
447            let cell = take(tx, revision)?;
448            cell.map(|cell| decode::<V>(&cell.raw)).transpose()
449        })
450    }
451
452    pub(crate) fn entry_of(&self, key: &str, cell: Cell) -> Result<Entry<V>> {
453        Ok(Entry {
454            key: key.to_owned(),
455            value: decode(&cell.raw).map_err(|error| error.within(self.scope.shown_key(key)))?,
456            version: Version(cell.version),
457            expires_at: cell.expires.map(from_unix_millis),
458        })
459    }
460
461    /// Entries of the rows a page read, refused when one is not this branch's.
462    pub(crate) fn page_of(&self, rows: Vec<(Vec<u8>, Cell)>, limit: usize) -> Result<Page<V>> {
463        let branch = self.scope.branch()?;
464        let full = rows.len() == limit;
465        let mut entries = Vec::with_capacity(rows.len());
466        for (path, cell) in rows {
467            let key = branch.key_of(&path)?;
468            entries.push(self.entry_of(&key, cell)?);
469        }
470        let next = if full { entries.last().map(|entry| entry.key.clone()) } else { None };
471        Ok(Page { entries, next })
472    }
473}
474
475/// What a bucket does whatever its type: the calls that make no value, and
476/// the row-level ones the wire's handles use.
477impl<V> Bucket<V> {
478    pub(crate) fn new(scope: Scope, expiry: Expiry) -> Bucket<V> {
479        Bucket { scope, expiry, encrypted: None, _value: PhantomData }
480    }
481
482    /// The same bucket seen from the branch `owner` names under this one:
483    /// `sessions.under(user_id).clear()` signs a user out everywhere.
484    pub fn under(&self, owner: impl Key) -> Bucket<V> {
485        Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.under(owner), self.expiry) }
486    }
487
488    pub fn has(&self, key: impl Key) -> Result<bool> {
489        let key = key.text();
490        if matches!(self.expiry, Expiry::Idle(_)) {
491            return Ok(self.read_cell(&key)?.is_some());
492        }
493        let (id, path, now) = (self.scope.id, self.scope.path(&key)?, self.scope.now());
494        self.scope.read(&key, |connection| cells::has(connection, id, &path, now))
495    }
496
497    /// How many keys `all` would walk now: this branch's own live keys, not
498    /// those of the branches under it. An expired key not yet swept and a
499    /// cleared one are not counted, and an idle key is counted without being
500    /// renewed. It reads 65,536 keys a snapshot and holds none between
501    /// them, so a key written meanwhile may or may not be counted.
502    pub fn count(&self) -> Result<u64> {
503        let (mut after, past) = self.scope.branch()?.own_keys_after(None);
504        let (id, now) = (self.scope.id, self.scope.now());
505        let mut counted = 0;
506        loop {
507            let read = |connection: &Connection| cells::count(connection, id, (&after, &past), now, COUNT_KEYS);
508            let (keys, last) =
509                self.scope.kv.file().read(read).map_err(|error| error.within(self.scope.shown_branch()))?;
510            counted += keys as u64;
511            match last {
512                Some(last) if keys == COUNT_KEYS => after = last,
513                _ => return Ok(counted),
514            }
515        }
516    }
517
518    /// Removes `key` and says whether a live key was there.
519    pub fn delete(&self, key: impl Key) -> Result<bool> {
520        self.remove(&key.text(), WriteOptions::default())
521    }
522
523    /// Gives a live key a new expiry, `ttl` from now, as Redis's EXPIRE does,
524    /// keeping its value and version; says whether the key was there.
525    pub fn expire(&self, key: impl Key, ttl: Duration) -> Result<bool> {
526        self.expire_as(&key.text(), WriteOptions::default().ttl(ttl))
527    }
528
529    /// Gives a live key the expiry `options` names, at the version they name.
530    pub(crate) fn expire_as(&self, key: &str, options: WriteOptions) -> Result<bool> {
531        #[cfg(feature = "replication")]
532        if self.is_copy() {
533            return forward::found(&self.pass_on(key, forward::Call::Expire(options))?);
534        }
535        let work = self.expire_work(key, options)?;
536        self.scope.write(key, 0, work)
537    }
538
539    /// Removes every key of this branch and of the branches under it, at once
540    /// for every reader, however many there are.
541    pub fn clear(&self) -> Result<()> {
542        #[cfg(feature = "replication")]
543        if self.is_copy() {
544            return self.pass_on("", forward::Call::Clear).map(drop);
545        }
546        let work = clear_work(&self.scope)?;
547        let revision = self.scope.kv.revision();
548        let shown = self.scope.shown_branch();
549        self.scope.kv.file().write(0, move |tx| work(tx, &revision)).map_err(|error| error.within(shown))
550    }
551
552    /// Seals again with the store's sealing key every value of this branch,
553    /// and of the branches under it, that an older key sealed, and says how
554    /// many: once every value of the bucket is, an older key can leave the
555    /// store's options. It writes a batch of values a commit, each keeping
556    /// its version and its expiry. A value sealed with a key the store does
557    /// not hold stops it, `Invalid`, naming that key: the batches before it
558    /// stay sealed again, and a reseal after the key is given goes on.
559    pub fn reseal(&self) -> Result<u64> {
560        let shown = self.scope.shown_branch();
561        let Some(encrypted) = self.encrypted.clone() else {
562            return Err(Error::invalid("a bucket that is not encrypted holds nothing sealed").within(shown));
563        };
564        #[cfg(feature = "replication")]
565        if self.is_copy() {
566            return Err(Error::invalid("a copy's values are sealed again by its home").within(shown));
567        }
568        let branch = self.scope.branch()?;
569        let (mut from, to) = branch.everything();
570        let whole = branch.prefix().is_empty();
571        let mut moved = 0;
572        loop {
573            let work = reseal_work(&self.scope, &encrypted, (from, to.clone()), whole);
574            let (count, next) = self.scope.kv.file().write(0, work).map_err(|error| error.within(&shown))?;
575            moved += count;
576            match next {
577                Some(next) => from = next,
578                None => return Ok(moved),
579            }
580        }
581    }
582
583    /// `clear` without waiting for its commit.
584    #[cfg(any(feature = "wire", feature = "async"))]
585    pub(crate) fn clear_then(&self, done: impl FnOnce(Result<()>) + Send + 'static) {
586        #[cfg(feature = "replication")]
587        if self.is_copy() {
588            return self.pass_on_then("", forward::Call::Clear, |_| Ok(()), done);
589        }
590        let work = match clear_work(&self.scope) {
591            Ok(work) => work,
592            Err(error) => return done(Err(error)),
593        };
594        let (revision, shown) = (self.scope.kv.revision(), self.scope.shown_branch());
595        let answered = move |cleared: Result<()>| done(cleared.map_err(|error| error.within(shown)));
596        self.scope.kv.file().submit(0, move |tx| work(tx, &revision), answered);
597    }
598
599    /// Writes a row's value under `key`, as `put` says, and stamps it.
600    pub(crate) fn put_raw(&self, key: &str, raw: Raw, options: WriteOptions, put: Put) -> Result<Stamp> {
601        #[cfg(feature = "replication")]
602        if self.is_copy() {
603            return self
604                .pass_on(key, forward::Call::Put { raw, put, options })
605                .and_then(|bytes| forward::stamp(&bytes));
606        }
607        let (bytes, work) = self.put_work(key, raw, options, put)?;
608        self.scope.write(key, bytes, work)
609    }
610
611    /// `put_raw` without waiting: `done` gets the stamp once the commit ends.
612    #[cfg(any(feature = "wire", feature = "async"))]
613    pub(crate) fn put_raw_then(
614        &self,
615        key: &str,
616        (raw, options, put): (Raw, WriteOptions, Put),
617        done: impl FnOnce(Result<Stamp>) + Send + 'static,
618    ) {
619        #[cfg(feature = "replication")]
620        if self.is_copy() {
621            return self.pass_on_then(key, forward::Call::Put { raw, put, options }, forward::stamp, done);
622        }
623        match self.put_work(key, raw, options, put) {
624            Ok((bytes, work)) => self.scope.submit(key, bytes, work, done),
625            Err(error) => done(Err(error)),
626        }
627    }
628
629    /// The write a put commits, and the bytes it adds to its commit.
630    pub(crate) fn put_work(
631        &self,
632        key: &str,
633        raw: Raw,
634        options: WriteOptions,
635        put: Put,
636    ) -> Result<(usize, impl Work<Stamp> + use<V>)> {
637        self.put_work_as(key, raw, options, put, true)
638    }
639
640    /// A put's write, its value sealed first when `seal` says and the bucket
641    /// is encrypted, or written as it was sealed already.
642    fn put_work_as(
643        &self,
644        key: &str,
645        raw: Raw,
646        options: WriteOptions,
647        put: Put,
648        seal: bool,
649    ) -> Result<(usize, impl Work<Stamp> + use<V>)> {
650        if raw.len() > MAX_VALUE {
651            let too_large =
652                VALUE_BYTES.refuse(raw.len() as u64, format!("a value of {} bytes, over {MAX_VALUE}", raw.len()));
653            return Err(too_large.within(self.scope.shown_key(key)));
654        }
655        let now = self.scope.now();
656        let given = options.written_expires(now).map_err(|error| error.within(self.scope.shown_key(key)))?;
657        let path = self.scope.path(key)?;
658        let raw =
659            if seal { self.kept(&path, raw).map_err(|error| error.within(self.scope.shown_key(key)))? } else { raw };
660        let bytes = raw.len();
661        let cell = PutCell {
662            id: self.scope.id,
663            path,
664            raw,
665            now,
666            put,
667            if_version: options.if_version,
668            given,
669            default: self.default_expires(now),
670            // a write is a use of an idle key, which lives on from it; a key with a ttl keeps its own
671            keeps_its_expiry: !matches!(self.expiry, Expiry::Idle(_)),
672        };
673        let encrypted = self.encrypted.clone();
674        let work = move |tx: &Tx<'_>, revision: &Revision| {
675            if let Some(encrypted) = &encrypted {
676                encrypted.claim(tx)?;
677            }
678            cell.write(tx, revision)
679        };
680        Ok((bytes, work))
681    }
682
683    /// Removes a live key, at the version asked when one is, and says whether
684    /// one was there.
685    pub(crate) fn remove(&self, key: &str, options: WriteOptions) -> Result<bool> {
686        #[cfg(feature = "replication")]
687        if self.is_copy() {
688            return forward::found(&self.pass_on(key, forward::Call::Remove(options))?);
689        }
690        let work = self.remove_work(key, options)?;
691        self.scope.write(key, 0, work)
692    }
693
694    /// `remove` without waiting: `done` hears once the commit ends.
695    #[cfg(any(feature = "wire", feature = "async"))]
696    pub(crate) fn remove_then(
697        &self,
698        key: &str,
699        options: WriteOptions,
700        done: impl FnOnce(Result<bool>) + Send + 'static,
701    ) {
702        #[cfg(feature = "replication")]
703        if self.is_copy() {
704            return self.pass_on_then(key, forward::Call::Remove(options), forward::found, done);
705        }
706        self.scope.submit_made(key, 0, self.remove_work(key, options), done);
707    }
708
709    /// `expire_as` without waiting: `done` hears once the commit ends.
710    #[cfg(any(feature = "wire", feature = "async"))]
711    pub(crate) fn expire_then(
712        &self,
713        key: &str,
714        options: WriteOptions,
715        done: impl FnOnce(Result<bool>) + Send + 'static,
716    ) {
717        #[cfg(feature = "replication")]
718        if self.is_copy() {
719            return self.pass_on_then(key, forward::Call::Expire(options), forward::found, done);
720        }
721        self.scope.submit_made(key, 0, self.expire_work(key, options), done);
722    }
723
724    /// The delete of a key. It reads no value, so a key whose value no longer
725    /// opens, sealed with a key the store has lost, can still be deleted.
726    pub(crate) fn remove_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
727        let now = self.scope.now();
728        let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
729        Ok(move |tx: &Tx<'_>, _: &Revision| {
730            let Some(found) = live_at(tx, id, &path, now, if_version)? else {
731                return Ok(false);
732            };
733            cells::remove(tx, id, &path, found.spill)?;
734            Ok(true)
735        })
736    }
737
738    /// `take_cell_work` without waiting: `done` gets the cell once the commit
739    /// ends. The async API takes through it on a copy alone.
740    #[cfg(any(feature = "wire", all(feature = "async", feature = "replication")))]
741    pub(crate) fn take_cell_then(
742        &self,
743        key: &str,
744        options: WriteOptions,
745        done: impl FnOnce(Result<Option<Cell>>) + Send + 'static,
746    ) {
747        #[cfg(feature = "replication")]
748        if self.is_copy() {
749            match self.unsealer(key) {
750                Ok(read) => self.pass_on_then(key, forward::Call::Take(options), read, done),
751                Err(error) => done(Err(error)),
752            }
753            return;
754        }
755        self.scope.submit_made(key, 0, self.take_cell_work(key, options), done);
756    }
757
758    /// The take of a key: its delete, which hands back the cell it removed. A
759    /// cell that does not open fails the take, and stays.
760    pub(crate) fn take_cell_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<Option<Cell>> + use<V>> {
761        let now = self.scope.now();
762        let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
763        let encrypted = self.encrypted.clone();
764        Ok(move |tx: &Tx<'_>, _: &Revision| {
765            let Some(found) = live_at(tx, id, &path, now, if_version)? else {
766                return Ok(None);
767            };
768            let cell = cells::live(tx, id, &path, now)?;
769            cells::remove(tx, id, &path, found.spill)?;
770            cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose()
771        })
772    }
773
774    pub(crate) fn expire_work(&self, key: &str, options: WriteOptions) -> Result<impl Work<bool> + use<V>> {
775        let now = self.scope.now();
776        let expires = options
777            .expires(now)
778            .ok_or_else(|| Error::invalid("an expiry needs a ttl or a time").within(self.scope.shown_key(key)))?;
779        let (id, path, if_version) = (self.scope.id, self.scope.path(key)?, options.if_version);
780        Ok(move |tx: &Tx<'_>, _: &Revision| {
781            if live_at(tx, id, &path, now, if_version)?.is_none() {
782                return Ok(false);
783            }
784            cells::set_expires(tx, id, &path, Some(expires))?;
785            Ok(true)
786        })
787    }
788
789    /// Reads a live cell on a reader, renewing an idle key when it is due.
790    pub(crate) fn read_cell(&self, key: &str) -> Result<Option<Cell>> {
791        let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
792        let read = |connection: &Connection| {
793            let found = cells::live(connection, id, &path, now)?;
794            found.map(|cell| opened(self.encrypted.as_ref(), &path, cell)).transpose()
795        };
796        let found = self.scope.read(key, read)?;
797        Ok(found.map(|cell| self.renew(key, path, cell, now)))
798    }
799
800    /// Reads a live cell inside a transaction, renewing an idle key in it.
801    pub(crate) fn read_cell_in(&self, tx: &Tx<'_>, key: &str) -> Result<Option<Cell>> {
802        let (id, path, now) = (self.scope.id, self.scope.path(key)?, self.scope.now());
803        let Some(cell) = cells::live(tx, id, &path, now)? else {
804            return Ok(None);
805        };
806        let mut cell = opened(self.encrypted.as_ref(), &path, cell)?;
807        if let Some(renewal) = self.renewal_due(&cell, now)
808            && cells::renew(tx, id, &path, (renewal.version, renewal.seen), (renewal.until, now))?
809        {
810            cell.expires = Some(renewal.until);
811        }
812        Ok(Some(cell))
813    }
814
815    /// One page of this branch's own rows, each with its key, read in one
816    /// snapshot; the wire's pages, whose values stay rows.
817    #[cfg(feature = "wire")]
818    pub(crate) fn list_rows(&self, limit: usize, after: Option<&str>) -> Result<Vec<(String, Cell)>> {
819        let limit = limit.clamp(1, PAGE_KEYS);
820        let rows = self
821            .scope
822            .kv
823            .file()
824            .read(|connection| self.page_rows(connection, limit, after))
825            .map_err(|error| error.within(self.scope.shown_branch()))?;
826        self.keyed(rows)
827    }
828
829    /// Rows of this branch by path, each with its key instead.
830    #[cfg(feature = "wire")]
831    pub(crate) fn keyed(&self, rows: Vec<(Vec<u8>, Cell)>) -> Result<Vec<(String, Cell)>> {
832        let branch = self.scope.branch()?;
833        rows.into_iter().map(|(path, cell)| Ok((branch.key_of(&path)?, cell))).collect()
834    }
835
836    /// A page of this branch's own rows on `connection`, by path.
837    pub(crate) fn page_rows(
838        &self,
839        connection: &Connection,
840        limit: usize,
841        after: Option<&str>,
842    ) -> Result<Vec<(Vec<u8>, Cell)>> {
843        let (from, past) = self.scope.branch()?.own_keys_after(after);
844        let rows = cells::page(connection, self.scope.id, (&from, &past), self.scope.now(), limit)?;
845        let read = |(path, cell): (Vec<u8>, Cell)| {
846            let cell = opened(self.encrypted.as_ref(), &path, cell)?;
847            Ok((path, cell))
848        };
849        rows.into_iter().map(read).collect()
850    }
851
852    /// The row as the file keeps it: sealed when the bucket is encrypted.
853    fn kept(&self, path: &[u8], raw: Raw) -> Result<Raw> {
854        match &self.encrypted {
855            Some(encrypted) => encrypted.seal(path, &raw),
856            None => Ok(raw),
857        }
858    }
859
860    /// Renews a due idle key: with the next flush of renewals, or before the
861    /// read returns when the key has less than a minute left. A renewal that
862    /// cannot be written now waits for the flush. A copy's renewals are its
863    /// home's to write, and go there.
864    fn renew(&self, key: &str, path: Vec<u8>, mut cell: Cell, now: i64) -> Cell {
865        let Some(renewal) = self.renewal_due(&cell, now) else {
866            return cell;
867        };
868        #[cfg(feature = "replication")]
869        if self.is_copy() {
870            if self.renew_at_home(key, path, renewal, now) {
871                cell.expires = Some(renewal.until);
872            }
873            return cell;
874        }
875        let renewals = self.scope.kv.renewals();
876        if renewal.seen - now >= RENEW_AT_ONCE {
877            renewals.ask(self.scope.id, path, renewal);
878            return cell;
879        }
880        let (id, written_path, kv) = (self.scope.id, path.clone(), Arc::clone(&self.scope.kv));
881        let at_once = move |tx: &Tx<'_>, _: &Revision| {
882            cells::renew(tx, id, &written_path, (renewal.version, renewal.seen), (renewal.until, kv.now()))
883        };
884        match self.scope.write(key, 0, at_once) {
885            Ok(true) => cell.expires = Some(renewal.until),
886            Ok(false) => {}
887            // a point read refused its write here runs again on the pool, which renews the key
888            Err(_) if crate::polled::waits_refused() => {}
889            Err(_) => renewals.ask(self.scope.id, path, renewal),
890        }
891        cell
892    }
893
894    fn renewal_due(&self, cell: &Cell, now: i64) -> Option<Renewal> {
895        let Expiry::Idle(term) = self.expiry else {
896            return None;
897        };
898        let (term, expires) = (millis(term), cell.expires?);
899        if expires - now > term - term / REFRESHES {
900            return None;
901        }
902        Some(Renewal { version: cell.version, seen: expires, until: now.saturating_add(term) })
903    }
904
905    fn default_expires(&self, now: i64) -> Option<i64> {
906        match self.expiry {
907            Expiry::Never => None,
908            Expiry::Ttl(span) | Expiry::Idle(span) => Some(now.saturating_add(millis(span))),
909        }
910    }
911}
912
913impl Bucket<()> {
914    /// Adds `key` to a bucket of keys alone, a set, and says whether it was new:
915    /// `seen.add(event_id)` is false for an event already handled.
916    pub fn add(&self, key: impl Key) -> Result<bool> {
917        self.create(key, &())
918    }
919}
920
921/// A write on a copy of the bucket's file, which its home takes.
922#[cfg(feature = "replication")]
923impl<V> Bucket<V> {
924    pub(crate) fn is_copy(&self) -> bool {
925        self.scope.kv.file().is_copy()
926    }
927
928    /// Passes a call on `key` to the home of the copy, and gives its answer's
929    /// bytes once this copy holds the commit that made it.
930    pub(crate) fn pass_on(&self, key: &str, call: forward::Call) -> Result<Vec<u8>> {
931        let shown = || self.scope.shown_key(key);
932        let call = self.sealed(key, call).map_err(|error| error.within(shown()))?;
933        self.scope.pass_on(&self.handle(), key, &call)
934    }
935
936    /// The handle a call on this bucket is made on at its home.
937    fn handle(&self) -> forward::Handle {
938        let name = self.scope.name().to_owned();
939        let database = self.scope.kv.lent_by().and_then(crate::replication::database_of).map(str::to_owned);
940        forward::Handle::Bucket { name, expiry: self.expiry, encrypted: self.encrypted.is_some(), database }
941    }
942
943    /// Asks the home of the copy for a due renewal, as the home's own reads
944    /// renew a key, and says whether the home renewed it before this returned:
945    /// with the next pass of renewals, or at once when the key has less than a
946    /// minute left. That waits for the home's answer, a few seconds at most,
947    /// and neither for a link nor for this copy to hold the renewal. A store
948    /// opened beside the process that holds it passes nothing on.
949    fn renew_at_home(&self, key: &str, path: Vec<u8>, renewal: Renewal, now: i64) -> bool {
950        let (Ok(store), Ok(branch)) = (self.scope.kv.store(), self.scope.branch()) else { return false };
951        if store.is_beside() {
952            return false;
953        }
954        let request = forward::encode(&self.handle(), branch.owners(), key, &forward::Call::Renew(renewal));
955        let renewals = self.scope.kv.renewals();
956        if renewal.seen - now >= RENEW_AT_ONCE {
957            renewals.pass(self.scope.id, path, renewal, request);
958            return false;
959        }
960        renewals.pass_now(&store, (self.scope.id, path), renewal, request) == Some(true)
961    }
962
963    /// Renews `key` for a read on a copy, as this node's own reads do: with
964    /// the next flush, or at once when it has less than a minute left; says
965    /// whether it renewed it now. A node that holds a copy passes it on as its
966    /// own reads do.
967    pub(crate) fn renew_as(&self, key: &str, renewal: Renewal) -> Result<bool> {
968        let (id, path) = (self.scope.id, self.scope.path(key)?);
969        if self.is_copy() {
970            return Ok(self.renew_at_home(key, path, renewal, self.scope.now()));
971        }
972        if renewal.seen - self.scope.now() >= RENEW_AT_ONCE {
973            self.scope.kv.renewals().ask(id, path, renewal);
974            return Ok(false);
975        }
976        let kv = Arc::clone(&self.scope.kv);
977        self.scope.write(key, 0, move |tx: &Tx<'_>, _: &Revision| {
978            cells::renew(tx, id, &path, (renewal.version, renewal.seen), (renewal.until, kv.now()))
979        })
980    }
981
982    /// The call as it crosses the link: an encrypted bucket's value sealed
983    /// here, and a take asking for the value sealed on its way back.
984    fn sealed(&self, key: &str, call: forward::Call) -> Result<forward::Call> {
985        let Some(encrypted) = &self.encrypted else {
986            return Ok(call);
987        };
988        match call {
989            forward::Call::Put { raw, put, options } => {
990                let raw = encrypted.seal(&self.scope.path(key)?, &raw)?;
991                Ok(forward::Call::PutSealed { raw, key_id: encrypted.key_id(), put, options })
992            }
993            forward::Call::Take(options) => Ok(forward::Call::TakeSealed { options, key_id: encrypted.key_id() }),
994            call => Ok(call),
995        }
996    }
997
998    /// Takes a key at the home of the copy: an encrypted bucket's value comes
999    /// back sealed and opens here.
1000    pub(crate) fn take_at_home(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
1001        let answer = self.pass_on(key, forward::Call::Take(options))?;
1002        self.unsealer(key)?(&answer)
1003    }
1004
1005    /// What reads a take's answer from the home: its cell, opened with the
1006    /// bucket's key where it is encrypted.
1007    fn unsealer(&self, key: &str) -> Result<impl FnOnce(&[u8]) -> Result<Option<Cell>> + Send + 'static + use<V>> {
1008        let (encrypted, path, shown) = (self.encrypted.clone(), self.scope.path(key)?, self.scope.shown_key(key));
1009        Ok(move |answer: &[u8]| {
1010            let cell = forward::cell(answer)?;
1011            cell.map(|cell| opened(encrypted.as_ref(), &path, cell)).transpose().map_err(|error| error.within(shown))
1012        })
1013    }
1014
1015    /// Takes a key for a copy that shares this store's key, `key_id`, its
1016    /// value sealed again for the way back.
1017    pub(crate) fn take_sealed(&self, key: &str, options: WriteOptions, key_id: &str) -> Result<Option<Cell>> {
1018        let encrypted = self.shared_key(key, key_id)?;
1019        if self.is_copy() {
1020            let call = forward::Call::TakeSealed { options, key_id: key_id.to_owned() };
1021            return forward::cell(&self.pass_on(key, call)?);
1022        }
1023        let path = self.scope.path(key)?;
1024        let taken = self.scope.write(key, 0, self.take_cell_work(key, options)?)?;
1025        let seal = |mut cell: Cell| -> Result<Cell> {
1026            cell.raw = encrypted.seal(&path, &cell.raw)?;
1027            Ok(cell)
1028        };
1029        taken.map(seal).transpose().map_err(|error| error.within(self.scope.shown_key(key)))
1030    }
1031
1032    /// This bucket's key, which a copy sealed with `key_id`: a copy and its
1033    /// home share one.
1034    fn shared_key(&self, key: &str, key_id: &str) -> Result<&Encrypted> {
1035        let Some(encrypted) = &self.encrypted else {
1036            return Err(
1037                Error::invalid("a sealed value for a bucket that is not encrypted").within(self.scope.shown_key(key))
1038            );
1039        };
1040        if encrypted.key_id() != key_id {
1041            return Err(Error::invalid(format!(
1042                "a value sealed with the key {key_id}, and this store's is {}: a copy and its home share one key",
1043                encrypted.key_id()
1044            ))
1045            .within(self.scope.shown_key(key)));
1046        }
1047        Ok(encrypted)
1048    }
1049
1050    /// Writes a value a copy sealed with `key_id`, which must be this store's
1051    /// key for the bucket, as it is.
1052    pub(crate) fn put_sealed(
1053        &self,
1054        key: &str,
1055        raw: Raw,
1056        key_id: &str,
1057        options: WriteOptions,
1058        put: Put,
1059    ) -> Result<Stamp> {
1060        self.shared_key(key, key_id)?;
1061        let (bytes, work) = self.put_work_as(key, raw, options, put, false)?;
1062        self.scope.write(key, bytes, work)
1063    }
1064
1065    /// Claims a once's key at the home of the copy these answers are kept in.
1066    pub(crate) fn once_claim(&self, key: &str) -> Result<forward::Claimed> {
1067        forward::claimed(&self.pass_on_once(key, &forward::Call::OnceClaim)?)
1068    }
1069
1070    /// Keeps at the home what a run it handed over answered.
1071    pub(crate) fn once_keep(&self, key: &str, token: u64, answer: Option<Raw>) -> Result<()> {
1072        self.pass_on_once(key, &forward::Call::OnceKeep { token, answer }).map(drop)
1073    }
1074
1075    fn pass_on_once(&self, key: &str, call: &forward::Call) -> Result<Vec<u8>> {
1076        let shown = || self.scope.shown_key(key);
1077        let keep = match self.expiry {
1078            Expiry::Ttl(keep) => crate::clock::millis(keep) as u64,
1079            _ => return Err(Error::internal("once's answers kept for no span").within(shown())),
1080        };
1081        let handle = forward::Handle::Once { name: self.scope.name().to_owned(), keep };
1082        self.scope.pass_on(&handle, key, call).map_err(|error| error.within(shown()))
1083    }
1084
1085    /// Takes a key's cell, at the home where the bucket's file is a copy.
1086    pub(crate) fn take_cell(&self, key: &str, options: WriteOptions) -> Result<Option<Cell>> {
1087        if self.is_copy() {
1088            return self.take_at_home(key, options);
1089        }
1090        let work = self.take_cell_work(key, options)?;
1091        self.scope.write(key, 0, work)
1092    }
1093
1094    /// `pass_on` without waiting, on a thread of its own: `done` gets what
1095    /// `read` makes of the answer.
1096    #[cfg(any(feature = "wire", feature = "async"))]
1097    fn pass_on_then<T: Send + 'static>(
1098        &self,
1099        key: &str,
1100        call: forward::Call,
1101        read: impl FnOnce(&[u8]) -> Result<T> + Send + 'static,
1102        done: impl FnOnce(Result<T>) + Send + 'static,
1103    ) {
1104        let (bucket, key) = (self.untyped(), key.to_owned());
1105        std::thread::spawn(move || done(bucket.pass_on(&key, call).and_then(|bytes| read(&bytes))));
1106    }
1107}
1108
1109impl<V> Bucket<V> {
1110    /// The same bucket as rows, whose calls make no value of `V`.
1111    #[cfg(any(all(feature = "wire", feature = "replication"), feature = "async"))]
1112    pub(crate) fn untyped(&self) -> Bucket<()> {
1113        Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
1114    }
1115}
1116
1117impl<V> Clone for Bucket<V> {
1118    fn clone(&self) -> Self {
1119        Bucket { encrypted: self.encrypted.clone(), ..Bucket::new(self.scope.clone(), self.expiry) }
1120    }
1121}
1122
1123impl<V> fmt::Debug for Bucket<V> {
1124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125        write!(f, "Bucket({:?})", self.scope)
1126    }
1127}
1128
1129impl<V> fmt::Debug for BucketBuilder<V> {
1130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131        write!(f, "BucketBuilder({})", self.name)
1132    }
1133}
1134
1135/// Every key of a branch, a page at a time.
1136pub struct All<V> {
1137    bucket: Bucket<V>,
1138    page: std::vec::IntoIter<Entry<V>>,
1139    next: Option<String>,
1140    done: bool,
1141}
1142
1143impl<V: Value> Iterator for All<V> {
1144    type Item = Result<Entry<V>>;
1145
1146    fn next(&mut self) -> Option<Self::Item> {
1147        loop {
1148            if let Some(entry) = self.page.next() {
1149                return Some(Ok(entry));
1150            }
1151            if self.done {
1152                return None;
1153            }
1154            match self.bucket.list(PAGE_KEYS, self.next.as_deref()) {
1155                Ok(page) => {
1156                    self.done = page.next.is_none();
1157                    self.next = page.next;
1158                    self.page = page.entries.into_iter();
1159                }
1160                Err(error) => {
1161                    self.done = true;
1162                    return Some(Err(error));
1163                }
1164            }
1165        }
1166    }
1167}
1168
1169impl<V> fmt::Debug for All<V> {
1170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1171        write!(f, "All({:?})", self.bucket.scope)
1172    }
1173}
1174
1175/// The values a reseal's commit seals again at most, and the bytes past which
1176/// it takes no more, since each value may be a mebibyte.
1177const RESEAL_BATCH: (usize, usize) = (1000, 8 << 20);
1178
1179/// One batch of a reseal: the live cells from `from` on, each an older key
1180/// sealed opened and sealed with the sealing key, and how many it sealed with
1181/// where the next batch begins, none after the last. The last batch of a
1182/// bucket resealed whole leaves it the sealing key alone.
1183fn reseal_work(
1184    scope: &Scope,
1185    encrypted: &Encrypted,
1186    (from, to): (Vec<u8>, Vec<u8>),
1187    whole: bool,
1188) -> impl FnOnce(&Tx<'_>) -> Result<(u64, Option<Vec<u8>>)> + Send + 'static + use<> {
1189    let (id, now, encrypted) = (scope.id, scope.now(), encrypted.clone());
1190    move |tx: &Tx<'_>| {
1191        let (cells, more) = cells::sealed_page(tx, id, (&from, &to), now, RESEAL_BATCH)?;
1192        let mut moved = 0;
1193        for cell in cells.iter().filter(|cell| !encrypted.sealed_it(&cell.bytes)) {
1194            let opened = encrypted.open(&cell.path, &Raw::Bytes(cell.bytes.clone()))?;
1195            let Raw::Bytes(sealed) = encrypted.seal(&cell.path, &opened)? else {
1196                return Err(Error::internal("a value sealed as no bytes"));
1197            };
1198            cells::reseal(tx, id, cell, &sealed)?;
1199            moved += 1;
1200        }
1201        if more {
1202            let mut next = cells.last().map(|cell| cell.path.clone()).unwrap_or_default();
1203            next.push(0);
1204            return Ok((moved, Some(next)));
1205        }
1206        if whole {
1207            cells::keep_bucket_key(tx, id, Some(&encrypted.sealing()))?;
1208        }
1209        Ok((moved, None))
1210    }
1211}
1212
1213/// The clear of a scope's branch: every key under it deleted when they are few,
1214/// else the branch marked cleared at a new version, which hides them at once.
1215pub(crate) fn clear_work(scope: &Scope) -> Result<impl Work<()> + use<>> {
1216    let branch = scope.branch()?;
1217    let (id, prefix, everything) = (scope.id, branch.prefix().to_vec(), branch.everything());
1218    Ok(move |tx: &Tx<'_>, revision: &Revision| {
1219        // a bucket cleared whole holds no value of any key, and takes the key of its next write
1220        if prefix.is_empty() {
1221            cells::keep_bucket_key(tx, id, None)?;
1222        }
1223        if cells::delete_under(tx, id, (&everything.0, &everything.1), CLEAR_BOUND)? {
1224            return Ok(());
1225        }
1226        let cleared = next_version(revision, tx)?;
1227        cells::mark_cleared(tx, id, &prefix, cleared)
1228    })
1229}
1230
1231/// A cell of the file as a caller reads it: opened when its bucket is
1232/// encrypted.
1233fn opened(encrypted: Option<&Encrypted>, path: &[u8], mut cell: Cell) -> Result<Cell> {
1234    if let Some(encrypted) = encrypted {
1235        cell.raw = encrypted.open(path, &cell.raw)?;
1236    }
1237    Ok(cell)
1238}
1239
1240/// A row read back as `V`; a row that is not one is corrupt.
1241pub(crate) fn decode<V: Value>(raw: &Raw) -> Result<V> {
1242    value::decode(raw)
1243        .map_err(|mismatch| Error::corrupt(format!("its value does not read as the bucket's type: {mismatch}")))
1244}
1245
1246/// A put of one cell, made before it waits for the writer.
1247struct PutCell {
1248    id: i64,
1249    path: Vec<u8>,
1250    raw: Raw,
1251    now: i64,
1252    put: Put,
1253    if_version: Option<Version>,
1254    /// The expiry the call asks for.
1255    given: Option<i64>,
1256    /// The bucket's expiry, for a key the write makes.
1257    default: Option<i64>,
1258    /// A live key keeps the expiry it has where the call gives none.
1259    keeps_its_expiry: bool,
1260}
1261
1262impl PutCell {
1263    /// Writes the cell in one statement where nothing the cell there holds
1264    /// can change the write: a set, not at a version, of a value small enough
1265    /// for its cell, whose expiry no live key keeps or is none, as a bucket's
1266    /// whose keys never expire. A key with a ttl keeps an expiry only a read
1267    /// says. The read first cost a set a third of its instructions (issue 7).
1268    fn write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
1269        let expires = self.given.or(self.default);
1270        let keeps = self.keeps_its_expiry && self.given.is_none();
1271        let alone = self.put == Put::Always && self.if_version.is_none() && !cells::spills(&self.raw);
1272        if alone && (!keeps || expires.is_none()) {
1273            let version = next_version(revision, tx)?;
1274            if cells::set(tx, self.id, &self.path, (version, expires), &self.raw, keeps)? {
1275                return Ok(Stamp { written: true, version: Version(version), expires });
1276            }
1277        }
1278        self.read_then_write(tx, revision)
1279    }
1280
1281    /// Reads the cell, then writes it as what it holds says: a create of a
1282    /// key that is not there, a write at the version the key has, or one that
1283    /// deletes the row the cell's last value spilled to.
1284    fn read_then_write(self, tx: &Tx<'_>, revision: &Revision) -> Result<Stamp> {
1285        let current = cells::current(tx, self.id, &self.path, self.now)?;
1286        let live = current.filter(|current| current.live);
1287        if let (Put::OnlyNew, Some(live)) = (self.put, live) {
1288            return Ok(Stamp { written: false, version: Version(live.version), expires: live.expires });
1289        }
1290        check_version(live.map(|live| live.version), self.if_version)?;
1291        let expires = self.given.or(match live {
1292            Some(live) if self.keeps_its_expiry => live.expires,
1293            _ => self.default,
1294        });
1295        let version = next_version(revision, tx)?;
1296        let spilled = current.and_then(|current| current.spill);
1297        cells::put(tx, self.id, &self.path, (version, expires), &self.raw, spilled)?;
1298        Ok(Stamp { written: true, version: Version(version), expires })
1299    }
1300}
1301
1302/// The key's current cell when it is live and, if a version is asked, at that
1303/// version; a key that is not is a conflict when a version was asked.
1304fn live_at(tx: &Tx<'_>, id: i64, path: &[u8], now: i64, if_version: Option<Version>) -> Result<Option<cells::Current>> {
1305    let live = cells::current(tx, id, path, now)?.filter(|current| current.live);
1306    check_version(live.map(|live| live.version), if_version)?;
1307    Ok(live)
1308}
1309
1310fn check_version(found: Option<i64>, wanted: Option<Version>) -> Result<()> {
1311    match wanted {
1312        Some(Version(wanted)) if found != Some(wanted) => Err(Error::new(
1313            ErrorKind::Conflict,
1314            match found {
1315                Some(found) => format!("at version {found}, not {wanted}"),
1316                None => format!("not there at version {wanted}"),
1317            },
1318        )),
1319        _ => Ok(()),
1320    }
1321}
1322
1323pub(crate) fn check_expiry(expiry: Expiry) -> Result<()> {
1324    match expiry {
1325        Expiry::Ttl(span) | Expiry::Idle(span) if span.is_zero() => Err(Error::invalid("an expiry of zero")),
1326        _ => Ok(()),
1327    }
1328}
1329
1330#[cfg(test)]
1331#[path = "bucket_tests.rs"]
1332mod tests;