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