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