datumesh-store 0.4.3

Store for Datumesh on PostgreSQL or SQLite: descriptors, receipts, blobs, versions over transaction time, lineage, namespaces and names; a datumesh-core Resolver.
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
//! A store for [Datumesh](https://datumesh.com): function descriptors, receipts, blobs,
//! versions of cells over transaction time, lineage, namespaces and function names, on
//! PostgreSQL or (since 0.4.0) in one SQLite file. [`PgStore`] and [`SqliteStore`] implement
//! [`Store`], and through it `datumesh_core`'s [`Resolver`], so `datumesh_core::verify` can
//! recompute receipts of stored cells from either; the two behave the same (one
//! conformance suite runs against both).
//!
//! The API is synchronous (the `postgres` driver and a small connection pool; `rusqlite`
//! with SQLite compiled in, feature `sqlite`, on by default). Async callers run it on a
//! blocking thread, e.g. `tokio::task::spawn_blocking`.
//!
//! [`SqliteStore::open`] takes a file path ([`SqliteStore::connect`] a `sqlite:` URL); the
//! file is in WAL mode, every write is one `BEGIN IMMEDIATE` transaction, and the
//! append-only rules are triggers in the file, so they hold for writers in several
//! threads and processes on one machine. Its schema comes from [`migrate::sqlite::apply`].
//!
//! [`PgStore::connect`] / [`PgStore::connect_with`] take a URL and [`PoolOptions`]; TLS
//! (rustls) is used as the URL's `sslmode` says and always verifies the server's
//! certificate and host name, against the Mozilla roots plus those added with
//! [`PoolOptions::tls_root_certificates_pem`]. No type of the driver or of a TLS crate is
//! part of the API, except in [`pg_unstable`] (any connection function, the driver
//! itself), which is outside semver until 1.0.
//!
//! What is stored, and how:
//!
//! * Descriptors are checked by the core (`FunctionDescriptor::from_json`: since 0.3.1,
//!   spec-0.4.0's, with `signature.order` and argument `extent`) and stored in canonical
//!   form (JCS) under their hash. Receipts are verified (`datumesh_core::verify`, SPEC 10.1
//!   steps 1-6) against the key document stored for their signer host, so nothing
//!   unverified enters the store, and are stored canonical under their hash. Storing the
//!   same thing twice stores it once. A second, different valid signature over the same
//!   payload (possible only with a randomised signer: the payload names the key, so a
//!   rotated key gives a new hash) is refused ([`Error::Conflict`]) and the stored receipt
//!   kept.
//! * Blobs are stored in the database, under the SHA-256 of their content.
//! * Versions: from transaction time `tx` on, cell `cell_id` has the value of a receipt.
//!   Append-only and in tx order per cell, enforced by the database (triggers) as well as by
//!   [`Store::put_version`], which also checks that the receipt is stored and is of that
//!   cell at that tx.
//! * Computed versions: from transaction time `tx` on, cell `cell_id` has the value a
//!   receipt computed, as of the receipt's asof. Derived rather than facts, so they are
//!   added in any order, keyed on (cell, tx, asof), insert-only
//!   ([`Store::put_computed`], [`Store::computed_asof`]).
//! * Answering as of A: a receipt answers as of A only when its `tx` and its `asof` are
//!   both at or before A ([`Store::stored_asof`], and the [`Resolver`]'s `evaluate` of a
//!   stored function; [`Store::version_asof`] looks at `tx` only).
//! * Lineage: `put_receipt` records an edge to each of the receipt's `inputs`, held or not:
//!   receipt hashes ([`Store::inputs`], [`Store::dependents`]) and, since 0.3.1, slice
//!   entries ([`Store::slice_entries`], [`Store::slice_dependents`]);
//!   [`Store::cell_dependents`] lifts both to cells.
//! * Slices (0.3.1, SPEC 15.13): every stored receipt's cell is indexed by its typed
//!   arguments, so that [`Store::slice_members`] finds the members of a slice as of A with
//!   a range scan, in key order; [`Store::versions_between`] gives a version slice.
//!   [`Store::slice_values`] gives the members' values without receipts (0.3.2) and
//!   [`Store::slice_changed_after`] whether they may answer differently later.
//!   Manifests ([`Store::put_manifest`], served by [`Resolver::manifest`]) are kept by
//!   entry and found from each member ([`Store::member_manifests`]). A receipt citing a
//!   slice can be stored before its manifest, and a manifest before its members.
//! * Namespaces: a host's key document (checked as SPEC 9.2 requires), with when it was
//!   validated. Store it before the host's receipts. Replacing it later (a key revoked or
//!   dropped) does not touch receipts already stored: they verified when they were stored,
//!   and putting one of them again is still idempotent.
//! * Names: which function hash a fully qualified function name meant from a transaction
//!   time on. Append-only, like versions. [`Store::resolve_binding`] gives the binding
//!   answering as of A with when it began; [`Store::resolve_name`] its hash.
//! * Classes (0.4.1, SPEC 16.1 to 16.3): a flattened class descriptor, checked by the core and
//!   stored canonical under its class hash ([`Store::put_class`], [`Store::class`]). A class
//!   name is bound over transaction time to a class hash, and binding it binds each method
//!   `<class name>/<m>` to the method's function hash in the same transaction
//!   ([`Store::bind_class`], [`Store::resolve_class`], [`Store::resolve_class_binding`]).
//!   Class names and function names are one namespace: a name bound as one kind cannot be
//!   bound as the other ([`Error::NameTaken`]).
//! * Owner: a class's owner is the definer's check (SPEC 16.2 step 1), made when the class is
//!   defined, not the store's. The store records what it is given; the HTTP service and the
//!   engine enforce the owner rule. [`Store::put_class`] and [`Store::bind_class`] do not take a
//!   key document or check the name against the steward.
//! * Namespace suspension (since 0.4.1): new writes under a suspended namespace are refused
//!   with [`Error::NamespaceSuspended`] (`put_class`: the steward's namespace; `bind_class`: the
//!   host of the class name); reads are never refused.
//!
//! Instants are compared as text (fixed width, `COLLATE "C"`; SQLite's default collation
//! is the same byte order), which is exact; on PostgreSQL each is also stored as
//! `timestamptz`, which round-trips every instant of the specification exactly. Numbers in
//! the typed-argument index compare as exact decimals (PostgreSQL `numeric`; on SQLite a
//! text encoding that sorts as the decimal does).
//!
//! Every [`Store`] method returns a `Result`: a malformed argument is [`Error::Invalid`] with
//! the core's code, a database failure [`Error::Database`]. The [`Resolver`] methods keep the
//! core's `Option` signatures; there a failure is logged with `tracing` (target
//! `datumesh_store`) and answered `None`, which `verify` reports as unavailable.
//!
//! [`Store`] is sealed: only this crate implements it. The store is the trust boundary:
//! everything in it was checked on the way in (every receipt verified against its host's
//! key document), and its callers rely on that rather than checking again. A `dyn Store`
//! is still a trait object as before.
//!
//! The schema comes from [`migrate::apply`] (PostgreSQL) or [`migrate::sqlite::apply`]
//! (SQLite) (the `datumesh-store migrate` command, for either), through a store on the
//! (possibly empty) database.

