Skip to main content

datumesh_store/
lib.rs

1//! A store for [Datumesh](https://datumesh.com): function descriptors, receipts, blobs,
2//! versions of cells over transaction time, lineage, namespaces and function names, on
3//! PostgreSQL or (since 0.4.0) in one SQLite file. [`PgStore`] and [`SqliteStore`] implement
4//! [`Store`], and through it `datumesh_core`'s [`Resolver`], so `datumesh_core::verify` can
5//! recompute receipts of stored cells from either; the two behave the same (one
6//! conformance suite runs against both).
7//!
8//! The API is synchronous (the `postgres` driver and a small connection pool; `rusqlite`
9//! with SQLite compiled in, feature `sqlite`, on by default). Async callers run it on a
10//! blocking thread, e.g. `tokio::task::spawn_blocking`.
11//!
12//! [`SqliteStore::open`] takes a file path ([`SqliteStore::connect`] a `sqlite:` URL); the
13//! file is in WAL mode, every write is one `BEGIN IMMEDIATE` transaction, and the
14//! append-only rules are triggers in the file, so they hold for writers in several
15//! threads and processes on one machine. Its schema comes from [`migrate::sqlite::apply`].
16//!
17//! [`PgStore::connect`] / [`PgStore::connect_with`] take a URL and [`PoolOptions`]; TLS
18//! (rustls) is used as the URL's `sslmode` says and always verifies the server's
19//! certificate and host name, against the Mozilla roots plus those added with
20//! [`PoolOptions::tls_root_certificates_pem`]. No type of the driver or of a TLS crate is
21//! part of the API, except in [`pg_unstable`] (any connection function, the driver
22//! itself), which is outside semver until 1.0.
23//!
24//! What is stored, and how:
25//!
26//! * Descriptors are checked by the core (`FunctionDescriptor::from_json`: since 0.3.1,
27//!   spec-0.4.0's, with `signature.order` and argument `extent`) and stored in canonical
28//!   form (JCS) under their hash. Receipts are verified (`datumesh_core::verify`, SPEC 10.1
29//!   steps 1-6) against the key document stored for their signer host, so nothing
30//!   unverified enters the store, and are stored canonical under their hash. Storing the
31//!   same thing twice stores it once. A second, different valid signature over the same
32//!   payload (possible only with a randomised signer: the payload names the key, so a
33//!   rotated key gives a new hash) is refused ([`Error::Conflict`]) and the stored receipt
34//!   kept.
35//! * Blobs are stored in the database, under the SHA-256 of their content.
36//! * Versions: from transaction time `tx` on, cell `cell_id` has the value of a receipt.
37//!   Append-only and in tx order per cell, enforced by the database (triggers) as well as by
38//!   [`Store::put_version`], which also checks that the receipt is stored and is of that
39//!   cell at that tx.
40//! * Computed versions: from transaction time `tx` on, cell `cell_id` has the value a
41//!   receipt computed, as of the receipt's asof. Derived rather than facts, so they are
42//!   added in any order, keyed on (cell, tx, asof), insert-only
43//!   ([`Store::put_computed`], [`Store::computed_asof`]).
44//! * Answering as of A: a receipt answers as of A only when its `tx` and its `asof` are
45//!   both at or before A ([`Store::stored_asof`], and the [`Resolver`]'s `evaluate` of a
46//!   stored function; [`Store::version_asof`] looks at `tx` only).
47//! * Lineage: `put_receipt` records an edge to each of the receipt's `inputs`, held or not:
48//!   receipt hashes ([`Store::inputs`], [`Store::dependents`]) and, since 0.3.1, slice
49//!   entries ([`Store::slice_entries`], [`Store::slice_dependents`]);
50//!   [`Store::cell_dependents`] lifts both to cells.
51//! * Slices (0.3.1, SPEC 15.13): every stored receipt's cell is indexed by its typed
52//!   arguments, so that [`Store::slice_members`] finds the members of a slice as of A with
53//!   a range scan, in key order; [`Store::versions_between`] gives a version slice.
54//!   [`Store::slice_values`] gives the members' values without receipts (0.3.2) and
55//!   [`Store::slice_changed_after`] whether they may answer differently later.
56//!   Manifests ([`Store::put_manifest`], served by [`Resolver::manifest`]) are kept by
57//!   entry and found from each member ([`Store::member_manifests`]). A receipt citing a
58//!   slice can be stored before its manifest, and a manifest before its members.
59//! * Namespaces: a host's key document (checked as SPEC 9.2 requires), with when it was
60//!   validated. Store it before the host's receipts. Replacing it later (a key revoked or
61//!   dropped) does not touch receipts already stored: they verified when they were stored,
62//!   and putting one of them again is still idempotent.
63//! * Names: which function hash a fully qualified function name meant from a transaction
64//!   time on. Append-only, like versions. [`Store::resolve_binding`] gives the binding
65//!   answering as of A with when it began; [`Store::resolve_name`] its hash.
66//! * Classes (0.4.1, SPEC 16.1 to 16.3): a flattened class descriptor, checked by the core and
67//!   stored canonical under its class hash ([`Store::put_class`], [`Store::class`]). A class
68//!   name is bound over transaction time to a class hash, and binding it binds each method
69//!   `<class name>/<m>` to the method's function hash in the same transaction
70//!   ([`Store::bind_class`], [`Store::resolve_class`], [`Store::resolve_class_binding`]).
71//!   Class names and function names are one namespace: a name bound as one kind cannot be
72//!   bound as the other ([`Error::NameTaken`]).
73//! * Owner: a class's owner is the definer's check (SPEC 16.2 step 1), made when the class is
74//!   defined, not the store's. The store records what it is given; the HTTP service and the
75//!   engine enforce the owner rule. [`Store::put_class`] and [`Store::bind_class`] do not take a
76//!   key document or check the name against the steward.
77//! * Namespace suspension (since 0.4.1): new writes under a suspended namespace are refused
78//!   with [`Error::NamespaceSuspended`] (`put_class`: the steward's namespace; `bind_class`: the
79//!   host of the class name); reads are never refused.
80//!
81//! Instants are compared as text (fixed width, `COLLATE "C"`; SQLite's default collation
82//! is the same byte order), which is exact; on PostgreSQL each is also stored as
83//! `timestamptz`, which round-trips every instant of the specification exactly. Numbers in
84//! the typed-argument index compare as exact decimals (PostgreSQL `numeric`; on SQLite a
85//! text encoding that sorts as the decimal does).
86//!
87//! Every [`Store`] method returns a `Result`: a malformed argument is [`Error::Invalid`] with
88//! the core's code, a database failure [`Error::Database`]. The [`Resolver`] methods keep the
89//! core's `Option` signatures; there a failure is logged with `tracing` (target
90//! `datumesh_store`) and answered `None`, which `verify` reports as unavailable.
91//!
92//! [`Store`] is sealed: only this crate implements it. The store is the trust boundary:
93//! everything in it was checked on the way in (every receipt verified against its host's
94//! key document), and its callers rely on that rather than checking again. A `dyn Store`
95//! is still a trait object as before.
96//!
97//! The schema comes from [`migrate::apply`] (PostgreSQL) or [`migrate::sqlite::apply`]
98//! (SQLite) (the `datumesh-store migrate` command, for either), through a store on the
99//! (possibly empty) database.
100
101#![forbid(unsafe_code)]
102#![deny(missing_docs)]
103
104use std::borrow::Cow;
105
106pub use datumesh_core::Resolver;
107use datumesh_core::{Cell, Scalar, Slice};
108
109mod catalogue;
110mod error;
111mod functions;
112pub mod migrate;
113mod pg;
114pub mod pg_unstable;
115mod pool;
116mod slices;
117mod sql;
118#[cfg(feature = "sqlite")]
119mod sqlite;
120#[cfg(feature = "sqlite")]
121mod sqlite_sql;
122mod tls;
123
124pub use catalogue::{
125    CatalogEntry, CatalogEntryExt, CatalogKind, CatalogSource, Dictionary, DictionaryValue, EmbedRef, Embedding,
126    FacetedEntry, Facets, Hit, KeyValue, PendingEmbedding, Summary, SummaryEntry, FIND_MISSES_CAP,
127};
128pub use error::{DatabaseError, Error, Result};
129pub use pg::PgStore;
130pub use pool::PoolOptions;
131#[cfg(feature = "sqlite")]
132pub use sqlite::{SqliteOptions, SqliteStore};
133
134/// The sort key of a cell (CONTRACT-0.5.1 S1; SPEC 5.6 and 15.13): its arguments as
135/// `(name, type, lexical form)`, in ascending name order, encoded as `cells.sort_key` is stored
136/// (the same bytes on PostgreSQL and SQLite) and as [`SliceValue::sort_key`] returns them. Keys
137/// compare as bytes. An empty `args` gives the empty key of a cell with no arguments. Since
138/// 0.6.4.
139pub fn sort_key(args: &[(&str, &str, &str)]) -> Vec<u8> {
140    let mut sorted: Vec<&(&str, &str, &str)> = args.iter().collect();
141    sorted.sort_by(|a, b| a.0.cmp(b.0));
142    sorted.iter().flat_map(|(_, ty, value)| slices::sort_item(ty, value)).collect()
143}
144
145/// A version of a cell: from transaction time `tx` on, the cell's value is that of the
146/// receipt `receipt_hash`, which states it as of `asof`.
147///
148/// A stored version ([`Store::put_version`]) or a computed one ([`Store::put_computed`]).
149#[non_exhaustive]
150#[derive(Clone, Debug, PartialEq, Eq, Hash)]
151pub struct Version {
152    /// The cell id.
153    pub cell_id: String,
154    /// The transaction time (an instant, SPEC 3.3).
155    pub tx: String,
156    /// The receipt stating the value.
157    pub receipt_hash: String,
158    /// The receipt's `asof` (an instant; never earlier than `tx`). Since 0.2.0.
159    pub asof: String,
160    /// Whether the receipt is a withdrawal (8.1): the cell has no value from `asof` on. Since
161    /// 0.6.0; always `false` for a computed version.
162    pub withdrawn: bool,
163}
164
165/// One cell write of [`Store::put_cells`]: a receipt and, optionally, the version it
166/// becomes. Since 0.4.3.
167#[non_exhaustive]
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub struct CellWrite<'a> {
170    /// The receipt's JSON bytes, as for `put_receipt`.
171    pub receipt: &'a [u8],
172    /// `Some((cell_id, tx))`: also `put_version(cell_id, tx, <this receipt's hash>)`.
173    pub version: Option<(&'a str, &'a str)>,
174}
175
176impl<'a> CellWrite<'a> {
177    /// A cell write of `receipt` and, when `version` is `Some((cell_id, tx))`, its version.
178    pub fn new(receipt: &'a [u8], version: Option<(&'a str, &'a str)>) -> Self {
179        CellWrite { receipt, version }
180    }
181}
182
183/// A member of a slice ([`Store::slice_members`], [`Store::versions_between`]): a stored
184/// version and the bytes of its receipt (as [`receipt`](Resolver::receipt) returns them).
185/// Since 0.3.1.
186#[non_exhaustive]
187#[derive(Clone, Debug, PartialEq, Eq, Hash)]
188pub struct SliceMember {
189    /// The version answering (its cell, tx, receipt hash and asof).
190    pub version: Version,
191    /// The receipt's bytes, canonical JSON.
192    pub receipt: Vec<u8>,
193}
194
195/// A member of a slice with its value and without its receipt's bytes
196/// ([`Store::slice_values`]). Since 0.3.2.
197#[non_exhaustive]
198#[derive(Clone, Debug, PartialEq, Eq, Hash)]
199pub struct SliceValue {
200    /// The version answering (its cell, tx, receipt hash and asof).
201    pub version: Version,
202    /// The receipt's typed value.
203    pub value: Scalar,
204    /// The member's cell, with its arguments (from the store's typed-argument index; equal
205    /// to the receipt's `cell`, and `cell.id()` is `version.cell_id`).
206    pub cell: Cell,
207    /// The member's sort key (the cell's, see [`Store::slice_page`]): the byte order of the
208    /// keys is the order of [`Store::slice_values`]. Since 0.6.4.
209    pub sort_key: Vec<u8>,
210}
211
212/// A name binding: from transaction time `tx` on, a fully qualified function name means the
213/// function `fn_hash` ([`Store::bind_name`]). Since 0.3.0.
214#[non_exhaustive]
215#[derive(Clone, Debug, PartialEq, Eq, Hash)]
216pub struct Binding {
217    /// The function hash the name means.
218    pub fn_hash: String,
219    /// When the binding began: the transaction time from which the name means `fn_hash`
220    /// (an instant, SPEC 3.3).
221    pub tx: String,
222}
223
224/// A class-name binding: from transaction time `tx` on, a class name means the class
225/// `class_hash` ([`Store::bind_class`]). The class counterpart of [`Binding`]; the bindings
226/// answer of SPEC 9.7 gives `class_hash` in place of `fn_hash` for such a name. Since 0.4.1.
227#[non_exhaustive]
228#[derive(Clone, Debug, PartialEq, Eq, Hash)]
229pub struct ClassBinding {
230    /// The class hash the name means.
231    pub class_hash: String,
232    /// When the binding began (an instant, SPEC 3.3).
233    pub tx: String,
234}
235
236/// A function test: a canonical test line of a function, stored once per (function hash,
237/// case) ([`Store::put_function_test`]). The run fields are set by
238/// [`Store::record_function_test`]; the branch counts by [`Store::set_function_branches`],
239/// which keeps them equal on every test of the function. Since 0.5.1.
240#[non_exhaustive]
241#[derive(Clone, Debug, PartialEq, Eq)]
242pub struct FunctionTest {
243    /// The function hash the test is of (64 lowercase hex digits).
244    pub fn_hash: String,
245    /// The case: 16 lowercase hex digits. Tests of a function are ordered by it.
246    pub case: String,
247    /// The test line, canonical (JCS) JSON.
248    pub test_json: Vec<u8>,
249    /// The host or key id that wrote the test. The first writer's: a later one changes nothing.
250    pub signed_by: String,
251    /// When the test last ran (an instant), if it has.
252    pub last_run_at: Option<String>,
253    /// The result of the last run: `pass`, `fail` or `error`.
254    pub last_result: Option<String>,
255    /// The detail of the last run.
256    pub last_detail: Option<String>,
257    /// The branches of the function (the same on every test of the function).
258    pub branches_total: u32,
259    /// The branches the function's tests cover (the same on every test of the function).
260    pub branches_covered: u32,
261}
262
263impl FunctionTest {
264    /// A test that has not run, with no branch counts: the run fields are `None` and the
265    /// counts zero. Since 0.5.1.
266    pub fn new(fn_hash: &str, case: &str, test_json: &[u8], signed_by: &str) -> FunctionTest {
267        FunctionTest {
268            fn_hash: fn_hash.to_string(),
269            case: case.to_string(),
270            test_json: test_json.to_vec(),
271            signed_by: signed_by.to_string(),
272            last_run_at: None,
273            last_result: None,
274            last_detail: None,
275            branches_total: 0,
276            branches_covered: 0,
277        }
278    }
279}
280
281/// The results of a function's tests ([`Store::function_test_summary`]): how many there are,
282/// how many passed, failed, errored or have not run, the latest run and the branch counts.
283/// `Default` is the summary of no tests (all zero, no run). Since 0.5.2.
284#[non_exhaustive]
285#[derive(Clone, Debug, Default)]
286pub struct TestSummary {
287    /// The tests counted.
288    pub count: u64,
289    /// The tests whose last run passed.
290    pub pass: u64,
291    /// The tests whose last run failed.
292    pub fail: u64,
293    /// The tests whose last run errored.
294    pub error: u64,
295    /// The tests that have not run (no last result).
296    pub not_run: u64,
297    /// The latest `last_run_at` of the tests, if any has run (an instant; instants compare as
298    /// text).
299    pub last_run_at: Option<String>,
300    /// The branches of the function (the value replicated on its tests; 0 when none).
301    pub branches_total: u32,
302    /// The branches covered by the function's tests (replicated as `branches_total`).
303    pub branches_covered: u32,
304}
305
306/// A namespace's host and its key document.
307#[non_exhaustive]
308#[derive(Clone, Debug, PartialEq, Eq, Hash)]
309pub struct Namespace {
310    /// The host (a DNS name).
311    pub host: String,
312    /// The key document, canonical (JCS).
313    pub keydoc: Vec<u8>,
314    /// When the document was last retrieved and checked.
315    pub validated_at: String,
316    /// When the namespace was suspended, if it is: the single record of suspension. Set by
317    /// [`record_namespace_failure`](Store::record_namespace_failure) when the consecutive
318    /// failures reach its threshold, cleared by
319    /// [`record_namespace_success`](Store::record_namespace_success). While it is set the
320    /// store refuses new writes under the host ([`Error::NamespaceSuspended`]).
321    pub suspended_at: Option<String>,
322    /// How many checks of the host's key document have failed in a row (zero after a
323    /// success). Since the namespace checks (since 0.4.1).
324    pub consecutive_failures: u32,
325    /// When the host's key document was last checked, successfully or not; `None` before
326    /// the first check recorded. Since the namespace checks (since 0.4.1).
327    pub last_checked_at: Option<String>,
328}
329
330/// The namespace after a check at `at`: a failed one (`threshold` is `Some`) adds to the
331/// consecutive failures and suspends at the threshold (an existing suspension keeps its
332/// time), a successful one (`None`) resets them and reinstates.
333/// The refusal of class descriptor bytes that are not the canonical form of the descriptor
334/// (`E_SCHEMA`, nothing stored): the class hash is the hash of the bytes stored, so only the
335/// canonical bytes are stored. Shared by both backends (since 0.4.1).
336pub(crate) fn not_canonical_class() -> Error {
337    Error::Invalid(datumesh_core::Error::new(
338        datumesh_core::ErrorCode::Schema,
339        "$",
340        "class descriptor is not in canonical form (JCS): put the canonical bytes",
341    ))
342}
343
344pub(crate) fn apply_check(ns: &mut Namespace, at: &str, threshold: Option<u32>) {
345    ns.last_checked_at = Some(at.to_string());
346    match threshold {
347        None => {
348            ns.consecutive_failures = 0;
349            ns.suspended_at = None;
350        }
351        Some(t) => {
352            ns.consecutive_failures = ns.consecutive_failures.saturating_add(1);
353            if ns.suspended_at.is_none() && ns.consecutive_failures >= t.max(1) {
354                ns.suspended_at = Some(at.to_string());
355            }
356        }
357    }
358}
359
360/// A Datumesh store: a [`Resolver`] that can also be written to.
361///
362/// Instants are SPEC 3.3 instants (`YYYY-MM-DDTHH:MM:SS.ffffffZ`), hashes and cell ids 64
363/// lowercase hex digits, hosts DNS names and function names fully qualified. Every method,
364/// read or write, refuses anything else with the core's error code ([`Error::Invalid`]),
365/// and reports a database failure as [`Error::Database`] (or [`Error::PoolTimeout`]): a read
366/// answers `Ok(None)` / `Ok(vec![])` only when the store really holds nothing.
367///
368/// The [`Resolver`] methods keep the core's `Option` signatures: there a malformed argument
369/// or a database failure is `None` (logged with `tracing` when it is a failure), which
370/// `verify` reports as unavailable.
371///
372/// Only this crate implements `Store` (it is sealed, since 0.3.0; [`PgStore`] and, since
373/// 0.4.0, [`SqliteStore`]): the store is the trust boundary, where every receipt is verified against its host's key document before it is
374/// kept, and what a store answers is relied on as checked. An implementation elsewhere
375/// could answer anything. `Store` stays object-safe (`Arc<dyn Store + Send + Sync>`). Even a complete implementation that
376/// delegates every method to a [`PgStore`] is refused (`E0277`: the private supertrait is
377/// not implemented; `tests/sealed.rs` checks that this is the only error):
378///
379/// ```compile_fail
380/// use std::borrow::Cow;
381/// use datumesh_core::{Cell, Scalar};
382/// use datumesh_core::Slice;
383/// use datumesh_store::{Binding, CatalogEntry, ClassBinding, Embedding, FunctionTest, Hit, KeyValue, Namespace, PendingEmbedding, PgStore, Resolver, Result, SliceMember, SliceValue, Store, Summary, Version};
384///
385/// struct Wrapper(PgStore);
386/// impl Resolver for Wrapper {
387///     fn descriptor(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.descriptor(h) }
388///     fn receipt(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.receipt(h) }
389///     fn evaluate(&self, c: &Cell, a: &str) -> Option<Scalar> { self.0.evaluate(c, a) }
390///     fn manifest(&self, e: &str) -> Option<Cow<'_, [u8]>> { self.0.manifest(e) }
391/// }
392/// impl Store for Wrapper {
393///     fn put_descriptor(&self, b: &[u8]) -> Result<String> { self.0.put_descriptor(b) }
394///     fn put_receipt(&self, b: &[u8]) -> Result<String> { self.0.put_receipt(b) }
395///     fn put_blob(&self, b: &[u8]) -> Result<String> { self.0.put_blob(b) }
396///     fn blob(&self, s: &str) -> Result<Option<Cow<'_, [u8]>>> { self.0.blob(s) }
397///     fn put_version(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_version(c, t, r) }
398///     fn version_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.version_asof(c, a) }
399///     fn versions(&self, c: &str, f: &str, t: &str) -> Result<Vec<Version>> { self.0.versions(c, f, t) }
400///     fn latest(&self, c: &str) -> Result<Option<Version>> { self.0.latest(c) }
401///     fn dependents(&self, r: &str) -> Result<Vec<String>> { self.0.dependents(r) }
402///     fn inputs(&self, r: &str) -> Result<Vec<String>> { self.0.inputs(r) }
403///     fn put_namespace(&self, h: &str, k: &[u8], v: &str) -> Result<()> { self.0.put_namespace(h, k, v) }
404///     fn namespace(&self, h: &str) -> Result<Option<Namespace>> { self.0.namespace(h) }
405///     fn namespaces(&self) -> Result<Vec<Namespace>> { self.0.namespaces() }
406///     fn record_namespace_failure(&self, h: &str, a: &str, n: u32) -> Result<Option<Namespace>> { self.0.record_namespace_failure(h, a, n) }
407///     fn record_namespace_success(&self, h: &str, a: &str) -> Result<Option<Namespace>> { self.0.record_namespace_success(h, a) }
408///     fn bind_name(&self, n: &str, f: &str, t: &str) -> Result<()> { self.0.bind_name(n, f, t) }
409///     fn resolve_name(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_name(n, a) }
410///     fn resolve_binding(&self, n: &str, a: &str) -> Result<Option<Binding>> { self.0.resolve_binding(n, a) }
411///     fn put_class(&self, b: &[u8]) -> Result<String> { self.0.put_class(b) }
412///     fn class(&self, h: &str) -> Result<Option<Vec<u8>>> { self.0.class(h) }
413///     fn bind_class(&self, n: &str, h: &str, t: &str) -> Result<()> { self.0.bind_class(n, h, t) }
414///     fn resolve_class(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_class(n, a) }
415///     fn resolve_class_binding(&self, n: &str, a: &str) -> Result<Option<ClassBinding>> { self.0.resolve_class_binding(n, a) }
416///     fn put_computed(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_computed(c, t, r) }
417///     fn computed_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.computed_asof(c, a) }
418///     fn stored_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.stored_asof(c, a) }
419///     fn cell_dependents(&self, c: &str) -> Result<Vec<String>> { self.0.cell_dependents(c) }
420///     fn put_manifest(&self, b: &[u8]) -> Result<String> { self.0.put_manifest(b) }
421///     fn member_manifests(&self, r: &str) -> Result<Vec<String>> { self.0.member_manifests(r) }
422///     fn slice_entries(&self, r: &str) -> Result<Vec<String>> { self.0.slice_entries(r) }
423///     fn slice_dependents(&self, e: &str) -> Result<Vec<String>> { self.0.slice_dependents(e) }
424///     fn slice_members(&self, s: &Slice, a: &str) -> Result<Vec<SliceMember>> { self.0.slice_members(s, a) }
425///     fn versions_between(&self, c: &str, f: &str, t: &str, a: &str) -> Result<Vec<SliceMember>> { self.0.versions_between(c, f, t, a) }
426///     fn slice_values(&self, s: &Slice, a: &str) -> Result<Vec<SliceValue>> { self.0.slice_values(s, a) }
427///     fn slice_changed_after(&self, s: &Slice, a: &str) -> Result<bool> { self.0.slice_changed_after(s, a) }
428///     fn computed_cells(&self, s: &Slice, a: &str, n: usize) -> Result<Vec<Cell>> { self.0.computed_cells(s, a, n) }
429///     fn has_bindings_under(&self, n: &str) -> Result<bool> { self.0.has_bindings_under(n) }
430///     fn upsert_catalog(&self, e: &[CatalogEntry]) -> Result<Vec<i64>> { self.0.upsert_catalog(e) }
431///     fn upsert_key_values(&self, o: &str, k: &str, v: &[KeyValue]) -> Result<Vec<i64>> { self.0.upsert_key_values(o, k, v) }
432///     fn refresh_value_counts(&self) -> Result<u64> { self.0.refresh_value_counts() }
433///     fn text_find(&self, q: &str, l: usize) -> Result<Vec<Hit>> { self.0.text_find(q, l) }
434///     fn vector_find(&self, m: &str, v: &[f32], l: usize) -> Result<Vec<Hit>> { self.0.vector_find(m, v, l) }
435///     fn put_embeddings(&self, m: &str, i: &[Embedding]) -> Result<()> { self.0.put_embeddings(m, i) }
436///     fn pending_embeddings(&self, m: &str, l: usize) -> Result<Vec<PendingEmbedding>> { self.0.pending_embeddings(m, l) }
437///     fn vector_available(&self) -> bool { self.0.vector_available() }
438///     fn log_miss(&self, q: &str) -> Result<()> { self.0.log_miss(q) }
439///     fn catalog_summary(&self) -> Result<Summary> { self.0.catalog_summary() }
440///     fn put_function_test(&self, t: &FunctionTest) -> Result<bool> { self.0.put_function_test(t) }
441///     fn function_tests(&self, f: &str) -> Result<Vec<FunctionTest>> { self.0.function_tests(f) }
442///     fn record_function_test(&self, f: &str, c: &str, r: &str, res: &str, d: &str) -> Result<bool> { self.0.record_function_test(f, c, r, res, d) }
443///     fn set_function_branches(&self, f: &str, t: u32, c: u32) -> Result<()> { self.0.set_function_branches(f, t, c) }
444///     fn function_readers(&self, n: &str) -> Result<Vec<String>> { self.0.function_readers(n) }
445///     fn bound_names(&self, f: &str) -> Result<Vec<String>> { self.0.bound_names(f) }
446/// }
447/// ```
448pub trait Store: Resolver + sealed::Sealed {
449    /// Stores a descriptor (checked and canonicalised by the core); returns its function
450    /// hash. Idempotent.
451    fn put_descriptor(&self, bytes: &[u8]) -> Result<String>;
452    /// Stores a receipt that verifies (SPEC 10.1 steps 1-6) against the key document stored
453    /// for its signer host with [`put_namespace`](Store::put_namespace), in canonical form,
454    /// with an edge to each of its inputs; returns its hash. An input that is a slice entry
455    /// (`slice:<slice id>:<members hash>`, since 0.3.1) is recorded as such
456    /// ([`slice_entries`](Store::slice_entries)); its manifest need not be stored, before or
457    /// after (it is needed only to recompute, SPEC 10.1 step 7.5). The receipt's cell is
458    /// indexed by its typed arguments ([`slice_members`](Store::slice_members)). A receipt that does not verify
459    /// is refused with `verify`'s code (no key document for the host: `E_KEY_UNAVAILABLE`).
460    /// Idempotent: bytes whose canonical form is the stored copy return its hash without
461    /// checking the signature again (it verified when stored), even if the key has since
462    /// been revoked. Other bytes with a stored hash are verified first, then refused as
463    /// [`Error::Conflict`].
464    fn put_receipt(&self, bytes: &[u8]) -> Result<String>;
465    /// Stores blob content; returns its SHA-256 (lowercase hex). Idempotent.
466    fn put_blob(&self, bytes: &[u8]) -> Result<String>;
467    /// Blob content by SHA-256.
468    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>>;
469    /// Appends a version: from `tx` on, `cell_id` has the value of receipt `receipt_hash`,
470    /// which must be stored, of that cell and at that tx. `tx` must be later than the cell's
471    /// latest version ([`Error::NotLater`]).
472    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
473    /// The cell's latest version with `tx <= asof`.
474    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
475    /// The cell's versions with `from <= tx <= to`, in tx order.
476    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>>;
477    /// The cell's latest version.
478    fn latest(&self, cell_id: &str) -> Result<Option<Version>>;
479    /// [`latest`](Store::latest) of each of `cell_ids`, in input order (duplicates allowed;
480    /// empty input, empty result). The first malformed id is the error. Since 0.4.3.
481    fn latest_many(&self, cell_ids: &[&str]) -> Result<Vec<Option<Version>>> {
482        cell_ids.iter().map(|id| self.latest(id)).collect()
483    }
484    /// [`receipt`](Resolver::receipt) of each of `hashes`, in input order, as owned bytes.
485    /// Since 0.4.3.
486    fn receipts_many(&self, hashes: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
487        Ok(hashes.iter().map(|h| self.receipt(h).map(|b| b.into_owned())).collect())
488    }
489    /// For each item in order, [`put_receipt`](Store::put_receipt) and then, when the item
490    /// has a `version`, [`put_version`](Store::put_version); returns the receipt hashes.
491    /// All or nothing on PostgreSQL (one transaction; calls of up to 10,000 items are the
492    /// size it is written for). SQLite (and this default) loops, stops at the first error,
493    /// and need not be atomic: the items before a failing one stay stored there. Since 0.4.3.
494    fn put_cells(&self, items: &[CellWrite<'_>]) -> Result<Vec<String>> {
495        items
496            .iter()
497            .map(|w| {
498                let hash = self.put_receipt(w.receipt)?;
499                if let Some((cell_id, tx)) = w.version {
500                    self.put_version(cell_id, tx, &hash)?;
501                }
502                Ok(hash)
503            })
504            .collect()
505    }
506    /// The stored receipts that list `receipt_hash` among their inputs, by hash. Only as
507    /// an input of its own: a receipt read as a member of a slice is found through its
508    /// manifests ([`member_manifests`](Store::member_manifests), then
509    /// [`slice_dependents`](Store::slice_dependents)).
510    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>>;
511    /// The inputs of a stored receipt that are receipt hashes (whether or not they are
512    /// stored). Its slice entries are [`slice_entries`](Store::slice_entries).
513    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>>;
514    /// Records a host's key document, checked as a 200 response for that host would be
515    /// (SPEC 9.2, 9.3), validated at `validated_at`. Re-validation replaces the document; a
516    /// `validated_at` earlier than the recorded one is [`Error::NotLater`]. Receipts already
517    /// stored are not re-checked: they verified when they were stored (and putting one again
518    /// stays idempotent).
519    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()>;
520    /// A host's recorded key document.
521    fn namespace(&self, host: &str) -> Result<Option<Namespace>>;
522    /// Every recorded namespace, by host. Since the namespace checks (since 0.4.1).
523    fn namespaces(&self) -> Result<Vec<Namespace>>;
524    /// Records a failed check of `host`'s key document at `checked_at` (domain validation):
525    /// the consecutive failures grow by one, and when they reach `threshold` (zero counts as
526    /// one) the namespace is suspended at `checked_at`, unless it already is (the first
527    /// suspension's time is kept). While it is suspended the store refuses new writes under
528    /// the host: `put_receipt` of a receipt signed by it, `put_version` of such a receipt
529    /// and `bind_name` of a name under it ([`Error::NamespaceSuspended`]); reads,
530    /// verification and the stored key document are not affected, and neither is putting a
531    /// receipt that is already stored. Returns the namespace as recorded, or `None` for a
532    /// host with no namespace (there is nothing to suspend). A `checked_at` earlier than the
533    /// latest check is [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
534    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>>;
535    /// Records a successful check of `host`'s key document at `checked_at`: the consecutive
536    /// failures are reset to zero and a suspension is lifted (the namespace is reinstated).
537    /// The document itself is recorded with [`put_namespace`](Store::put_namespace) (which
538    /// neither suspends nor reinstates). Returns the namespace as recorded, or `None` for a
539    /// host with no namespace. A `checked_at` earlier than the latest check is
540    /// [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
541    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>>;
542    /// Appends a binding: from `tx` on, the fully qualified function name `fn_name` means
543    /// `fn_hash`, whose descriptor must be stored. `tx` must be later than the name's latest
544    /// binding ([`Error::NotLater`]).
545    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()>;
546    /// The function hash `fn_name` meant as of `asof`: the hash of
547    /// [`resolve_binding`](Store::resolve_binding)'s binding.
548    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>>;
549    /// The binding of `fn_name` that answers as of `asof`: the one with the latest `tx <=
550    /// asof`, with its function hash and its `tx`, when it began; `None` before the first.
551    /// A name bound again to a hash it meant before (even the hash of the binding before
552    /// it) begins again: the later binding's `tx`. Since 0.3.0.
553    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>>;
554
555    /// Stores a class descriptor (SPEC 16.1, 16.2) under its class hash and returns the hash.
556    /// Since 0.4.1.
557    ///
558    /// `bytes` must be a **flattened** descriptor in **canonical form** (the bytes
559    /// `ClassDescriptor::canonical` gives, 6.2: what the class hash hashes). The core checks it
560    /// (`ClassDescriptor::from_json`: strict JSON, then 16.1 in its check order; a flattened
561    /// descriptor passes). Bytes that are a valid descriptor but not the canonical form of
562    /// it (white space, members out of order) are refused with [`Error::Invalid`], code
563    /// `E_SCHEMA`, and nothing is stored: unlike [`put_descriptor`](Store::put_descriptor),
564    /// which canonicalises, the bytes put are the bytes stored, so the class hash is the
565    /// SHA-256 of what [`class`](Store::class) returns. Idempotent for the same bytes.
566    ///
567    /// The store does not flatten (that is define's, with the parent in hand), and does not
568    /// need the parent, the method functions or the interfaces to be stored (`bind_class`
569    /// needs the methods' descriptors). It does not check the owner either (16.2 step 1 is the
570    /// definer's check: the store records, http and the engine enforce). It is a write under
571    /// the class's steward namespace (`steward.namespace`): refused with
572    /// [`Error::NamespaceSuspended`] while that namespace is suspended, even for a class
573    /// already stored.
574    fn put_class(&self, bytes: &[u8]) -> Result<String>;
575    /// The canonical bytes of the class descriptor with this class hash, as stored
576    /// ([`put_class`](Store::put_class)); `None` when no such class is stored. A malformed
577    /// hash is `E_CANON_HEX`. Never refused under a suspended namespace. Since 0.4.1.
578    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>>;
579    /// Binds the class name `class_name` (a full name, 2.3) to the stored class `class_hash`
580    /// from `tx` on and, in the same transaction, binds each method `<class_name>/<m>` of the
581    /// stored (flattened, so inherited methods included) descriptor to the method's function
582    /// hash from the same `tx` (SPEC 16.3, 9.7). All of it or nothing:
583    ///
584    /// - the class must be stored ([`Error::NotFound`], `what` `"class"`), and so must every
585    ///   method's function descriptor ([`Error::NotFound`], `what` `"descriptor"`, the missing
586    ///   function hash; the first in JCS order of method names);
587    /// - class names and function names share one namespace of names: `class_name`, or a
588    ///   method name, whose latest binding is of the other kind (a function for `class_name`,
589    ///   a class for a method name) is refused with [`Error::NameTaken`]. A method name bound
590    ///   as a function, to whatever hash, is simply bound again;
591    /// - `tx` must be later than the latest binding of `class_name` and of each method name
592    ///   ([`Error::NotLater`], `what` `"name"`, the name that is not);
593    /// - while the namespace of `class_name`'s host is suspended: [`Error::NamespaceSuspended`].
594    ///
595    /// The store does not check that the class name is under the steward's namespace, nor
596    /// who binds it (the definer's check, 16.2 step 1). Since 0.4.1.
597    ///
598    /// Since 0.5.4 (K5), only the methods the class adds or overrides are bound under its name:
599    /// those whose function hash its parent's flattened descriptor does not give (or that the
600    /// parent does not have). An inherited method's name is not bound, so `S/m` of an inherited
601    /// `m` answers `None`. Under 0.5.3 every flattened method was bound.
602    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()>;
603    /// Closes the latest binding of `name`, a function name or a class name, from `at` on: as
604    /// of `at` or later the name resolves to `None` (also through
605    /// [`resolve_binding`](Store::resolve_binding) and [`resolve_class_binding`](Store::resolve_class_binding)),
606    /// and as of an earlier instant the binding it had. Closing a class name closes its
607    /// method names (`<class name>/<m>`, the ones [`bind_class`](Store::bind_class) bound) from
608    /// the same `at`. The name may be bound again later ([`bind_name`](Store::bind_name),
609    /// [`bind_class`](Store::bind_class)), with a `tx` after `at`. Each close is one row of the
610    /// binding history (with `written_at`). `at` must be later than the latest binding of the
611    /// name; a name with no binding, or whose latest binding is closed, is [`Error::NotFound`]
612    /// (`what` is `binding`). A malformed instant is `E_CANON_INSTANT`. The default is
613    /// [`Error::Unsupported`]. Since 0.6.0.
614    fn close_binding(&self, name: &str, at: &str) -> Result<()> {
615        let _ = (name, at);
616        Err(Error::Unsupported("closing a binding needs a store of 0.6.0".into()))
617    }
618    /// The class hash `class_name` meant as of `asof`: the hash of
619    /// [`resolve_class_binding`](Store::resolve_class_binding)'s binding. `None` before the
620    /// first binding, and for a name whose binding as of `asof` is a function's. Since 0.4.1.
621    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>>;
622    /// The class binding of `class_name` that answers as of `asof`: the latest with
623    /// `tx <= asof`, with its class hash and its `tx` (when it began; binding the same hash
624    /// again begins again), as [`resolve_binding`](Store::resolve_binding) does for functions.
625    /// `None` before the first, and for a function name. The function accessors
626    /// ([`resolve_name`](Store::resolve_name), [`resolve_binding`](Store::resolve_binding))
627    /// answer `None` for a class name: a bindings answer (9.7) has `fn_hash` or `class_hash`,
628    /// never both. Since 0.4.1.
629    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>>;
630    /// The class names whose class binding as of `at` (the latest with `tx <= at`, as
631    /// [`resolve_class_binding`](Store::resolve_class_binding) takes it) is `class_hash`, in byte
632    /// order, each once. A name rebound to another hash is no longer listed from that binding's
633    /// `tx` on. Function names are never listed. Empty when none is bound (also when the hash is
634    /// not stored, or `at` is before the first binding). A malformed hash is `E_CANON_HEX`, a
635    /// malformed instant `E_CANON_INSTANT`. The default is [`Error::Unsupported`]. Since 0.5.3.
636    fn class_names_bound_to(&self, class_hash: &str, at: &str) -> Result<Vec<String>> {
637        let _ = (class_hash, at);
638        Err(Error::Unsupported("class names need a store of 0.5.3".into()))
639    }
640
641    /// Records that `receipt_hash` (stored, a receipt of `cell_id` at `tx`) is a computed
642    /// version of the cell. Insert-only, in any order (an older version may be added after a
643    /// newer one): `tx` need not be later than anything. The version's asof is the
644    /// receipt's. Idempotent for the same (cell_id, tx, asof, receipt_hash); another receipt
645    /// for an existing (cell_id, tx, asof) is [`Error::Conflict`] (its `hash` is the receipt
646    /// refused) and the stored one is kept. The receipt is checked as for
647    /// [`put_version`](Store::put_version): [`Error::NotFound`] when it is not stored,
648    /// [`Error::Mismatch`] when it is of another cell or at another tx. Since 0.2.0.
649    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
650    /// The computed version that answers as of `asof`: the one with the greatest asof <=
651    /// `asof` (between equal asof, the greatest tx), or `None`. Since 0.2.0.
652    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
653    /// The stored version that answers as of `asof`: the latest version (by tx) with `tx <=
654    /// asof` whose receipt's asof is also `<= asof`, or `None`. A version whose receipt is
655    /// late-signed (asof later than tx) answers only from its asof on; until then the
656    /// version before it answers. ([`version_asof`](Store::version_asof) keeps its tx-only
657    /// meaning.) Since 0.2.0.
658    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
659    /// The cells that read `cell_id`: the cell ids of the stored receipts that list, among
660    /// their inputs, any stored receipt of `cell_id` (lineage: edges joined to receipts),
661    /// or (since 0.3.1) a slice entry whose stored manifest lists one as a member.
662    /// Ascending, each once. Since 0.2.0.
663    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>>;
664
665    /// Stores a manifest (SPEC 15.13), `{"members": [...], "slice": {...}}`: parsed strictly
666    /// and checked by the core (`Manifest::from_json`: structure, members, their order and
667    /// limit, the slice object), kept in canonical form under its entry
668    /// `slice:<slice id>:<members hash>`, which it returns, and recorded for each member
669    /// ([`member_manifests`](Store::member_manifests)). The members need not be stored.
670    /// Idempotent; insert-only (the entry is a hash of the content, so a stored entry
671    /// always has these bytes). Served by [`manifest`](Resolver::manifest). Since 0.3.1.
672    fn put_manifest(&self, bytes: &[u8]) -> Result<String>;
673    /// The entries of the stored manifests that list `receipt_hash` among their members,
674    /// ascending: from a member, the slices it was read in (then
675    /// [`slice_dependents`](Store::slice_dependents)). Since 0.3.1.
676    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>>;
677    /// The slice entries among the inputs of a stored receipt, ascending. Since 0.3.1.
678    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>>;
679    /// The stored receipts whose inputs list the slice entry `entry`, by hash, ascending.
680    /// An entry is `slice:` and two 64-digit hashes (`E_CANON_HEX` otherwise). Since 0.3.1.
681    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>>;
682    /// The members of `slice` as of `asof` (SPEC 15.13), with the stored version of each
683    /// that answers as of `asof` and its receipt's bytes.
684    ///
685    /// For a slice of cells: the cells of the slice's function (its `fn_hash`, `ns` and
686    /// `fn`, with the same argument names) whose bound arguments are the same typed scalar,
687    /// whose ranged arguments are of the range's type and within it (`lo <= v <= hi`,
688    /// inclusive, in the type's order: numbers as exact decimals, dates and instants
689    /// chronologically, strings by code point; `lo` after `hi` is empty), any value for an
690    /// open argument, and that have a stored version answering as of `asof`: as
691    /// [`stored_asof`](Store::stored_asof), the latest version with `tx <= asof` whose
692    /// receipt's `asof <= asof` (so a late-signed version is not a member's answer before
693    /// its asof, and a correction replaces a member's version from its asof on). Computed
694    /// versions are not members. In key order: by the open and ranged arguments in
695    /// ascending name order, each in its type's order (`false` before `true`; blobs as
696    /// text); the cell id last, for two cells whose key arguments are of different types.
697    ///
698    /// For a version slice `{"cell", "from", "to"}`: [`versions_between`](Store::versions_between)
699    /// of its cell. Empty when nothing matches. Since 0.3.1.
700    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>>;
701    /// The stored versions of `cell_id` with `from <= tx <= to` that answer as of `asof`
702    /// (`tx <= asof` and the receipt's `asof <= asof`), ascending by tx, each with its
703    /// receipt's bytes: SPEC 15.13's version slice. Empty when `from` is after `to`. Since
704    /// 0.3.1.
705    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>>;
706    /// The members [`slice_members`](Store::slice_members) gives, in its order and by its
707    /// answering rule, each as its version, its receipt's typed value and its cell (with its
708    /// arguments), without the receipt's bytes (the value is a stored column of the receipt
709    /// and the cell comes from the typed-argument index, neither parsed per call).
710    /// Since 0.3.2.
711    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>>;
712    /// Whether the members of `slice`, or their versions, may answer differently as of some
713    /// time after `asof`: whether a cell matching the slice has a stored version whose
714    /// receipt's `asof` is after `asof` (its `tx` is never later than that), for a version
715    /// slice one with `tx` in `[from, to]`. `false` means [`slice_members`](Store::slice_members)
716    /// (and `slice_values`) give the same answer as of every time from `asof` on, until a
717    /// version is stored with an asof after it; `true` may be conservative (a late-signed
718    /// version superseded before its asof never answers). Index scans only, whatever the
719    /// slice's size: two bounded probes (at most 10,001 entries each) choose whether to walk
720    /// the function's receipts with an asof after `asof` or the slice's candidate cells,
721    /// whichever is fewer, and one query walks it, stopping at the first match. Since 0.3.2.
722    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool>;
723    /// The latest withdrawal among the cells that match `slice` (SPEC 8.2, spec-0.7.0): among
724    /// the cells whose version answering as of `asof` (the rule of `stored_asof`) is a
725    /// withdrawal, the greatest by `tx`, then by `asof`; its `(tx, asof)`. `None` when no such
726    /// cell. A version slice's one cell counts when its answering version is a withdrawal with
727    /// a `tx` in the slice's range. A malformed instant is `E_CANON_INSTANT`. The default is
728    /// [`Error::Unsupported`]. Since 0.6.0.
729    fn slice_withdrawn_latest(&self, slice: &Slice, asof: &str) -> Result<Option<(String, String)>> {
730        let _ = (slice, asof);
731        Err(Error::Unsupported("the withdrawn cells of a slice need a store of 0.6.0".into()))
732    }
733    /// The cells of `slice` (matched as [`slice_values`](Store::slice_values) matches them: the
734    /// fixed arguments, `fn_hash`, `ns`, `fn` and the number of arguments) that have a computed
735    /// version answering as of `asof`: one with `tx <= asof` whose receipt's asof is `<= asof`
736    /// (the rule of [`computed_asof`](Store::computed_asof)). Ascending by cell id, at most
737    /// `limit` (`slice_values` takes no limit), each with its arguments from the typed-argument
738    /// index. A cell with only a stored version is not returned. Since 0.4.2.
739    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>>;
740    /// Whether any name binding or class binding has a name starting with `namespace` and `/`
741    /// (so `"a.example/n"` is not a namespace of `"a.example/ns/f"`). Since 0.4.2.
742    fn has_bindings_under(&self, namespace: &str) -> Result<bool>;
743
744    /// Inserts or replaces catalogue entries, keyed by (kind, name); returns each entry's id,
745    /// in order. All or nothing: every entry is checked first (the name by the core's rules,
746    /// `hash` as 64 hex digits, the bounds of [`CatalogEntry`]) and refused with
747    /// [`Error::Invalid`] before anything is written. An operator's entry never replaces a
748    /// publisher's: that entry is kept, and the call still answers its id. A publisher's
749    /// replaces either. Replacing an entry's label or description drops its embedding.
750    /// Since 0.5.0.
751    fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>>;
752    /// Inserts or replaces the values of `key` of `owner` (a function or class name): each
753    /// value's label and aliases are replaced, and its `n_cells` is kept. Values not in
754    /// `values` stay (an upsert adds and replaces, it does not prune). Returns each value's
755    /// id, in order. Replacing a value's label drops its embedding. Since 0.5.0.
756    fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>>;
757    /// Sets every dictionary value's `n_cells` to the number of cells of the function named
758    /// by its owner that have that value for the key; returns the number of rows refreshed
759    /// (every value, changed or not). Since 0.5.0.
760    fn refresh_value_counts(&self) -> Result<u64>;
761    /// The entries and dictionary values that match every word of `query` (split on white
762    /// space; a word matches case-insensitively, literally, in any field of the entry or
763    /// value, and scores 1.0 as a whole field, 0.8 as one of a field's words, 0.5 inside a
764    /// field; a score is the mean over the words, in (0, 1]). Best first, ties by name; at
765    /// most `limit`. A blank query finds nothing. Since 0.5.0.
766    fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>>;
767    /// The entries and values nearest to `vec` by cosine similarity, among those with an
768    /// embedding for `model`: each score is 1 minus the cosine distance (1.0 for the same
769    /// direction), best first, at most `limit`. `vec` has 384 finite values, not all zero
770    /// ([`Error::Invalid`] otherwise). [`Error::Unsupported`] where
771    /// [`vector_available`](Store::vector_available) is false. Since 0.5.0.
772    fn vector_find(&self, model: &str, vec: &[f32], limit: usize) -> Result<Vec<Hit>>;
773    /// Stores embeddings for `model`, one per (kind, id, model): an existing one is replaced.
774    /// All or nothing; a reference to an entry or value that is not stored is
775    /// [`Error::NotFound`], and a vector is checked as [`vector_find`](Store::vector_find)
776    /// checks it. [`Error::Unsupported`] where `vector_available` is false. Since 0.5.0.
777    fn put_embeddings(&self, model: &str, items: &[Embedding]) -> Result<()>;
778    /// Up to `limit` entries and values with no embedding for `model`, with the text to embed
779    /// (see [`PendingEmbedding`]). Empty where `vector_available` is false (nothing can be
780    /// stored there). Since 0.5.0.
781    fn pending_embeddings(&self, model: &str, limit: usize) -> Result<Vec<PendingEmbedding>>;
782    /// Whether vectors can be stored and searched by this store: PostgreSQL with the `vector`
783    /// extension, where the migration made the `embeddings` table. Looked at when the store
784    /// is opened (migrate before opening, as the schema is then in place). Since 0.5.0.
785    fn vector_available(&self) -> bool;
786    /// Records a find that found nothing: the query's text (trimmed, at most 512 bytes; a
787    /// blank query records nothing) and the time. The store keeps at most
788    /// [`FIND_MISSES_CAP`] rows, pruning the oldest. Since 0.5.0.
789    fn log_miss(&self, query: &str) -> Result<()>;
790    /// The catalogue as an operator reads it: every entry with its label and its cell count,
791    /// and every dictionary with its first 50 values (by value) and how many it has. Since 0.5.0.
792    fn catalog_summary(&self) -> Result<Summary>;
793
794    /// Stores a function test, if its (fn_hash, case) has none: `Ok(true)` when the row is
795    /// inserted, `Ok(false)` when one exists, in which case nothing changes (the first
796    /// writer's `signed_by` and `test_json` stay). The test is checked first: a 64-digit
797    /// hash, a 16-digit case, a canonical `test_json`, a signer of 1 to 256 bytes, an instant
798    /// and result if it carries them, and branch counts with covered not above total, each
799    /// at most `i32::MAX`; a failing check is [`Error::Invalid`] and nothing is stored.
800    /// Since 0.5.1.
801    fn put_function_test(&self, test: &FunctionTest) -> Result<bool>;
802    /// Every test of `fn_hash`, ordered by case ascending; empty when there are none. Since 0.5.1.
803    fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>>;
804    /// Records a run of the test (`fn_hash`, `case`): sets its `last_run_at` (the instant
805    /// `run_at`), `last_result` and `last_detail`. `Ok(true)` when the test exists; `Ok(false)`
806    /// when it does not, and nothing is inserted. `result` must be `pass`, `fail` or `error`:
807    /// any other value is [`Error::Invalid`], and nothing changes. Since 0.5.1.
808    fn record_function_test(&self, fn_hash: &str, case: &str, run_at: &str, result: &str, detail: &str)
809        -> Result<bool>;
810    /// Sets `branches_total` and `branches_covered` on every test of `fn_hash`. A function
811    /// with no tests is a no-op, not an error. `covered` above `total` is [`Error::Invalid`].
812    /// Since 0.5.1.
813    fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()>;
814    /// The function hashes of the stored descriptors whose `inputs` contain `name` (a fully
815    /// qualified function name), distinct, ascending. Answered from the index of descriptor
816    /// inputs, which [`put_descriptor`](Store::put_descriptor) fills; the migration that
817    /// introduced the index filled it from the descriptors stored before. Since 0.5.1.
818    fn function_readers(&self, name: &str) -> Result<Vec<String>>;
819    /// Every fully qualified name ever bound (by [`bind_name`](Store::bind_name)) to
820    /// `fn_hash`, distinct, ascending. A name since bound to another hash still lists this
821    /// one. Since 0.5.1.
822    fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>>;
823
824    /// Sets the function name of tests of `fn_hash`: each `(case, fn_name)` names the test of
825    /// that case, if it has no name yet. A name once set is never changed, and a case with no
826    /// test changes nothing. Returns the number of tests named (rows changed); an empty list
827    /// is 0. The default is [`Error::Unsupported`]. Since 0.5.2.
828    fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
829        let _ = (fn_hash, names);
830        Err(Error::Unsupported("naming function tests needs a store of 0.5.2".into()))
831    }
832    /// Up to `limit` tests that have no function name, ordered by (function hash, case), each
833    /// as [`function_tests`](Store::function_tests) gives it. Naming them drains the list. The
834    /// default is [`Error::Unsupported`]. Since 0.5.2.
835    fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
836        let _ = limit;
837        Err(Error::Unsupported("unnamed tests need a store of 0.5.2".into()))
838    }
839    /// The summary of the tests of `fn_hash` in one aggregate: every test of the hash when
840    /// `fn_name` is `None`, else only those named `fn_name`. A hash with no such test gives the
841    /// zero summary ([`TestSummary::default`]). The default computes it from
842    /// [`function_tests`](Store::function_tests) when `fn_name` is `None`, and is
843    /// [`Error::Unsupported`] for a name (0.5.1 does not give a test's name). Since 0.5.2.
844    fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
845        if fn_name.is_some() {
846            return Err(Error::Unsupported("a summary by function name needs a store of 0.5.2".into()));
847        }
848        let mut s = TestSummary::default();
849        for t in self.function_tests(fn_hash)? {
850            s.count += 1;
851            match t.last_result.as_deref() {
852                Some("pass") => s.pass += 1,
853                Some("fail") => s.fail += 1,
854                Some("error") => s.error += 1,
855                _ => s.not_run += 1,
856            }
857            if let Some(at) = t.last_run_at {
858                if s.last_run_at.as_ref().is_none_or(|latest| at > *latest) {
859                    s.last_run_at = Some(at);
860                }
861            }
862            s.branches_total = s.branches_total.max(t.branches_total);
863            s.branches_covered = s.branches_covered.max(t.branches_covered);
864        }
865        Ok(s)
866    }
867    /// A page of the tests of `fn_hash` by case ascending: those named `fn_name` (or all, when
868    /// `None`), with a case after `after_case` (exclusive, when given), at most `limit`.
869    /// Whole rows, as [`function_tests`](Store::function_tests) gives them. The default is the
870    /// page of [`function_tests`](Store::function_tests) when `fn_name` is `None`, and is
871    /// [`Error::Unsupported`] for a name. Since 0.5.2.
872    fn function_tests_page(
873        &self,
874        fn_hash: &str,
875        fn_name: Option<&str>,
876        after_case: Option<&str>,
877        limit: usize,
878    ) -> Result<Vec<FunctionTest>> {
879        if fn_name.is_some() {
880            return Err(Error::Unsupported("a page by function name needs a store of 0.5.2".into()));
881        }
882        Ok(self
883            .function_tests(fn_hash)?
884            .into_iter()
885            .filter(|t| after_case.is_none_or(|after| t.case.as_str() > after))
886            .take(limit)
887            .collect())
888    }
889    /// The receipts (bytes, as [`receipt`](Resolver::receipt) returns them) of the latest
890    /// stored version of up to `limit` cells of `ns`/`fn_name`/`fn_hash` that have one, lowest
891    /// cell id first: at most `limit` cells are read. The default is [`Error::Unsupported`]
892    /// (0.5.1 has no read of a function's cells without a slice). Since 0.5.2.
893    fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
894        let _ = (ns, fn_name, fn_hash, limit);
895        Err(Error::Unsupported("stored receipts of a function need a store of 0.5.2".into()))
896    }
897    /// [`slice_values`](Store::slice_values) with at most `limit` members: the first `limit` of
898    /// its order (the same members, in the same order). The default takes them from
899    /// `slice_values`. Since 0.5.2.
900    fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
901        let mut values = self.slice_values(slice, asof)?;
902        values.truncate(limit);
903        Ok(values)
904    }
905    /// [`versions`](Store::versions) with at most `limit` versions: the first `limit`, in tx
906    /// order. The default takes them from `versions`. Since 0.5.2.
907    fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
908        let mut versions = self.versions(cell_id, from, to)?;
909        versions.truncate(limit);
910        Ok(versions)
911    }
912    /// The number of cells of `ns`/`fn_name`/`fn_hash` that have a stored version (a second
913    /// version of a cell is not a second cell). The default is [`Error::Unsupported`]. Since
914    /// 0.5.2.
915    fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
916        let _ = (ns, fn_name, fn_hash);
917        Err(Error::Unsupported("counting a function's cells needs a store of 0.5.2".into()))
918    }
919    /// Whether `owner` has the dictionary value `value` for `key`, exactly (the value's text,
920    /// case-sensitive; no prefix, substring or label match). Indexed in the native stores. The
921    /// default asks [`text_find`](Store::text_find) for `value` and keeps the exact match.
922    /// Since 0.5.2.
923    fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
924        Ok(self.text_find(value, usize::MAX)?.iter().any(
925            |h| matches!(h, Hit::Value { owner: o, key: k, value: v, .. } if o == owner && k == key && v == value),
926        ))
927    }
928    /// The number of dictionary values `owner` has for `key`. The default is
929    /// [`Error::Unsupported`]. Since 0.5.2.
930    fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
931        let _ = (owner, key);
932        Err(Error::Unsupported("counting a dictionary needs a store of 0.5.2".into()))
933    }
934    /// Marks the key `key` of `owner` open: it takes no automatic values from now on. Marking
935    /// an open key again changes nothing. Its existing values stay. The default is
936    /// [`Error::Unsupported`]. Since 0.5.2.
937    fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
938        let _ = (owner, key);
939        Err(Error::Unsupported("open keys need a store of 0.5.2".into()))
940    }
941    /// Whether the key `key` of `owner` has been marked open ([`mark_key_open`](Store::mark_key_open)).
942    /// The default is [`Error::Unsupported`]. Since 0.5.2.
943    fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
944        let _ = (owner, key);
945        Err(Error::Unsupported("open keys need a store of 0.5.2".into()))
946    }
947    /// The number of keys marked open, of any owner ([`mark_key_open`](Store::mark_key_open)).
948    /// The default is 0, which is exact for a store with no open key. Since 0.5.2.
949    fn open_key_count(&self) -> Result<u64> {
950        Ok(0)
951    }
952    /// The catalogue entry named `name` (exactly), if there is one. A name may be the name of a
953    /// function and of a class; the function's entry is given first, then a method's, then a
954    /// class's. The default is [`Error::Unsupported`]. Since 0.5.2.
955    fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
956        let _ = name;
957        Err(Error::Unsupported("an exact catalogue lookup needs a store of 0.5.2".into()))
958    }
959
960    /// Inserts or replaces catalogue entries with their facets and `extends`, keyed by (kind,
961    /// name), as [`upsert_catalog`](Store::upsert_catalog) does, and replaces the facets and
962    /// `extends` of an existing row. Checked first, all or nothing ([`Error::Invalid`]): the
963    /// facets (a key of domain, thing, measure, region or frequency; 1 to 8 names each, names of
964    /// at most 32 bytes, ascending and unique), and `extends` (a full function name, on a
965    /// function only). The store does not check that `extends` names a stored class, nor the key
966    /// rule of 16.3. Returns each entry's id, in order. The default is [`Error::Unsupported`].
967    /// Since 0.6.0.
968    fn upsert_catalog_ext(&self, entries: &[CatalogEntryExt]) -> Result<Vec<i64>> {
969        let _ = entries;
970        Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
971    }
972    /// The catalogue entry of kind `kind` and name `name` (exactly), with its facets and
973    /// `extends`, if there is one. The default is [`Error::Unsupported`]. Since 0.6.0.
974    fn catalog_entry_ext(&self, kind: CatalogKind, name: &str) -> Result<Option<CatalogEntryExt>> {
975        let _ = (kind, name);
976        Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
977    }
978    /// The entries that have at least one facet, by kind (as text: class, function, method)
979    /// then name in byte order, each with its first binding time (see [`FacetedEntry`]).
980    /// The default is [`Error::Unsupported`]. Since 0.6.0.
981    fn catalog_entries_with_facets(&self) -> Result<Vec<FacetedEntry>> {
982        Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
983    }
984    /// The function entries whose `extends` is `class`, by name in byte order. A `class` that
985    /// is not a full name is [`Error::Invalid`]. The default is [`Error::Unsupported`]. Since 0.6.0.
986    fn extensions_of(&self, class: &str) -> Result<Vec<CatalogEntryExt>> {
987        let _ = class;
988        Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
989    }
990    /// [`extensions_of`](Store::extensions_of) with at most `limit` entries: the first `limit` by name (CONTRACT-round-0.7 R11,
991    /// the bounded read of a describe). The backends read `limit` rows (`LIMIT`, with the index on `extends`). The default takes
992    /// them from `extensions_of`. Since 0.6.0.
993    fn extensions_of_limit(&self, class: &str, limit: usize) -> Result<Vec<CatalogEntryExt>> {
994        let mut all = self.extensions_of(class)?;
995        all.truncate(limit);
996        Ok(all)
997    }
998
999    /// The number of cells of `ns`/`fn_name`/`fn_hash`: every cell with a stored receipt, a
1000    /// second version of a cell not counted again. Read from the counter (PK), not counted
1001    /// over the cells. The default is [`stored_cell_count`](Store::stored_cell_count). Since
1002    /// 0.5.3.
1003    fn cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
1004        self.stored_cell_count(ns, fn_name, fn_hash)
1005    }
1006    /// The test of `fn_hash` with case `case` (16 hex digits), if there is one: one row by
1007    /// primary key, as [`function_tests`](Store::function_tests) gives it. The default takes
1008    /// it from [`function_tests`](Store::function_tests). Since 0.5.3.
1009    fn function_test(&self, fn_hash: &str, case: &str) -> Result<Option<FunctionTest>> {
1010        Ok(self.function_tests(fn_hash)?.into_iter().find(|t| t.case == case))
1011    }
1012    /// Up to `limit` tests of `fn_hash` whose last result is `fail` or `error`, by case
1013    /// ascending, among those named `fn_name` (or all, when `None`). A SQL limit: the rows
1014    /// past it are not read. The default pages [`function_tests_page`](Store::function_tests_page)
1015    /// (which is [`Error::Unsupported`] for a name). Since 0.5.3.
1016    fn function_tests_failing(&self, fn_hash: &str, fn_name: Option<&str>, limit: usize) -> Result<Vec<FunctionTest>> {
1017        let mut out = Vec::new();
1018        if limit == 0 {
1019            return Ok(out);
1020        }
1021        let mut after: Option<String> = None;
1022        loop {
1023            let page = self.function_tests_page(fn_hash, fn_name, after.as_deref(), 256)?;
1024            let Some(last) = page.last() else { return Ok(out) };
1025            after = Some(last.case.clone());
1026            for t in page {
1027                if matches!(t.last_result.as_deref(), Some("fail") | Some("error")) {
1028                    out.push(t);
1029                    if out.len() == limit {
1030                        return Ok(out);
1031                    }
1032                }
1033            }
1034        }
1035    }
1036    /// The stored `test_case` cells of any namespace whose `function_hash` argument is
1037    /// `fn_hash` and whose latest version is `false`: each as (cell id, the bytes of the
1038    /// receipt of that latest version), at most `limit`, in one query. The default is
1039    /// [`Error::Unsupported`]. Since 0.5.3.
1040    fn false_test_cells(&self, fn_hash: &str, limit: usize) -> Result<Vec<(String, Vec<u8>)>> {
1041        let _ = (fn_hash, limit);
1042        Err(Error::Unsupported("false test cells need a store of 0.5.3".into()))
1043    }
1044    /// The names bound at `at` to a function hash that reads `name` (its descriptor's inputs
1045    /// name it), as (name, fn_hash), at most `limit`. The default walks
1046    /// [`function_readers`](Store::function_readers), [`bound_names`](Store::bound_names) and
1047    /// [`resolve_name`](Store::resolve_name). Since 0.5.3.
1048    fn dependants_of(&self, name: &str, at: &str, limit: usize) -> Result<Vec<(String, String)>> {
1049        let mut out = Vec::new();
1050        if limit == 0 {
1051            return Ok(out);
1052        }
1053        for h in self.function_readers(name)? {
1054            for n in self.bound_names(&h)? {
1055                if self.resolve_name(&n, at)?.as_deref() == Some(h.as_str()) {
1056                    out.push((n, h.clone()));
1057                    if out.len() == limit {
1058                        return Ok(out);
1059                    }
1060                }
1061            }
1062        }
1063        Ok(out)
1064    }
1065    /// A page of the members of `slice` as of `asof` in sort-key order (CONTRACT-0.5.1 S2):
1066    /// those whose [`SliceValue::sort_key`] is greater than `after` (exclusive; all of them
1067    /// when `None`), at most `limit`, with the same membership as
1068    /// [`slice_values`](Store::slice_values) (fixed arguments, ranges, the latest version as of
1069    /// `asof`, withdrawals left out), so that a walk of pages, each from the last member's key,
1070    /// gives `slice_values` member for member. A version slice has no key order to page by:
1071    /// [`Error::Unsupported`]. The default takes all of `slice_values` and pages them; the
1072    /// stores read the index of the function's cells. Since 0.6.4.
1073    fn slice_page(&self, slice: &Slice, asof: &str, after: Option<&[u8]>, limit: usize) -> Result<Vec<SliceValue>> {
1074        if slice.is_version_slice() {
1075            return Err(Error::Unsupported("a version slice has no key order to page by".into()));
1076        }
1077        if limit == 0 {
1078            return Ok(Vec::new());
1079        }
1080        let values = self.slice_values(slice, asof)?;
1081        Ok(values.into_iter().filter(|v| after.is_none_or(|a| v.sort_key.as_slice() > a)).take(limit).collect())
1082    }
1083    /// A page of the members of `slice` as of `asof`, by cell id ascending: those whose cell
1084    /// id is after `after_cell_id` (exclusive, when given), at most `limit`, with one value
1085    /// per member. The default takes all of [`slice_values`](Store::slice_values) and pages
1086    /// them. Since 0.5.3.
1087    fn slice_values_page(
1088        &self,
1089        slice: &Slice,
1090        asof: &str,
1091        after_cell_id: Option<&str>,
1092        limit: usize,
1093    ) -> Result<Vec<SliceValue>> {
1094        let mut values = self.slice_values(slice, asof)?;
1095        values.retain(|v| after_cell_id.is_none_or(|a| v.version.cell_id.as_str() > a));
1096        values.sort_by(|a, b| a.version.cell_id.cmp(&b.version.cell_id));
1097        values.truncate(limit);
1098        Ok(values)
1099    }
1100    /// Up to `limit` catalogue entries as (kind, name, label, description), with no counts.
1101    /// The default is [`Error::Unsupported`]. Since 0.5.3.
1102    fn catalog_entries_all(&self, limit: usize) -> Result<Vec<(CatalogKind, String, String, String)>> {
1103        let _ = limit;
1104        Err(Error::Unsupported("the catalogue's entries need a store of 0.5.3".into()))
1105    }
1106    /// The values of dictionary `key` of `owner`, in insertion order, at most `limit`. The
1107    /// default is [`Error::Unsupported`]. Since 0.5.3.
1108    fn dictionary_values_ordered(&self, owner: &str, key: &str, limit: usize) -> Result<Vec<String>> {
1109        let _ = (owner, key, limit);
1110        Err(Error::Unsupported("ordered dictionary values need a store of 0.5.3".into()))
1111    }
1112    /// [`computed_asof`](Store::computed_asof) and the bytes of the version's receipt (as
1113    /// [`receipt`](Resolver::receipt) returns them), which is what a caller reads next.
1114    /// The default asks for the two in turn (a receipt that cannot be read then is
1115    /// [`Error::NotFound`]); [`PgStore`] and [`SqliteStore`] answer both with one query.
1116    /// Since 0.2.0.
1117    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1118        match self.computed_asof(cell_id, asof)? {
1119            Some(v) => with_receipt(self, v).map(Some),
1120            None => Ok(None),
1121        }
1122    }
1123    /// [`stored_asof`](Store::stored_asof) and the bytes of the version's receipt, as
1124    /// [`computed_asof_with_receipt`](Store::computed_asof_with_receipt) does. Since 0.2.0.
1125    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1126        match self.stored_asof(cell_id, asof)? {
1127            Some(v) => with_receipt(self, v).map(Some),
1128            None => Ok(None),
1129        }
1130    }
1131}
1132
1133/// The seal of [`Store`]: a public trait in a private module, so no other crate can name it,
1134/// and so none can implement `Store`.
1135mod sealed {
1136    pub trait Sealed {}
1137    impl Sealed for crate::PgStore {}
1138    #[cfg(feature = "sqlite")]
1139    impl Sealed for crate::SqliteStore {}
1140}
1141
1142/// A receipt as the store reads it when it is put (crate-internal, since 0.6.0): a valued
1143/// receipt, or a withdrawal (8.1), which has no value.
1144pub(crate) struct Parsed {
1145    /// The canonical (JCS) bytes, `sig` included: what the store keeps.
1146    pub(crate) canonical: Vec<u8>,
1147    pub(crate) hash: String,
1148    pub(crate) cell_id: String,
1149    pub(crate) tx: String,
1150    pub(crate) asof: String,
1151    pub(crate) fn_hash: String,
1152    pub(crate) publisher: String,
1153    /// The receipt's cell (its arguments are indexed by the SQLite store).
1154    #[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
1155    pub(crate) cell: Cell,
1156    /// The signer's host (the namespace whose keys verify it).
1157    pub(crate) host: String,
1158    /// The slice entries (`slice:` inputs) and the receipt inputs (edges), in the receipt's order.
1159    pub(crate) entries: Vec<String>,
1160    pub(crate) inputs: Vec<String>,
1161    /// The value's type and lexical form; `None` for a withdrawal.
1162    #[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
1163    pub(crate) value: Option<(String, String)>,
1164}
1165
1166/// The `value_type` and `value` columns of a withdrawal: empty, which no valued receipt has
1167/// (a receipt's type is a name). Since 0.6.0; both backends.
1168#[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
1169pub(crate) const WITHDRAWN_VALUE: &str = "";
1170
1171/// Parses receipt bytes as a valued [`Receipt`] or, failing that, a [`Withdrawal`] (steps 1-4
1172/// of either). The error is the receipt's when the bytes are neither.
1173pub(crate) fn parse_receipt(bytes: &[u8]) -> Result<Parsed> {
1174    // A receipt with a `withdrawn` member is a withdrawal: parsed by the core's `Withdrawal`
1175    // alone, so its own error (not the receipt's) is the one refused.
1176    let withdrawal = datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some());
1177    if withdrawal {
1178        let w = datumesh_core::Withdrawal::from_json(bytes)?;
1179        return Ok(Parsed {
1180            canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
1181            hash: w.hash().to_string(),
1182            cell_id: w.cell().id(),
1183            tx: w.tx().to_string(),
1184            asof: w.asof().to_string(),
1185            fn_hash: w.cell().fn_hash.clone(),
1186            publisher: w.publisher().to_string(),
1187            cell: w.cell().clone(),
1188            host: w.signer_host().to_string(),
1189            entries: Vec::new(),
1190            inputs: Vec::new(),
1191            value: None,
1192        });
1193    }
1194    match datumesh_core::Receipt::from_json(bytes) {
1195        Ok(r) => {
1196            let (entries, inputs): (Vec<String>, Vec<String>) =
1197                r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
1198            let value = r.value();
1199            Ok(Parsed {
1200                canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
1201                hash: r.hash().to_string(),
1202                cell_id: r.cell().id(),
1203                tx: r.tx().to_string(),
1204                asof: r.asof().to_string(),
1205                fn_hash: r.cell().fn_hash.clone(),
1206                publisher: r.publisher().to_string(),
1207                cell: r.cell().clone(),
1208                host: r.signer_host().to_string(),
1209                entries,
1210                inputs,
1211                value: Some((value.ty().as_str().to_string(), value.lexical().to_string())),
1212            })
1213        }
1214        Err(e) => {
1215            let Ok(w) = datumesh_core::Withdrawal::from_json(bytes) else { return Err(e.into()) };
1216            Ok(Parsed {
1217                canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
1218                hash: w.hash().to_string(),
1219                cell_id: w.cell().id(),
1220                tx: w.tx().to_string(),
1221                asof: w.asof().to_string(),
1222                fn_hash: w.cell().fn_hash.clone(),
1223                publisher: w.publisher().to_string(),
1224                cell: w.cell().clone(),
1225                host: w.signer_host().to_string(),
1226                entries: Vec::new(),
1227                inputs: Vec::new(),
1228                value: None,
1229            })
1230        }
1231    }
1232}
1233
1234/// The value of stored receipt bytes: `Some` for a valued receipt, `None` for a withdrawal.
1235/// An error when the bytes are neither.
1236pub(crate) fn stored_value(bytes: &[u8]) -> std::result::Result<Option<Scalar>, datumesh_core::Error> {
1237    match datumesh_core::Receipt::from_json(bytes) {
1238        Ok(r) => Ok(Some(r.value().clone())),
1239        Err(e) => match datumesh_core::Withdrawal::from_json(bytes) {
1240            Ok(_) => Ok(None),
1241            Err(_) => Err(e),
1242        },
1243    }
1244}
1245
1246/// The error of closing a name with no binding to close (never bound, or closed already).
1247pub(crate) fn unbound(name: &str) -> Error {
1248    Error::NotFound { what: "binding", key: name.to_string() }
1249}
1250
1251/// `Ok` when `at` is later than the latest binding `latest` of `key` (a closing's tx).
1252pub(crate) fn later_than(what: &'static str, key: &str, at: &str, latest: &str) -> Result<()> {
1253    if at <= latest {
1254        return Err(Error::NotLater { what, key: key.to_string(), given: at.to_string(), latest: latest.to_string() });
1255    }
1256    Ok(())
1257}
1258
1259/// A version and its receipt's bytes, for the default `*_with_receipt` methods.
1260fn with_receipt<S: Store + ?Sized>(store: &S, v: Version) -> Result<(Version, Cow<'_, [u8]>)> {
1261    match store.receipt(&v.receipt_hash) {
1262        Some(bytes) => Ok((v, bytes)),
1263        None => Err(Error::NotFound { what: "receipt", key: v.receipt_hash }),
1264    }
1265}