#![forbid(unsafe_code)]
#![deny(missing_docs)]

use std::borrow::Cow;

pub use datumesh_core::Resolver;
use datumesh_core::{Cell, Scalar, Slice};

mod error;
pub mod migrate;
mod pg;
pub mod pg_unstable;
mod pool;
mod slices;
mod sql;
#[cfg(feature = "sqlite")]
mod sqlite;
#[cfg(feature = "sqlite")]
mod sqlite_sql;
mod tls;

pub use error::{DatabaseError, Error, Result};
pub use pg::PgStore;
pub use pool::PoolOptions;
#[cfg(feature = "sqlite")]
pub use sqlite::{SqliteOptions, SqliteStore};

/// A version of a cell: from transaction time `tx` on, the cell's value is that of the
/// receipt `receipt_hash`, which states it as of `asof`.
///
/// A stored version ([`Store::put_version`]) or a computed one ([`Store::put_computed`]).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Version {
    /// The cell id.
    pub cell_id: String,
    /// The transaction time (an instant, SPEC 3.3).
    pub tx: String,
    /// The receipt stating the value.
    pub receipt_hash: String,
    /// The receipt's `asof` (an instant; never earlier than `tx`). Since 0.2.0.
    pub asof: String,
}

/// One cell write of [`Store::put_cells`]: a receipt and, optionally, the version it
/// becomes. Since 0.4.3.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CellWrite<'a> {
    /// The receipt's JSON bytes, as for `put_receipt`.
    pub receipt: &'a [u8],
    /// `Some((cell_id, tx))`: also `put_version(cell_id, tx, <this receipt's hash>)`.
    pub version: Option<(&'a str, &'a str)>,
}

impl<'a> CellWrite<'a> {
    /// A cell write of `receipt` and, when `version` is `Some((cell_id, tx))`, its version.
    pub fn new(receipt: &'a [u8], version: Option<(&'a str, &'a str)>) -> Self {
        CellWrite { receipt, version }
    }
}

/// A member of a slice ([`Store::slice_members`], [`Store::versions_between`]): a stored
/// version and the bytes of its receipt (as [`receipt`](Resolver::receipt) returns them).
/// Since 0.3.1.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SliceMember {
    /// The version answering (its cell, tx, receipt hash and asof).
    pub version: Version,
    /// The receipt's bytes, canonical JSON.
    pub receipt: Vec<u8>,
}

/// A member of a slice with its value and without its receipt's bytes
/// ([`Store::slice_values`]). Since 0.3.2.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SliceValue {
    /// The version answering (its cell, tx, receipt hash and asof).
    pub version: Version,
    /// The receipt's typed value.
    pub value: Scalar,
    /// The member's cell, with its arguments (from the store's typed-argument index; equal
    /// to the receipt's `cell`, and `cell.id()` is `version.cell_id`).
    pub cell: Cell,
}

/// A name binding: from transaction time `tx` on, a fully qualified function name means the
/// function `fn_hash` ([`Store::bind_name`]). Since 0.3.0.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Binding {
    /// The function hash the name means.
    pub fn_hash: String,
    /// When the binding began: the transaction time from which the name means `fn_hash`
    /// (an instant, SPEC 3.3).
    pub tx: String,
}

/// A class-name binding: from transaction time `tx` on, a class name means the class
/// `class_hash` ([`Store::bind_class`]). The class counterpart of [`Binding`]; the bindings
/// answer of SPEC 9.7 gives `class_hash` in place of `fn_hash` for such a name. Since 0.4.1.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ClassBinding {
    /// The class hash the name means.
    pub class_hash: String,
    /// When the binding began (an instant, SPEC 3.3).
    pub tx: String,
}

/// A namespace's host and its key document.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Namespace {
    /// The host (a DNS name).
    pub host: String,
    /// The key document, canonical (JCS).
    pub keydoc: Vec<u8>,
    /// When the document was last retrieved and checked.
    pub validated_at: String,
    /// When the namespace was suspended, if it is: the single record of suspension. Set by
    /// [`record_namespace_failure`](Store::record_namespace_failure) when the consecutive
    /// failures reach its threshold, cleared by
    /// [`record_namespace_success`](Store::record_namespace_success). While it is set the
    /// store refuses new writes under the host ([`Error::NamespaceSuspended`]).
    pub suspended_at: Option<String>,
    /// How many checks of the host's key document have failed in a row (zero after a
    /// success). Since the namespace checks (since 0.4.1).
    pub consecutive_failures: u32,
    /// When the host's key document was last checked, successfully or not; `None` before
    /// the first check recorded. Since the namespace checks (since 0.4.1).
    pub last_checked_at: Option<String>,
}

/// The namespace after a check at `at`: a failed one (`threshold` is `Some`) adds to the
/// consecutive failures and suspends at the threshold (an existing suspension keeps its
/// time), a successful one (`None`) resets them and reinstates.
/// The refusal of class descriptor bytes that are not the canonical form of the descriptor
/// (`E_SCHEMA`, nothing stored): the class hash is the hash of the bytes stored, so only the
/// canonical bytes are stored. Shared by both backends (since 0.4.1).
pub(crate) fn not_canonical_class() -> Error {
    Error::Invalid(datumesh_core::Error::new(
        datumesh_core::ErrorCode::Schema,
        "$",
        "class descriptor is not in canonical form (JCS): put the canonical bytes",
    ))
}

pub(crate) fn apply_check(ns: &mut Namespace, at: &str, threshold: Option<u32>) {
    ns.last_checked_at = Some(at.to_string());
    match threshold {
        None => {
            ns.consecutive_failures = 0;
            ns.suspended_at = None;
        }
        Some(t) => {
            ns.consecutive_failures = ns.consecutive_failures.saturating_add(1);
            if ns.suspended_at.is_none() && ns.consecutive_failures >= t.max(1) {
                ns.suspended_at = Some(at.to_string());
            }
        }
    }
}

/// A Datumesh store: a [`Resolver`] that can also be written to.
///
/// Instants are SPEC 3.3 instants (`YYYY-MM-DDTHH:MM:SS.ffffffZ`), hashes and cell ids 64
/// lowercase hex digits, hosts DNS names and function names fully qualified. Every method,
/// read or write, refuses anything else with the core's error code ([`Error::Invalid`]),
/// and reports a database failure as [`Error::Database`] (or [`Error::PoolTimeout`]): a read
/// answers `Ok(None)` / `Ok(vec![])` only when the store really holds nothing.
///
/// The [`Resolver`] methods keep the core's `Option` signatures: there a malformed argument
/// or a database failure is `None` (logged with `tracing` when it is a failure), which
/// `verify` reports as unavailable.
///
/// Only this crate implements `Store` (it is sealed, since 0.3.0; [`PgStore`] and, since
/// 0.4.0, [`SqliteStore`]): the store is the trust boundary, where every receipt is verified against its host's key document before it is
/// kept, and what a store answers is relied on as checked. An implementation elsewhere
/// could answer anything. `Store` stays object-safe (`Arc<dyn Store + Send + Sync>`). Even a complete implementation that
/// delegates every method to a [`PgStore`] is refused (`E0277`: the private supertrait is
/// not implemented; `tests/sealed.rs` checks that this is the only error):
///
/// ```compile_fail
/// use std::borrow::Cow;
/// use datumesh_core::{Cell, Scalar};
/// use datumesh_core::Slice;
/// use datumesh_store::{Binding, ClassBinding, Namespace, PgStore, Resolver, Result, SliceMember, SliceValue, Store, Version};
///
/// struct Wrapper(PgStore);
/// impl Resolver for Wrapper {
///     fn descriptor(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.descriptor(h) }
///     fn receipt(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.receipt(h) }
///     fn evaluate(&self, c: &Cell, a: &str) -> Option<Scalar> { self.0.evaluate(c, a) }
///     fn manifest(&self, e: &str) -> Option<Cow<'_, [u8]>> { self.0.manifest(e) }
/// }
/// impl Store for Wrapper {
///     fn put_descriptor(&self, b: &[u8]) -> Result<String> { self.0.put_descriptor(b) }
///     fn put_receipt(&self, b: &[u8]) -> Result<String> { self.0.put_receipt(b) }
///     fn put_blob(&self, b: &[u8]) -> Result<String> { self.0.put_blob(b) }
///     fn blob(&self, s: &str) -> Result<Option<Cow<'_, [u8]>>> { self.0.blob(s) }
///     fn put_version(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_version(c, t, r) }
///     fn version_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.version_asof(c, a) }
///     fn versions(&self, c: &str, f: &str, t: &str) -> Result<Vec<Version>> { self.0.versions(c, f, t) }
///     fn latest(&self, c: &str) -> Result<Option<Version>> { self.0.latest(c) }
///     fn dependents(&self, r: &str) -> Result<Vec<String>> { self.0.dependents(r) }
///     fn inputs(&self, r: &str) -> Result<Vec<String>> { self.0.inputs(r) }
///     fn put_namespace(&self, h: &str, k: &[u8], v: &str) -> Result<()> { self.0.put_namespace(h, k, v) }
///     fn namespace(&self, h: &str) -> Result<Option<Namespace>> { self.0.namespace(h) }
///     fn namespaces(&self) -> Result<Vec<Namespace>> { self.0.namespaces() }
///     fn record_namespace_failure(&self, h: &str, a: &str, n: u32) -> Result<Option<Namespace>> { self.0.record_namespace_failure(h, a, n) }
///     fn record_namespace_success(&self, h: &str, a: &str) -> Result<Option<Namespace>> { self.0.record_namespace_success(h, a) }
///     fn bind_name(&self, n: &str, f: &str, t: &str) -> Result<()> { self.0.bind_name(n, f, t) }
///     fn resolve_name(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_name(n, a) }
///     fn resolve_binding(&self, n: &str, a: &str) -> Result<Option<Binding>> { self.0.resolve_binding(n, a) }
///     fn put_class(&self, b: &[u8]) -> Result<String> { self.0.put_class(b) }
///     fn class(&self, h: &str) -> Result<Option<Vec<u8>>> { self.0.class(h) }
///     fn bind_class(&self, n: &str, h: &str, t: &str) -> Result<()> { self.0.bind_class(n, h, t) }
///     fn resolve_class(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_class(n, a) }
///     fn resolve_class_binding(&self, n: &str, a: &str) -> Result<Option<ClassBinding>> { self.0.resolve_class_binding(n, a) }
///     fn put_computed(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_computed(c, t, r) }
///     fn computed_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.computed_asof(c, a) }
///     fn stored_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.stored_asof(c, a) }
///     fn cell_dependents(&self, c: &str) -> Result<Vec<String>> { self.0.cell_dependents(c) }
///     fn put_manifest(&self, b: &[u8]) -> Result<String> { self.0.put_manifest(b) }
///     fn member_manifests(&self, r: &str) -> Result<Vec<String>> { self.0.member_manifests(r) }
///     fn slice_entries(&self, r: &str) -> Result<Vec<String>> { self.0.slice_entries(r) }
///     fn slice_dependents(&self, e: &str) -> Result<Vec<String>> { self.0.slice_dependents(e) }
///     fn slice_members(&self, s: &Slice, a: &str) -> Result<Vec<SliceMember>> { self.0.slice_members(s, a) }
///     fn versions_between(&self, c: &str, f: &str, t: &str, a: &str) -> Result<Vec<SliceMember>> { self.0.versions_between(c, f, t, a) }
///     fn slice_values(&self, s: &Slice, a: &str) -> Result<Vec<SliceValue>> { self.0.slice_values(s, a) }
///     fn slice_changed_after(&self, s: &Slice, a: &str) -> Result<bool> { self.0.slice_changed_after(s, a) }
///     fn computed_cells(&self, s: &Slice, a: &str, n: usize) -> Result<Vec<Cell>> { self.0.computed_cells(s, a, n) }
///     fn has_bindings_under(&self, n: &str) -> Result<bool> { self.0.has_bindings_under(n) }
/// }
/// ```
pub trait Store: Resolver + sealed::Sealed {
    /// Stores a descriptor (checked and canonicalised by the core); returns its function
    /// hash. Idempotent.
    fn put_descriptor(&self, bytes: &[u8]) -> Result<String>;
    /// Stores a receipt that verifies (SPEC 10.1 steps 1-6) against the key document stored
    /// for its signer host with [`put_namespace`](Store::put_namespace), in canonical form,
    /// with an edge to each of its inputs; returns its hash. An input that is a slice entry
    /// (`slice:<slice id>:<members hash>`, since 0.3.1) is recorded as such
    /// ([`slice_entries`](Store::slice_entries)); its manifest need not be stored, before or
    /// after (it is needed only to recompute, SPEC 10.1 step 7.5). The receipt's cell is
    /// indexed by its typed arguments ([`slice_members`](Store::slice_members)). A receipt that does not verify
    /// is refused with `verify`'s code (no key document for the host: `E_KEY_UNAVAILABLE`).
    /// Idempotent: bytes whose canonical form is the stored copy return its hash without
    /// checking the signature again (it verified when stored), even if the key has since
    /// been revoked. Other bytes with a stored hash are verified first, then refused as
    /// [`Error::Conflict`].
    fn put_receipt(&self, bytes: &[u8]) -> Result<String>;
    /// Stores blob content; returns its SHA-256 (lowercase hex). Idempotent.
    fn put_blob(&self, bytes: &[u8]) -> Result<String>;
    /// Blob content by SHA-256.
    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>>;
    /// Appends a version: from `tx` on, `cell_id` has the value of receipt `receipt_hash`,
    /// which must be stored, of that cell and at that tx. `tx` must be later than the cell's
    /// latest version ([`Error::NotLater`]).
    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
    /// The cell's latest version with `tx <= asof`.
    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
    /// The cell's versions with `from <= tx <= to`, in tx order.
    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>>;
    /// The cell's latest version.
    fn latest(&self, cell_id: &str) -> Result<Option<Version>>;
    /// [`latest`](Store::latest) of each of `cell_ids`, in input order (duplicates allowed;
    /// empty input, empty result). The first malformed id is the error. Since 0.4.3.
    fn latest_many(&self, cell_ids: &[&str]) -> Result<Vec<Option<Version>>> {
        cell_ids.iter().map(|id| self.latest(id)).collect()
    }
    /// [`receipt`](Resolver::receipt) of each of `hashes`, in input order, as owned bytes.
    /// Since 0.4.3.
    fn receipts_many(&self, hashes: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
        Ok(hashes.iter().map(|h| self.receipt(h).map(|b| b.into_owned())).collect())
    }
    /// For each item in order, [`put_receipt`](Store::put_receipt) and then, when the item
    /// has a `version`, [`put_version`](Store::put_version); returns the receipt hashes.
    /// All or nothing on PostgreSQL (one transaction; calls of up to 10,000 items are the
    /// size it is written for). SQLite (and this default) loops, stops at the first error,
    /// and need not be atomic: the items before a failing one stay stored there. Since 0.4.3.
    fn put_cells(&self, items: &[CellWrite<'_>]) -> Result<Vec<String>> {
        items
            .iter()
            .map(|w| {
                let hash = self.put_receipt(w.receipt)?;
                if let Some((cell_id, tx)) = w.version {
                    self.put_version(cell_id, tx, &hash)?;
                }
                Ok(hash)
            })
            .collect()
    }
    /// The stored receipts that list `receipt_hash` among their inputs, by hash. Only as
    /// an input of its own: a receipt read as a member of a slice is found through its
    /// manifests ([`member_manifests`](Store::member_manifests), then
    /// [`slice_dependents`](Store::slice_dependents)).
    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>>;
    /// The inputs of a stored receipt that are receipt hashes (whether or not they are
    /// stored). Its slice entries are [`slice_entries`](Store::slice_entries).
    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>>;
    /// Records a host's key document, checked as a 200 response for that host would be
    /// (SPEC 9.2, 9.3), validated at `validated_at`. Re-validation replaces the document; a
    /// `validated_at` earlier than the recorded one is [`Error::NotLater`]. Receipts already
    /// stored are not re-checked: they verified when they were stored (and putting one again
    /// stays idempotent).
    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()>;
    /// A host's recorded key document.
    fn namespace(&self, host: &str) -> Result<Option<Namespace>>;
    /// Every recorded namespace, by host. Since the namespace checks (since 0.4.1).
    fn namespaces(&self) -> Result<Vec<Namespace>>;
    /// Records a failed check of `host`'s key document at `checked_at` (domain validation):
    /// the consecutive failures grow by one, and when they reach `threshold` (zero counts as
    /// one) the namespace is suspended at `checked_at`, unless it already is (the first
    /// suspension's time is kept). While it is suspended the store refuses new writes under
    /// the host: `put_receipt` of a receipt signed by it, `put_version` of such a receipt
    /// and `bind_name` of a name under it ([`Error::NamespaceSuspended`]); reads,
    /// verification and the stored key document are not affected, and neither is putting a
    /// receipt that is already stored. Returns the namespace as recorded, or `None` for a
    /// host with no namespace (there is nothing to suspend). A `checked_at` earlier than the
    /// latest check is [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>>;
    /// Records a successful check of `host`'s key document at `checked_at`: the consecutive
    /// failures are reset to zero and a suspension is lifted (the namespace is reinstated).
    /// The document itself is recorded with [`put_namespace`](Store::put_namespace) (which
    /// neither suspends nor reinstates). Returns the namespace as recorded, or `None` for a
    /// host with no namespace. A `checked_at` earlier than the latest check is
    /// [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>>;
    /// Appends a binding: from `tx` on, the fully qualified function name `fn_name` means
    /// `fn_hash`, whose descriptor must be stored. `tx` must be later than the name's latest
    /// binding ([`Error::NotLater`]).
    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()>;
    /// The function hash `fn_name` meant as of `asof`: the hash of
    /// [`resolve_binding`](Store::resolve_binding)'s binding.
    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>>;
    /// The binding of `fn_name` that answers as of `asof`: the one with the latest `tx <=
    /// asof`, with its function hash and its `tx`, when it began; `None` before the first.
    /// A name bound again to a hash it meant before (even the hash of the binding before
    /// it) begins again: the later binding's `tx`. Since 0.3.0.
    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>>;

    /// Stores a class descriptor (SPEC 16.1, 16.2) under its class hash and returns the hash.
    /// Since 0.4.1.
    ///
    /// `bytes` must be a **flattened** descriptor in **canonical form** (the bytes
    /// `ClassDescriptor::canonical` gives, 6.2: what the class hash hashes). The core checks it
    /// (`ClassDescriptor::from_json`: strict JSON, then 16.1 in its check order; a flattened
    /// descriptor passes). Bytes that are a valid descriptor but not the canonical form of
    /// it (white space, members out of order) are refused with [`Error::Invalid`], code
    /// `E_SCHEMA`, and nothing is stored: unlike [`put_descriptor`](Store::put_descriptor),
    /// which canonicalises, the bytes put are the bytes stored, so the class hash is the
    /// SHA-256 of what [`class`](Store::class) returns. Idempotent for the same bytes.
    ///
    /// The store does not flatten (that is define's, with the parent in hand), and does not
    /// need the parent, the method functions or the interfaces to be stored (`bind_class`
    /// needs the methods' descriptors). It does not check the owner either (16.2 step 1 is the
    /// definer's check: the store records, http and the engine enforce). It is a write under
    /// the class's steward namespace (`steward.namespace`): refused with
    /// [`Error::NamespaceSuspended`] while that namespace is suspended, even for a class
    /// already stored.
    fn put_class(&self, bytes: &[u8]) -> Result<String>;
    /// The canonical bytes of the class descriptor with this class hash, as stored
    /// ([`put_class`](Store::put_class)); `None` when no such class is stored. A malformed
    /// hash is `E_CANON_HEX`. Never refused under a suspended namespace. Since 0.4.1.
    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>>;
    /// Binds the class name `class_name` (a full name, 2.3) to the stored class `class_hash`
    /// from `tx` on and, in the same transaction, binds each method `<class_name>/<m>` of the
    /// stored (flattened, so inherited methods included) descriptor to the method's function
    /// hash from the same `tx` (SPEC 16.3, 9.7). All of it or nothing:
    ///
    /// - the class must be stored ([`Error::NotFound`], `what` `"class"`), and so must every
    ///   method's function descriptor ([`Error::NotFound`], `what` `"descriptor"`, the missing
    ///   function hash; the first in JCS order of method names);
    /// - class names and function names share one namespace of names: `class_name`, or a
    ///   method name, whose latest binding is of the other kind (a function for `class_name`,
    ///   a class for a method name) is refused with [`Error::NameTaken`]. A method name bound
    ///   as a function, to whatever hash, is simply bound again;
    /// - `tx` must be later than the latest binding of `class_name` and of each method name
    ///   ([`Error::NotLater`], `what` `"name"`, the name that is not);
    /// - while the namespace of `class_name`'s host is suspended: [`Error::NamespaceSuspended`].
    ///
    /// The store does not check that the class name is under the steward's namespace, nor
    /// who binds it (the definer's check, 16.2 step 1). Since 0.4.1.
    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()>;
    /// The class hash `class_name` meant as of `asof`: the hash of
    /// [`resolve_class_binding`](Store::resolve_class_binding)'s binding. `None` before the
    /// first binding, and for a name whose binding as of `asof` is a function's. Since 0.4.1.
    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>>;
    /// The class binding of `class_name` that answers as of `asof`: the latest with
    /// `tx <= asof`, with its class hash and its `tx` (when it began; binding the same hash
    /// again begins again), as [`resolve_binding`](Store::resolve_binding) does for functions.
    /// `None` before the first, and for a function name. The function accessors
    /// ([`resolve_name`](Store::resolve_name), [`resolve_binding`](Store::resolve_binding))
    /// answer `None` for a class name: a bindings answer (9.7) has `fn_hash` or `class_hash`,
    /// never both. Since 0.4.1.
    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>>;

    /// Records that `receipt_hash` (stored, a receipt of `cell_id` at `tx`) is a computed
    /// version of the cell. Insert-only, in any order (an older version may be added after a
    /// newer one): `tx` need not be later than anything. The version's asof is the
    /// receipt's. Idempotent for the same (cell_id, tx, asof, receipt_hash); another receipt
    /// for an existing (cell_id, tx, asof) is [`Error::Conflict`] (its `hash` is the receipt
    /// refused) and the stored one is kept. The receipt is checked as for
    /// [`put_version`](Store::put_version): [`Error::NotFound`] when it is not stored,
    /// [`Error::Mismatch`] when it is of another cell or at another tx. Since 0.2.0.
    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
    /// The computed version that answers as of `asof`: the one with the greatest asof <=
    /// `asof` (between equal asof, the greatest tx), or `None`. Since 0.2.0.
    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
    /// The stored version that answers as of `asof`: the latest version (by tx) with `tx <=
    /// asof` whose receipt's asof is also `<= asof`, or `None`. A version whose receipt is
    /// late-signed (asof later than tx) answers only from its asof on; until then the
    /// version before it answers. ([`version_asof`](Store::version_asof) keeps its tx-only
    /// meaning.) Since 0.2.0.
    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
    /// The cells that read `cell_id`: the cell ids of the stored receipts that list, among
    /// their inputs, any stored receipt of `cell_id` (lineage: edges joined to receipts),
    /// or (since 0.3.1) a slice entry whose stored manifest lists one as a member.
    /// Ascending, each once. Since 0.2.0.
    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>>;

    /// Stores a manifest (SPEC 15.13), `{"members": [...], "slice": {...}}`: parsed strictly
    /// and checked by the core (`Manifest::from_json`: structure, members, their order and
    /// limit, the slice object), kept in canonical form under its entry
    /// `slice:<slice id>:<members hash>`, which it returns, and recorded for each member
    /// ([`member_manifests`](Store::member_manifests)). The members need not be stored.
    /// Idempotent; insert-only (the entry is a hash of the content, so a stored entry
    /// always has these bytes). Served by [`manifest`](Resolver::manifest). Since 0.3.1.
    fn put_manifest(&self, bytes: &[u8]) -> Result<String>;
    /// The entries of the stored manifests that list `receipt_hash` among their members,
    /// ascending: from a member, the slices it was read in (then
    /// [`slice_dependents`](Store::slice_dependents)). Since 0.3.1.
    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>>;
    /// The slice entries among the inputs of a stored receipt, ascending. Since 0.3.1.
    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>>;
    /// The stored receipts whose inputs list the slice entry `entry`, by hash, ascending.
    /// An entry is `slice:` and two 64-digit hashes (`E_CANON_HEX` otherwise). Since 0.3.1.
    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>>;
    /// The members of `slice` as of `asof` (SPEC 15.13), with the stored version of each
    /// that answers as of `asof` and its receipt's bytes.
    ///
    /// For a slice of cells: the cells of the slice's function (its `fn_hash`, `ns` and
    /// `fn`, with the same argument names) whose bound arguments are the same typed scalar,
    /// whose ranged arguments are of the range's type and within it (`lo <= v <= hi`,
    /// inclusive, in the type's order: numbers as exact decimals, dates and instants
    /// chronologically, strings by code point; `lo` after `hi` is empty), any value for an
    /// open argument, and that have a stored version answering as of `asof`: as
    /// [`stored_asof`](Store::stored_asof), the latest version with `tx <= asof` whose
    /// receipt's `asof <= asof` (so a late-signed version is not a member's answer before
    /// its asof, and a correction replaces a member's version from its asof on). Computed
    /// versions are not members. In key order: by the open and ranged arguments in
    /// ascending name order, each in its type's order (`false` before `true`; blobs as
    /// text); the cell id last, for two cells whose key arguments are of different types.
    ///
    /// For a version slice `{"cell", "from", "to"}`: [`versions_between`](Store::versions_between)
    /// of its cell. Empty when nothing matches. Since 0.3.1.
    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>>;
    /// The stored versions of `cell_id` with `from <= tx <= to` that answer as of `asof`
    /// (`tx <= asof` and the receipt's `asof <= asof`), ascending by tx, each with its
    /// receipt's bytes: SPEC 15.13's version slice. Empty when `from` is after `to`. Since
    /// 0.3.1.
    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>>;
    /// The members [`slice_members`](Store::slice_members) gives, in its order and by its
    /// answering rule, each as its version, its receipt's typed value and its cell (with its
    /// arguments), without the receipt's bytes (the value is a stored column of the receipt
    /// and the cell comes from the typed-argument index, neither parsed per call).
    /// Since 0.3.2.
    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>>;
    /// Whether the members of `slice`, or their versions, may answer differently as of some
    /// time after `asof`: whether a cell matching the slice has a stored version whose
    /// receipt's `asof` is after `asof` (its `tx` is never later than that), for a version
    /// slice one with `tx` in `[from, to]`. `false` means [`slice_members`](Store::slice_members)
    /// (and `slice_values`) give the same answer as of every time from `asof` on, until a
    /// version is stored with an asof after it; `true` may be conservative (a late-signed
    /// version superseded before its asof never answers). Index scans only, whatever the
    /// slice's size: two bounded probes (at most 10,001 entries each) choose whether to walk
    /// the function's receipts with an asof after `asof` or the slice's candidate cells,
    /// whichever is fewer, and one query walks it, stopping at the first match. Since 0.3.2.
    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool>;
    /// The cells of `slice` (matched as [`slice_values`](Store::slice_values) matches them: the
    /// fixed arguments, `fn_hash`, `ns`, `fn` and the number of arguments) that have a computed
    /// version answering as of `asof`: one with `tx <= asof` whose receipt's asof is `<= asof`
    /// (the rule of [`computed_asof`](Store::computed_asof)). Ascending by cell id, at most
    /// `limit` (`slice_values` takes no limit), each with its arguments from the typed-argument
    /// index. A cell with only a stored version is not returned. Since 0.4.2.
    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>>;
    /// Whether any name binding or class binding has a name starting with `namespace` and `/`
    /// (so `"a.example/n"` is not a namespace of `"a.example/ns/f"`). Since 0.4.2.
    fn has_bindings_under(&self, namespace: &str) -> Result<bool>;

    /// [`computed_asof`](Store::computed_asof) and the bytes of the version's receipt (as
    /// [`receipt`](Resolver::receipt) returns them), which is what a caller reads next.
    /// The default asks for the two in turn (a receipt that cannot be read then is
    /// [`Error::NotFound`]); [`PgStore`] and [`SqliteStore`] answer both with one query.
    /// Since 0.2.0.
    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
        match self.computed_asof(cell_id, asof)? {
            Some(v) => with_receipt(self, v).map(Some),
            None => Ok(None),
        }
    }
    /// [`stored_asof`](Store::stored_asof) and the bytes of the version's receipt, as
    /// [`computed_asof_with_receipt`](Store::computed_asof_with_receipt) does. Since 0.2.0.
    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
        match self.stored_asof(cell_id, asof)? {
            Some(v) => with_receipt(self, v).map(Some),
            None => Ok(None),
        }
    }
}

/// The seal of [`Store`]: a public trait in a private module, so no other crate can name it,
/// and so none can implement `Store`.
mod sealed {
    pub trait Sealed {}
    impl Sealed for crate::PgStore {}
    #[cfg(feature = "sqlite")]
    impl Sealed for crate::SqliteStore {}
}

/// A version and its receipt's bytes, for the default `*_with_receipt` methods.
fn with_receipt<S: Store + ?Sized>(store: &S, v: Version) -> Result<(Version, Cow<'_, [u8]>)> {
    match store.receipt(&v.receipt_hash) {
        Some(bytes) => Ok((v, bytes)),
        None => Err(Error::NotFound { what: "receipt", key: v.receipt_hash }),
    }
}