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
106use datumesh_core::lexical::{check_hex, check_instant};
107pub use datumesh_core::Resolver;
108use datumesh_core::{Cell, Scalar, Slice};
109
110mod catalogue;
111mod error;
112mod functions;
113mod listings;
114pub mod migrate;
115mod pg;
116pub mod pg_unstable;
117mod pool;
118mod slices;
119mod sql;
120#[cfg(feature = "sqlite")]
121mod sqlite;
122#[cfg(feature = "sqlite")]
123mod sqlite_sql;
124mod tls;
125
126/// The clock a store records its versions at (CONTRACT-guard-patch G9): an instant, read at each
127/// insert. The store sets `recorded = max(signed tx, clock())`; with no clock it is the signed tx.
128/// Set once, when the store is opened ([`PoolOptions::recording_clock`], [`SqliteOptions::recording_clock`]).
129/// Since 0.6.5.
130pub type RecordingClock = std::sync::Arc<dyn Fn() -> String + Send + Sync>;
131
132/// The instant one microsecond after `s` (a `YYYY-MM-DDTHH:MM:SS.ffffffZ` instant, carried through the
133/// calendar; `s` unchanged when it is not one). The store's per-cell rule of recorded times (decided 27
134/// Nov, B5) uses it: a version is recorded after the cell's latest.
135pub(crate) fn instant_after(s: &str) -> String {
136 if s.len() != 27 || !s.is_ascii() || s.as_bytes()[19] != b'.' || s.as_bytes()[26] != b'Z' {
137 return s.to_string();
138 }
139 let num = |r: std::ops::Range<usize>| s[r].parse::<u64>().ok();
140 let (Some(mut y), Some(mut mo), Some(mut d), Some(mut h), Some(mut mi), Some(mut se), Some(mut us)) =
141 (num(0..4), num(5..7), num(8..10), num(11..13), num(14..16), num(17..19), num(20..26))
142 else {
143 return s.to_string();
144 };
145 us += 1;
146 if us == 1_000_000 {
147 us = 0;
148 se += 1;
149 }
150 if se == 60 {
151 se = 0;
152 mi += 1;
153 }
154 if mi == 60 {
155 mi = 0;
156 h += 1;
157 }
158 if h == 24 {
159 h = 0;
160 d += 1;
161 }
162 let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
163 let dim = match mo {
164 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
165 4 | 6 | 9 | 11 => 30,
166 2 if leap => 29,
167 2 => 28,
168 _ => return s.to_string(),
169 };
170 if d > dim {
171 d = 1;
172 mo += 1;
173 }
174 if mo == 13 {
175 mo = 1;
176 y += 1;
177 }
178 format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{se:02}.{us:06}Z")
179}
180
181/// The later of two instants of the same fixed-width form (their text order).
182pub(crate) fn later_of(a: &str, b: &str) -> String {
183 if a >= b {
184 a.to_string()
185 } else {
186 b.to_string()
187 }
188}
189
190/// The recorded time of a version signed at `tx`: the greater of `tx` and the store's clock, or
191/// `tx` with no clock (SPEC-free: a store detail, see [`Version::recorded`]).
192pub(crate) fn recorded_at(clock: Option<&RecordingClock>, tx: &str) -> String {
193 match clock {
194 Some(now) => {
195 let now = now();
196 if now.as_str() > tx {
197 now
198 } else {
199 tx.to_string()
200 }
201 }
202 None => tx.to_string(),
203 }
204}
205
206pub use catalogue::{
207 CatalogEntry, CatalogEntryExt, CatalogKind, CatalogSource, Dictionary, DictionaryValue, EmbedRef, Embedding,
208 FacetedEntry, Facets, Hit, KeyValue, PendingEmbedding, Summary, SummaryEntry, FIND_MISSES_CAP,
209};
210pub use error::{DatabaseError, Error, Result};
211pub use listings::{ListedHost, Listing, ListingWrite, SubjectKeys, LISTING_SUBJECTS_MAX};
212pub use pg::PgStore;
213pub use pool::PoolOptions;
214#[cfg(feature = "sqlite")]
215pub use sqlite::{SqliteOptions, SqliteStore};
216
217/// The sort key of a cell (CONTRACT-0.5.1 S1; SPEC 5.6 and 15.13): its arguments as
218/// `(name, type, lexical form)`, in ascending name order, encoded as `cells.sort_key` is stored
219/// (the same bytes on PostgreSQL and SQLite) and as [`SliceValue::sort_key`] returns them. Keys
220/// compare as bytes. An empty `args` gives the empty key of a cell with no arguments. Since
221/// 0.6.4.
222pub fn sort_key(args: &[(&str, &str, &str)]) -> Vec<u8> {
223 let mut sorted: Vec<&(&str, &str, &str)> = args.iter().collect();
224 sorted.sort_by(|a, b| a.0.cmp(b.0));
225 sorted.iter().flat_map(|(_, ty, value)| slices::sort_item(ty, value)).collect()
226}
227
228/// A member-set row (CONTRACT-guard-patch G2, since 0.6.5): what a slice read saw, without its
229/// members. The entry is `slice:<slice_id>:<members_hash>`, as a manifest's; `slice` is the slice
230/// object's canonical bytes, `members` the count, `tx` the latest member or withdrawal tx the read
231/// saw (`None`: none, an empty slice) and `asof` the read's as-of. Written once per entry
232/// ([`Store::put_member_set`]).
233#[non_exhaustive]
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct MemberSet {
236 /// `slice:<slice_id>:<members_hash>`.
237 pub entry: String,
238 /// The slice's id.
239 pub slice_id: String,
240 /// The members hash (SPEC 15.13): the entry's second part.
241 pub members_hash: String,
242 /// The slice's function hash (of the version slice's cell for a version slice).
243 pub fn_hash: String,
244 /// The slice object's canonical bytes (the members are rebuilt from them).
245 pub slice: Vec<u8>,
246 /// How many members.
247 pub members: u64,
248 /// The latest member or withdrawal tx the read saw; `None` when there is none.
249 pub tx: Option<String>,
250 /// The read's as-of.
251 pub asof: String,
252 /// The members' distinct licence URLs, sorted (decided 26 Nov, G3): the store keeps them
253 /// distinct and sorted, and refuses an empty one. `from_manifest` leaves them empty; the caller
254 /// sets them (the reuse check reads them from the row, no member).
255 pub licences: Vec<String>,
256 /// The slice's [`Store::slice_seq`] read before its members (decided 26 Nov, G3): the reuse check
257 /// stands only while the slice's seq is still this. `from_manifest` leaves it 0; the caller sets it.
258 pub seen_seq: i64,
259}
260
261impl MemberSet {
262 /// The row of `manifest`, read at `asof`, whose latest member or withdrawal tx is `tx`.
263 pub fn from_manifest(manifest: &datumesh_core::Manifest, tx: Option<&str>, asof: &str) -> MemberSet {
264 let slice = manifest.slice();
265 MemberSet {
266 entry: manifest.entry(),
267 slice_id: slice.id().to_string(),
268 members_hash: manifest.members_hash().to_string(),
269 fn_hash: slice.fn_hash().to_string(),
270 slice: slice.canonical(),
271 members: manifest.members().len() as u64,
272 tx: tx.map(str::to_string),
273 asof: asof.to_string(),
274 licences: Vec::new(),
275 seen_seq: 0,
276 }
277 }
278}
279
280/// Checks a member set's entry (`slice:<64 hex>:<64 hex>`): its two ids, and the entry's form.
281pub(crate) fn check_member_entry(entry: &str) -> Result<(&str, &str)> {
282 let bad = || Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "a member-set entry"));
283 let rest = entry.strip_prefix("slice:").ok_or_else(bad)?;
284 let (id, members_hash) = rest.split_once(':').ok_or_else(bad)?;
285 check_hex(id, 64, "slice_id")?;
286 check_hex(members_hash, 64, "members_hash")?;
287 Ok((id, members_hash))
288}
289
290/// The receipt hashes of `members` that are not withdrawn, at most `limit`, in no particular order: the
291/// result of `slice_member_hashes` for a version slice (and of the default). Withdrawals are left out, as
292/// `slice_values` leaves them out (decided 27 Nov, A2).
293pub(crate) fn hashes_limited(members: Vec<SliceMember>, limit: usize) -> Vec<String> {
294 let mut members: Vec<SliceMember> = members.into_iter().filter(|m| !m.version.withdrawn).collect();
295 members.truncate(limit);
296 members.into_iter().map(|m| m.version.receipt_hash).collect()
297}
298
299/// The licences of a member set as the store keeps them: distinct and sorted; an empty one refused.
300pub(crate) fn normal_licences(list: &[String]) -> Result<Vec<String>> {
301 if list.iter().any(|l| l.is_empty()) {
302 return Err(Error::Invalid(datumesh_core::Error::new(
303 datumesh_core::ErrorCode::Schema,
304 "$",
305 "an empty licence",
306 )));
307 }
308 let mut out = list.to_vec();
309 out.sort();
310 out.dedup();
311 Ok(out)
312}
313
314/// The JCS text of a (normalised) licence list, as `member_sets.licences` holds it.
315pub(crate) fn licences_text(list: &[String]) -> String {
316 let arr =
317 datumesh_core::json::Value::Array(list.iter().map(|s| datumesh_core::json::Value::String(s.clone())).collect());
318 String::from_utf8(arr.to_jcs()).unwrap_or_default()
319}
320
321/// The licence list of `member_sets.licences`' JCS text.
322pub(crate) fn licences_of(text: &str) -> Result<Vec<String>> {
323 let bad =
324 || Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "a stored licence list"));
325 match datumesh_core::json::parse(text.as_bytes()).map_err(Error::Invalid)? {
326 datumesh_core::json::Value::Array(items) => {
327 items.iter().map(|i| i.as_str().map(str::to_string).ok_or_else(bad)).collect()
328 }
329 _ => Err(bad()),
330 }
331}
332
333/// Checks a member-set row as the store accepts it (G2): its entry, the ids and function hash,
334/// the slice bytes (a canonical slice object of the slice id and function hash) and the instants.
335pub(crate) fn check_member_set(set: &MemberSet) -> Result<()> {
336 let (id, members_hash) = check_member_entry(&set.entry)?;
337 if set.members_hash != members_hash {
338 return Err(Error::Invalid(datumesh_core::Error::new(
339 datumesh_core::ErrorCode::Schema,
340 "$",
341 "members_hash is not the entry's",
342 )));
343 }
344 if set.slice_id != id {
345 return Err(Error::Invalid(datumesh_core::Error::new(
346 datumesh_core::ErrorCode::Schema,
347 "$",
348 "slice_id is not the entry's",
349 )));
350 }
351 check_hex(&set.fn_hash, 64, "fn_hash")?;
352 let slice = Slice::from_json(&set.slice).map_err(Error::Invalid)?;
353 if slice.id() != set.slice_id || slice.fn_hash() != set.fn_hash || slice.canonical() != set.slice {
354 return Err(Error::Invalid(datumesh_core::Error::new(
355 datumesh_core::ErrorCode::Schema,
356 "$",
357 "the slice bytes are not the canonical slice of the id and function hash",
358 )));
359 }
360 check_instant(&set.asof, "asof")?;
361 if let Some(tx) = &set.tx {
362 check_instant(tx, "tx")?;
363 }
364 if set.members > 1_048_576 {
365 return Err(Error::Invalid(datumesh_core::Error::new(
366 datumesh_core::ErrorCode::Schema,
367 "$",
368 "members is over the limit",
369 )));
370 }
371 Ok(())
372}
373
374/// A version of a cell: from transaction time `tx` on, the cell's value is that of the
375/// receipt `receipt_hash`, which states it as of `asof`.
376///
377/// A stored version ([`Store::put_version`]) or a computed one ([`Store::put_computed`]).
378#[non_exhaustive]
379#[derive(Clone, Debug, PartialEq, Eq, Hash)]
380pub struct Version {
381 /// The cell id.
382 pub cell_id: String,
383 /// The transaction time (an instant, SPEC 3.3).
384 pub tx: String,
385 /// The receipt stating the value.
386 pub receipt_hash: String,
387 /// The receipt's `asof` (an instant; never earlier than `tx`). Since 0.2.0.
388 pub asof: String,
389 /// Whether the receipt is a withdrawal (8.1): the cell has no value from `asof` on. Since
390 /// 0.6.0; always `false` for a computed version.
391 pub withdrawn: bool,
392 /// The instant the store recorded the version at (CONTRACT-guard-patch G9): the greater of
393 /// `tx` and the store's recording clock, or `tx` when the store has none. Every as-of
394 /// answer is by this time; a computed version's is its `tx`. Since 0.6.5.
395 pub recorded: String,
396 /// The insertion sequence of the version: assigned by the store at insert (through `put_version`
397 /// and `put_cells`), only increasing, never updated; withdrawals included. A computed version's
398 /// is 0. Since 0.6.5 (G3, "inserted since"; see [`Store::slice_seq`]).
399 pub seq: i64,
400}
401
402/// One cell write of [`Store::put_cells`]: a receipt and, optionally, the version it
403/// becomes. Since 0.4.3.
404#[non_exhaustive]
405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
406pub struct CellWrite<'a> {
407 /// The receipt's JSON bytes, as for `put_receipt`.
408 pub receipt: &'a [u8],
409 /// `Some((cell_id, tx))`: also `put_version(cell_id, tx, <this receipt's hash>)`.
410 pub version: Option<(&'a str, &'a str)>,
411}
412
413impl<'a> CellWrite<'a> {
414 /// A cell write of `receipt` and, when `version` is `Some((cell_id, tx))`, its version.
415 pub fn new(receipt: &'a [u8], version: Option<(&'a str, &'a str)>) -> Self {
416 CellWrite { receipt, version }
417 }
418}
419
420/// A member of a slice ([`Store::slice_members`], [`Store::versions_between`]): a stored
421/// version and the bytes of its receipt (as [`receipt`](Resolver::receipt) returns them).
422/// Since 0.3.1.
423#[non_exhaustive]
424#[derive(Clone, Debug, PartialEq, Eq, Hash)]
425pub struct SliceMember {
426 /// The version answering (its cell, tx, receipt hash and asof).
427 pub version: Version,
428 /// The receipt's bytes, canonical JSON.
429 pub receipt: Vec<u8>,
430}
431
432/// A member of a slice with its value and without its receipt's bytes
433/// ([`Store::slice_values`]). Since 0.3.2.
434#[non_exhaustive]
435#[derive(Clone, Debug, PartialEq, Eq, Hash)]
436pub struct SliceValue {
437 /// The version answering (its cell, tx, receipt hash and asof).
438 pub version: Version,
439 /// The receipt's typed value.
440 pub value: Scalar,
441 /// The member's cell, with its arguments (from the store's typed-argument index; equal
442 /// to the receipt's `cell`, and `cell.id()` is `version.cell_id`).
443 pub cell: Cell,
444 /// The member's sort key (the cell's, see [`Store::slice_page`]): the byte order of the
445 /// keys is the order of [`Store::slice_values`]. Since 0.6.4.
446 pub sort_key: Vec<u8>,
447}
448
449/// A name binding: from transaction time `tx` on, a fully qualified function name means the
450/// function `fn_hash` ([`Store::bind_name`]). Since 0.3.0.
451#[non_exhaustive]
452#[derive(Clone, Debug, PartialEq, Eq, Hash)]
453pub struct Binding {
454 /// The function hash the name means.
455 pub fn_hash: String,
456 /// When the binding began: the transaction time from which the name means `fn_hash`
457 /// (an instant, SPEC 3.3).
458 pub tx: String,
459}
460
461/// A class-name binding: from transaction time `tx` on, a class name means the class
462/// `class_hash` ([`Store::bind_class`]). The class counterpart of [`Binding`]; the bindings
463/// answer of SPEC 9.7 gives `class_hash` in place of `fn_hash` for such a name. Since 0.4.1.
464#[non_exhaustive]
465#[derive(Clone, Debug, PartialEq, Eq, Hash)]
466pub struct ClassBinding {
467 /// The class hash the name means.
468 pub class_hash: String,
469 /// When the binding began (an instant, SPEC 3.3).
470 pub tx: String,
471}
472
473/// A function test: a canonical test line of a function, stored once per (function hash,
474/// case) ([`Store::put_function_test`]). The run fields are set by
475/// [`Store::record_function_test`]; the branch counts by [`Store::set_function_branches`],
476/// which keeps them equal on every test of the function. Since 0.5.1.
477#[non_exhaustive]
478#[derive(Clone, Debug, PartialEq, Eq)]
479pub struct FunctionTest {
480 /// The function hash the test is of (64 lowercase hex digits).
481 pub fn_hash: String,
482 /// The case: 16 lowercase hex digits. Tests of a function are ordered by it.
483 pub case: String,
484 /// The test line, canonical (JCS) JSON.
485 pub test_json: Vec<u8>,
486 /// The host or key id that wrote the test. The first writer's: a later one changes nothing.
487 pub signed_by: String,
488 /// When the test last ran (an instant), if it has.
489 pub last_run_at: Option<String>,
490 /// The result of the last run: `pass`, `fail` or `error`.
491 pub last_result: Option<String>,
492 /// The detail of the last run.
493 pub last_detail: Option<String>,
494 /// The branches of the function (the same on every test of the function).
495 pub branches_total: u32,
496 /// The branches the function's tests cover (the same on every test of the function).
497 pub branches_covered: u32,
498}
499
500impl FunctionTest {
501 /// A test that has not run, with no branch counts: the run fields are `None` and the
502 /// counts zero. Since 0.5.1.
503 pub fn new(fn_hash: &str, case: &str, test_json: &[u8], signed_by: &str) -> FunctionTest {
504 FunctionTest {
505 fn_hash: fn_hash.to_string(),
506 case: case.to_string(),
507 test_json: test_json.to_vec(),
508 signed_by: signed_by.to_string(),
509 last_run_at: None,
510 last_result: None,
511 last_detail: None,
512 branches_total: 0,
513 branches_covered: 0,
514 }
515 }
516}
517
518/// The results of a function's tests ([`Store::function_test_summary`]): how many there are,
519/// how many passed, failed, errored or have not run, the latest run and the branch counts.
520/// `Default` is the summary of no tests (all zero, no run). Since 0.5.2.
521#[non_exhaustive]
522#[derive(Clone, Debug, Default)]
523pub struct TestSummary {
524 /// The tests counted.
525 pub count: u64,
526 /// The tests whose last run passed.
527 pub pass: u64,
528 /// The tests whose last run failed.
529 pub fail: u64,
530 /// The tests whose last run errored.
531 pub error: u64,
532 /// The tests that have not run (no last result).
533 pub not_run: u64,
534 /// The latest `last_run_at` of the tests, if any has run (an instant; instants compare as
535 /// text).
536 pub last_run_at: Option<String>,
537 /// The branches of the function (the value replicated on its tests; 0 when none).
538 pub branches_total: u32,
539 /// The branches covered by the function's tests (replicated as `branches_total`).
540 pub branches_covered: u32,
541}
542
543/// A namespace's host and its key document.
544#[non_exhaustive]
545#[derive(Clone, Debug, PartialEq, Eq, Hash)]
546pub struct Namespace {
547 /// The host (a DNS name).
548 pub host: String,
549 /// The key document, canonical (JCS).
550 pub keydoc: Vec<u8>,
551 /// When the document was last retrieved and checked.
552 pub validated_at: String,
553 /// When the namespace was suspended, if it is: the single record of suspension. Set by
554 /// [`record_namespace_failure`](Store::record_namespace_failure) when the consecutive
555 /// failures reach its threshold, cleared by
556 /// [`record_namespace_success`](Store::record_namespace_success). While it is set the
557 /// store refuses new writes under the host ([`Error::NamespaceSuspended`]).
558 pub suspended_at: Option<String>,
559 /// How many checks of the host's key document have failed in a row (zero after a
560 /// success). Since the namespace checks (since 0.4.1).
561 pub consecutive_failures: u32,
562 /// When the host's key document was last checked, successfully or not; `None` before
563 /// the first check recorded. Since the namespace checks (since 0.4.1).
564 pub last_checked_at: Option<String>,
565}
566
567/// The namespace after a check at `at`: a failed one (`threshold` is `Some`) adds to the
568/// consecutive failures and suspends at the threshold (an existing suspension keeps its
569/// time), a successful one (`None`) resets them and reinstates.
570/// The refusal of class descriptor bytes that are not the canonical form of the descriptor
571/// (`E_SCHEMA`, nothing stored): the class hash is the hash of the bytes stored, so only the
572/// canonical bytes are stored. Shared by both backends (since 0.4.1).
573pub(crate) fn not_canonical_class() -> Error {
574 Error::Invalid(datumesh_core::Error::new(
575 datumesh_core::ErrorCode::Schema,
576 "$",
577 "class descriptor is not in canonical form (JCS): put the canonical bytes",
578 ))
579}
580
581pub(crate) fn apply_check(ns: &mut Namespace, at: &str, threshold: Option<u32>) {
582 ns.last_checked_at = Some(at.to_string());
583 match threshold {
584 None => {
585 ns.consecutive_failures = 0;
586 ns.suspended_at = None;
587 }
588 Some(t) => {
589 ns.consecutive_failures = ns.consecutive_failures.saturating_add(1);
590 if ns.suspended_at.is_none() && ns.consecutive_failures >= t.max(1) {
591 ns.suspended_at = Some(at.to_string());
592 }
593 }
594 }
595}
596
597/// A Datumesh store: a [`Resolver`] that can also be written to.
598///
599/// Instants are SPEC 3.3 instants (`YYYY-MM-DDTHH:MM:SS.ffffffZ`), hashes and cell ids 64
600/// lowercase hex digits, hosts DNS names and function names fully qualified. Every method,
601/// read or write, refuses anything else with the core's error code ([`Error::Invalid`]),
602/// and reports a database failure as [`Error::Database`] (or [`Error::PoolTimeout`]): a read
603/// answers `Ok(None)` / `Ok(vec![])` only when the store really holds nothing.
604///
605/// The [`Resolver`] methods keep the core's `Option` signatures: there a malformed argument
606/// or a database failure is `None` (logged with `tracing` when it is a failure), which
607/// `verify` reports as unavailable.
608///
609/// Only this crate implements `Store` (it is sealed, since 0.3.0; [`PgStore`] and, since
610/// 0.4.0, [`SqliteStore`]): the store is the trust boundary, where every receipt is verified against its host's key document before it is
611/// kept, and what a store answers is relied on as checked. An implementation elsewhere
612/// could answer anything. `Store` stays object-safe (`Arc<dyn Store + Send + Sync>`). Even a complete implementation that
613/// delegates every method to a [`PgStore`] is refused (`E0277`: the private supertrait is
614/// not implemented; `tests/sealed.rs` checks that this is the only error):
615///
616/// ```compile_fail
617/// use std::borrow::Cow;
618/// use datumesh_core::{Cell, Scalar};
619/// use datumesh_core::Slice;
620/// use datumesh_store::{Binding, CatalogEntry, ClassBinding, Embedding, FunctionTest, Hit, KeyValue, Namespace, PendingEmbedding, PgStore, Resolver, Result, SliceMember, SliceValue, Store, Summary, Version};
621///
622/// struct Wrapper(PgStore);
623/// impl Resolver for Wrapper {
624/// fn descriptor(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.descriptor(h) }
625/// fn receipt(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.receipt(h) }
626/// fn evaluate(&self, c: &Cell, a: &str) -> Option<Scalar> { self.0.evaluate(c, a) }
627/// fn manifest(&self, e: &str) -> Option<Cow<'_, [u8]>> { self.0.manifest(e) }
628/// }
629/// impl Store for Wrapper {
630/// fn put_descriptor(&self, b: &[u8]) -> Result<String> { self.0.put_descriptor(b) }
631/// fn put_receipt(&self, b: &[u8]) -> Result<String> { self.0.put_receipt(b) }
632/// fn put_blob(&self, b: &[u8]) -> Result<String> { self.0.put_blob(b) }
633/// fn blob(&self, s: &str) -> Result<Option<Cow<'_, [u8]>>> { self.0.blob(s) }
634/// fn put_version(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_version(c, t, r) }
635/// fn version_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.version_asof(c, a) }
636/// fn versions(&self, c: &str, f: &str, t: &str) -> Result<Vec<Version>> { self.0.versions(c, f, t) }
637/// fn latest(&self, c: &str) -> Result<Option<Version>> { self.0.latest(c) }
638/// fn dependents(&self, r: &str) -> Result<Vec<String>> { self.0.dependents(r) }
639/// fn inputs(&self, r: &str) -> Result<Vec<String>> { self.0.inputs(r) }
640/// fn put_namespace(&self, h: &str, k: &[u8], v: &str) -> Result<()> { self.0.put_namespace(h, k, v) }
641/// fn namespace(&self, h: &str) -> Result<Option<Namespace>> { self.0.namespace(h) }
642/// fn namespaces(&self) -> Result<Vec<Namespace>> { self.0.namespaces() }
643/// fn record_namespace_failure(&self, h: &str, a: &str, n: u32) -> Result<Option<Namespace>> { self.0.record_namespace_failure(h, a, n) }
644/// fn record_namespace_success(&self, h: &str, a: &str) -> Result<Option<Namespace>> { self.0.record_namespace_success(h, a) }
645/// fn bind_name(&self, n: &str, f: &str, t: &str) -> Result<()> { self.0.bind_name(n, f, t) }
646/// fn resolve_name(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_name(n, a) }
647/// fn resolve_binding(&self, n: &str, a: &str) -> Result<Option<Binding>> { self.0.resolve_binding(n, a) }
648/// fn put_class(&self, b: &[u8]) -> Result<String> { self.0.put_class(b) }
649/// fn class(&self, h: &str) -> Result<Option<Vec<u8>>> { self.0.class(h) }
650/// fn bind_class(&self, n: &str, h: &str, t: &str) -> Result<()> { self.0.bind_class(n, h, t) }
651/// fn resolve_class(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_class(n, a) }
652/// fn resolve_class_binding(&self, n: &str, a: &str) -> Result<Option<ClassBinding>> { self.0.resolve_class_binding(n, a) }
653/// fn put_computed(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_computed(c, t, r) }
654/// fn computed_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.computed_asof(c, a) }
655/// fn stored_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.stored_asof(c, a) }
656/// fn cell_dependents(&self, c: &str) -> Result<Vec<String>> { self.0.cell_dependents(c) }
657/// fn put_manifest(&self, b: &[u8]) -> Result<String> { self.0.put_manifest(b) }
658/// fn member_manifests(&self, r: &str) -> Result<Vec<String>> { self.0.member_manifests(r) }
659/// fn slice_entries(&self, r: &str) -> Result<Vec<String>> { self.0.slice_entries(r) }
660/// fn slice_dependents(&self, e: &str) -> Result<Vec<String>> { self.0.slice_dependents(e) }
661/// fn slice_members(&self, s: &Slice, a: &str) -> Result<Vec<SliceMember>> { self.0.slice_members(s, a) }
662/// fn versions_between(&self, c: &str, f: &str, t: &str, a: &str) -> Result<Vec<SliceMember>> { self.0.versions_between(c, f, t, a) }
663/// fn slice_values(&self, s: &Slice, a: &str) -> Result<Vec<SliceValue>> { self.0.slice_values(s, a) }
664/// fn slice_changed_after(&self, s: &Slice, a: &str) -> Result<bool> { self.0.slice_changed_after(s, a) }
665/// fn computed_cells(&self, s: &Slice, a: &str, n: usize) -> Result<Vec<Cell>> { self.0.computed_cells(s, a, n) }
666/// fn has_bindings_under(&self, n: &str) -> Result<bool> { self.0.has_bindings_under(n) }
667/// fn upsert_catalog(&self, e: &[CatalogEntry]) -> Result<Vec<i64>> { self.0.upsert_catalog(e) }
668/// fn upsert_key_values(&self, o: &str, k: &str, v: &[KeyValue]) -> Result<Vec<i64>> { self.0.upsert_key_values(o, k, v) }
669/// fn refresh_value_counts(&self) -> Result<u64> { self.0.refresh_value_counts() }
670/// fn text_find(&self, q: &str, l: usize) -> Result<Vec<Hit>> { self.0.text_find(q, l) }
671/// fn vector_find(&self, m: &str, v: &[f32], l: usize) -> Result<Vec<Hit>> { self.0.vector_find(m, v, l) }
672/// fn put_embeddings(&self, m: &str, i: &[Embedding]) -> Result<()> { self.0.put_embeddings(m, i) }
673/// fn pending_embeddings(&self, m: &str, l: usize) -> Result<Vec<PendingEmbedding>> { self.0.pending_embeddings(m, l) }
674/// fn vector_available(&self) -> bool { self.0.vector_available() }
675/// fn log_miss(&self, q: &str) -> Result<()> { self.0.log_miss(q) }
676/// fn catalog_summary(&self) -> Result<Summary> { self.0.catalog_summary() }
677/// fn put_function_test(&self, t: &FunctionTest) -> Result<bool> { self.0.put_function_test(t) }
678/// fn function_tests(&self, f: &str) -> Result<Vec<FunctionTest>> { self.0.function_tests(f) }
679/// 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) }
680/// fn set_function_branches(&self, f: &str, t: u32, c: u32) -> Result<()> { self.0.set_function_branches(f, t, c) }
681/// fn function_readers(&self, n: &str) -> Result<Vec<String>> { self.0.function_readers(n) }
682/// fn bound_names(&self, f: &str) -> Result<Vec<String>> { self.0.bound_names(f) }
683/// }
684/// ```
685pub trait Store: Resolver + sealed::Sealed {
686 /// Writes the member-set row (G2, since 0.6.5): inserted when no row with its entry is held
687 /// (`Ok(true)`), otherwise nothing (`Ok(false)`, the held row kept). A row that is not
688 /// consistent (its entry, slice bytes, function hash or instants) is [`Error::Invalid`].
689 fn put_member_set(&self, set: &MemberSet) -> Result<bool> {
690 let mut set = set.clone();
691 set.licences = normal_licences(&set.licences)?;
692 check_member_set(&set)?;
693 self.put_member_set_checked(&set)
694 }
695
696 /// The highest insertion seq among the versions (withdrawals included) of the cells a slice
697 /// matches, whatever their recorded time; 0 when there are none. For a version slice, its cell's
698 /// versions (decided 26 Nov, G3: "inserted since", index-backed). Since 0.6.5.
699 fn slice_seq(&self, slice: &Slice) -> Result<i64> {
700 self.slice_seq_checked(slice)
701 }
702
703 /// The time a version signed at `signed_tx` is recorded at by the next put (G9): the greater of
704 /// `signed_tx` and this store's recording clock, or `signed_tx` with no clock. Exactly the rule the
705 /// puts apply, so publish-stored can compare against it. Since 0.6.5.
706 ///
707 /// Decided 27 Nov (B5): the puts also record a version after its cell's latest recorded time, a
708 /// microsecond later, so the time a put of a cell that already has versions records is later still.
709 /// This method gives the signed-tx-and-clock part only; a per-cell check must use the cell's latest.
710 fn recording_time(&self, signed_tx: &str) -> String {
711 crate::recorded_at(self.recording_clock_of().as_ref(), signed_tx)
712 }
713
714 /// The store's recording clock, not part of the API: the store's own implementations override it.
715 #[doc(hidden)]
716 fn recording_clock_of(&self) -> Option<RecordingClock> {
717 None
718 }
719
720 /// Waits for the writers of versions in flight, and returns at once when there is none (review item
721 /// 2): once it has passed, any writer still to come records a time later than it. The engine calls it
722 /// once per request, before its first store read. Since 0.6.5.
723 fn barrier(&self) -> Result<()> {
724 self.barrier_checked()
725 }
726
727 /// The read of `barrier`, not part of the API: the store's own implementations override it.
728 #[doc(hidden)]
729 fn barrier_checked(&self) -> Result<()> {
730 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no barrier here")))
731 }
732
733 /// The receipt hashes of the members of a slice as of `asof`, at most `limit`, in no particular order
734 /// (the engine sorts them, and uses the limit only to see whether there are more). Members are selected
735 /// as of `asof` by recorded time, the rules of `slice_members`; no values or receipt bytes are read.
736 /// Since 0.6.5.
737 fn slice_member_hashes(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<String>> {
738 Ok(hashes_limited(self.slice_members(slice, asof)?, limit))
739 }
740
741 /// The least start, over the versions of `cell_id` recorded after `recorded`, of `max(receipt asof,
742 /// recorded)`; `None` when none is recorded after (decided 27 Nov, A1: the memo bound, one aggregate
743 /// row). Since 0.6.5.
744 fn later_bound(&self, cell_id: &str, recorded: &str) -> Result<Option<String>> {
745 check_hex(cell_id, 64, "cell_id")?;
746 check_instant(recorded, "recorded")?;
747 self.later_bound_checked(cell_id, recorded)
748 }
749
750 /// The read of `later_bound`, not part of the API: the store's own implementations override it.
751 #[doc(hidden)]
752 fn later_bound_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<String>> {
753 let _ = (cell_id, recorded);
754 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no versions here")))
755 }
756
757 /// The receipt hashes of the members of a slice as of `asof`, at most `limit`, within `timeout`
758 /// (decided 27 Nov, B6: the rebuild listing under the budget's remaining time). On PostgreSQL the
759 /// statement runs under `statement_timeout`; on SQLite a progress deadline stops it. Past the timeout
760 /// the call fails with [`Error::Timeout`]. Since 0.6.5.
761 fn slice_member_hashes_within(
762 &self,
763 slice: &Slice,
764 asof: &str,
765 limit: usize,
766 timeout: std::time::Duration,
767 ) -> Result<Vec<String>> {
768 self.slice_member_hashes_within_checked(slice, asof, limit, timeout)
769 }
770
771 /// The read of `slice_member_hashes_within`, not part of the API. The default (no time bound) is the
772 /// listing of `slice_member_hashes`.
773 #[doc(hidden)]
774 fn slice_member_hashes_within_checked(
775 &self,
776 slice: &Slice,
777 asof: &str,
778 limit: usize,
779 timeout: std::time::Duration,
780 ) -> Result<Vec<String>> {
781 let _ = timeout;
782 self.slice_member_hashes(slice, asof, limit)
783 }
784
785 /// The first version of `cell_id` recorded after `recorded` (one row, the memo bound), or `None`.
786 /// Since 0.6.5.
787 fn next_version_after(&self, cell_id: &str, recorded: &str) -> Result<Option<Version>> {
788 check_hex(cell_id, 64, "cell_id")?;
789 check_instant(recorded, "recorded")?;
790 self.next_version_after_checked(cell_id, recorded)
791 }
792
793 /// The read of `next_version_after`, not part of the API: the store's own implementations override it.
794 #[doc(hidden)]
795 fn next_version_after_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<Version>> {
796 let _ = (cell_id, recorded);
797 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no versions here")))
798 }
799
800 /// The highest insertion seq among the versions (withdrawals included) of the functions `fn_hash`,
801 /// 0 when there are none: an upper bound of `slice_seq` for every slice of that function, in one
802 /// probe of the function's row (decided 26 Nov, G3: a slice whose `fn_seq` is at or below its row's
803 /// `seen_seq` is unchanged, with no candidate walk). Since 0.6.5.
804 fn fn_seq(&self, fn_hash: &str) -> Result<i64> {
805 check_hex(fn_hash, 64, "fn_hash")?;
806 self.fn_seq_checked(fn_hash)
807 }
808
809 /// The read of `fn_seq`, not part of the API: the store's own implementations override it.
810 #[doc(hidden)]
811 fn fn_seq_checked(&self, fn_hash: &str) -> Result<i64> {
812 let _ = fn_hash;
813 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no fn seq here")))
814 }
815
816 /// The read of `slice_seq`, not part of the API: the store's own implementations override it.
817 #[doc(hidden)]
818 fn slice_seq_checked(&self, slice: &Slice) -> Result<i64> {
819 let _ = slice;
820 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no slice seq here")))
821 }
822
823 /// The member-set row of `entry`, or `None` (G2, since 0.6.5).
824 fn member_set(&self, entry: &str) -> Result<Option<MemberSet>> {
825 check_member_entry(entry)?;
826 self.member_set_checked(entry)
827 }
828
829 /// Writes a slice's definition (G10, since 0.6.5), kept once per slice id (not per date):
830 /// `Ok(true)` when inserted, `Ok(false)` when held already.
831 fn put_slice_definition(&self, slice: &Slice) -> Result<bool> {
832 self.put_slice_definition_checked(slice)
833 }
834
835 /// The definition of the slice `slice_id`, or `None` (G10, since 0.6.5).
836 fn slice_definition(&self, slice_id: &str) -> Result<Option<Slice>> {
837 check_hex(slice_id, 64, "slice_id")?;
838 self.slice_definition_checked(slice_id)
839 }
840
841 /// The row of `put_member_set`, checked by the caller. Not part of the API: the store's own
842 /// implementations override it (a sealed trait, so no other implementation exists).
843 #[doc(hidden)]
844 fn put_member_set_checked(&self, set: &MemberSet) -> Result<bool> {
845 let _ = set;
846 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no member sets here")))
847 }
848 /// The row of `member_set`, checked by the caller. Not part of the API.
849 #[doc(hidden)]
850 fn member_set_checked(&self, entry: &str) -> Result<Option<MemberSet>> {
851 let _ = entry;
852 Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no member sets here")))
853 }
854 /// The write of `put_slice_definition`. Not part of the API.
855 #[doc(hidden)]
856 fn put_slice_definition_checked(&self, slice: &Slice) -> Result<bool> {
857 let _ = slice;
858 Err(Error::Invalid(datumesh_core::Error::new(
859 datumesh_core::ErrorCode::Schema,
860 "$",
861 "no slice definitions here",
862 )))
863 }
864 /// The read of `slice_definition`. Not part of the API.
865 #[doc(hidden)]
866 fn slice_definition_checked(&self, slice_id: &str) -> Result<Option<Slice>> {
867 let _ = slice_id;
868 Err(Error::Invalid(datumesh_core::Error::new(
869 datumesh_core::ErrorCode::Schema,
870 "$",
871 "no slice definitions here",
872 )))
873 }
874 /// Stores a descriptor (checked and canonicalised by the core); returns its function
875 /// hash. Idempotent.
876 fn put_descriptor(&self, bytes: &[u8]) -> Result<String>;
877 /// Stores a receipt that verifies (SPEC 10.1 steps 1-6) against the key document stored
878 /// for its signer host with [`put_namespace`](Store::put_namespace), in canonical form,
879 /// with an edge to each of its inputs; returns its hash. An input that is a slice entry
880 /// (`slice:<slice id>:<members hash>`, since 0.3.1) is recorded as such
881 /// ([`slice_entries`](Store::slice_entries)); its manifest need not be stored, before or
882 /// after (it is needed only to recompute, SPEC 10.1 step 7.5). The receipt's cell is
883 /// indexed by its typed arguments ([`slice_members`](Store::slice_members)). A receipt that does not verify
884 /// is refused with `verify`'s code (no key document for the host: `E_KEY_UNAVAILABLE`).
885 /// Idempotent: bytes whose canonical form is the stored copy return its hash without
886 /// checking the signature again (it verified when stored), even if the key has since
887 /// been revoked. Other bytes with a stored hash are verified first, then refused as
888 /// [`Error::Conflict`].
889 fn put_receipt(&self, bytes: &[u8]) -> Result<String>;
890 /// Stores blob content; returns its SHA-256 (lowercase hex). Idempotent.
891 fn put_blob(&self, bytes: &[u8]) -> Result<String>;
892 /// Blob content by SHA-256.
893 fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>>;
894 /// Appends a version: from `tx` on, `cell_id` has the value of receipt `receipt_hash`,
895 /// which must be stored, of that cell and at that tx. `tx` must be later than the cell's
896 /// latest version ([`Error::NotLater`]).
897 fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
898 /// The cell's latest version with `tx <= asof`.
899 fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
900 /// The cell's versions with `from <= tx <= to`, in tx order.
901 fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>>;
902 /// The cell's latest version.
903 fn latest(&self, cell_id: &str) -> Result<Option<Version>>;
904 /// [`latest`](Store::latest) of each of `cell_ids`, in input order (duplicates allowed;
905 /// empty input, empty result). The first malformed id is the error. Since 0.4.3.
906 fn latest_many(&self, cell_ids: &[&str]) -> Result<Vec<Option<Version>>> {
907 cell_ids.iter().map(|id| self.latest(id)).collect()
908 }
909 /// [`receipt`](Resolver::receipt) of each of `hashes`, in input order, as owned bytes.
910 /// Since 0.4.3.
911 fn receipts_many(&self, hashes: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
912 Ok(hashes.iter().map(|h| self.receipt(h).map(|b| b.into_owned())).collect())
913 }
914 /// For each item in order, [`put_receipt`](Store::put_receipt) and then, when the item
915 /// has a `version`, [`put_version`](Store::put_version); returns the receipt hashes.
916 /// All or nothing on PostgreSQL (one transaction; calls of up to 10,000 items are the
917 /// size it is written for). SQLite (and this default) loops, stops at the first error,
918 /// and need not be atomic: the items before a failing one stay stored there. Since 0.4.3.
919 fn put_cells(&self, items: &[CellWrite<'_>]) -> Result<Vec<String>> {
920 items
921 .iter()
922 .map(|w| {
923 let hash = self.put_receipt(w.receipt)?;
924 if let Some((cell_id, tx)) = w.version {
925 self.put_version(cell_id, tx, &hash)?;
926 }
927 Ok(hash)
928 })
929 .collect()
930 }
931 /// The stored receipts that list `receipt_hash` among their inputs, by hash. Only as
932 /// an input of its own: a receipt read as a member of a slice is found through its
933 /// manifests ([`member_manifests`](Store::member_manifests), then
934 /// [`slice_dependents`](Store::slice_dependents)).
935 fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>>;
936 /// The inputs of a stored receipt that are receipt hashes (whether or not they are
937 /// stored). Its slice entries are [`slice_entries`](Store::slice_entries).
938 fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>>;
939 /// Records a host's key document, checked as a 200 response for that host would be
940 /// (SPEC 9.2, 9.3), validated at `validated_at`. Re-validation replaces the document; a
941 /// `validated_at` earlier than the recorded one is [`Error::NotLater`]. Receipts already
942 /// stored are not re-checked: they verified when they were stored (and putting one again
943 /// stays idempotent).
944 fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()>;
945 /// A host's recorded key document.
946 fn namespace(&self, host: &str) -> Result<Option<Namespace>>;
947 /// Every recorded namespace, by host. Since the namespace checks (since 0.4.1).
948 fn namespaces(&self) -> Result<Vec<Namespace>>;
949 /// Records a failed check of `host`'s key document at `checked_at` (domain validation):
950 /// the consecutive failures grow by one, and when they reach `threshold` (zero counts as
951 /// one) the namespace is suspended at `checked_at`, unless it already is (the first
952 /// suspension's time is kept). While it is suspended the store refuses new writes under
953 /// the host: `put_receipt` of a receipt signed by it, `put_version` of such a receipt
954 /// and `bind_name` of a name under it ([`Error::NamespaceSuspended`]); reads,
955 /// verification and the stored key document are not affected, and neither is putting a
956 /// receipt that is already stored. Returns the namespace as recorded, or `None` for a
957 /// host with no namespace (there is nothing to suspend). A `checked_at` earlier than the
958 /// latest check is [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
959 fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>>;
960 /// Records a successful check of `host`'s key document at `checked_at`: the consecutive
961 /// failures are reset to zero and a suspension is lifted (the namespace is reinstated).
962 /// The document itself is recorded with [`put_namespace`](Store::put_namespace) (which
963 /// neither suspends nor reinstates). Returns the namespace as recorded, or `None` for a
964 /// host with no namespace. A `checked_at` earlier than the latest check is
965 /// [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
966 fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>>;
967 /// Appends a binding: from `tx` on, the fully qualified function name `fn_name` means
968 /// `fn_hash`, whose descriptor must be stored. `tx` must be later than the name's latest
969 /// binding ([`Error::NotLater`]).
970 fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()>;
971 /// The function hash `fn_name` meant as of `asof`: the hash of
972 /// [`resolve_binding`](Store::resolve_binding)'s binding.
973 fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>>;
974 /// The binding of `fn_name` that answers as of `asof`: the one with the latest `tx <=
975 /// asof`, with its function hash and its `tx`, when it began; `None` before the first.
976 /// A name bound again to a hash it meant before (even the hash of the binding before
977 /// it) begins again: the later binding's `tx`. Since 0.3.0.
978 fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>>;
979
980 /// Stores a class descriptor (SPEC 16.1, 16.2) under its class hash and returns the hash.
981 /// Since 0.4.1.
982 ///
983 /// `bytes` must be a **flattened** descriptor in **canonical form** (the bytes
984 /// `ClassDescriptor::canonical` gives, 6.2: what the class hash hashes). The core checks it
985 /// (`ClassDescriptor::from_json`: strict JSON, then 16.1 in its check order; a flattened
986 /// descriptor passes). Bytes that are a valid descriptor but not the canonical form of
987 /// it (white space, members out of order) are refused with [`Error::Invalid`], code
988 /// `E_SCHEMA`, and nothing is stored: unlike [`put_descriptor`](Store::put_descriptor),
989 /// which canonicalises, the bytes put are the bytes stored, so the class hash is the
990 /// SHA-256 of what [`class`](Store::class) returns. Idempotent for the same bytes.
991 ///
992 /// The store does not flatten (that is define's, with the parent in hand), and does not
993 /// need the parent, the method functions or the interfaces to be stored (`bind_class`
994 /// needs the methods' descriptors). It does not check the owner either (16.2 step 1 is the
995 /// definer's check: the store records, http and the engine enforce). It is a write under
996 /// the class's steward namespace (`steward.namespace`): refused with
997 /// [`Error::NamespaceSuspended`] while that namespace is suspended, even for a class
998 /// already stored.
999 fn put_class(&self, bytes: &[u8]) -> Result<String>;
1000 /// The canonical bytes of the class descriptor with this class hash, as stored
1001 /// ([`put_class`](Store::put_class)); `None` when no such class is stored. A malformed
1002 /// hash is `E_CANON_HEX`. Never refused under a suspended namespace. Since 0.4.1.
1003 fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>>;
1004 /// Binds the class name `class_name` (a full name, 2.3) to the stored class `class_hash`
1005 /// from `tx` on and, in the same transaction, binds each method `<class_name>/<m>` of the
1006 /// stored (flattened, so inherited methods included) descriptor to the method's function
1007 /// hash from the same `tx` (SPEC 16.3, 9.7). All of it or nothing:
1008 ///
1009 /// - the class must be stored ([`Error::NotFound`], `what` `"class"`), and so must every
1010 /// method's function descriptor ([`Error::NotFound`], `what` `"descriptor"`, the missing
1011 /// function hash; the first in JCS order of method names);
1012 /// - class names and function names share one namespace of names: `class_name`, or a
1013 /// method name, whose latest binding is of the other kind (a function for `class_name`,
1014 /// a class for a method name) is refused with [`Error::NameTaken`]. A method name bound
1015 /// as a function, to whatever hash, is simply bound again;
1016 /// - `tx` must be later than the latest binding of `class_name` and of each method name
1017 /// ([`Error::NotLater`], `what` `"name"`, the name that is not);
1018 /// - while the namespace of `class_name`'s host is suspended: [`Error::NamespaceSuspended`].
1019 ///
1020 /// The store does not check that the class name is under the steward's namespace, nor
1021 /// who binds it (the definer's check, 16.2 step 1). Since 0.4.1.
1022 ///
1023 /// Since 0.5.4 (K5), only the methods the class adds or overrides are bound under its name:
1024 /// those whose function hash its parent's flattened descriptor does not give (or that the
1025 /// parent does not have). An inherited method's name is not bound, so `S/m` of an inherited
1026 /// `m` answers `None`. Under 0.5.3 every flattened method was bound.
1027 fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()>;
1028 /// Closes the latest binding of `name`, a function name or a class name, from `at` on: as
1029 /// of `at` or later the name resolves to `None` (also through
1030 /// [`resolve_binding`](Store::resolve_binding) and [`resolve_class_binding`](Store::resolve_class_binding)),
1031 /// and as of an earlier instant the binding it had. Closing a class name closes its
1032 /// method names (`<class name>/<m>`, the ones [`bind_class`](Store::bind_class) bound) from
1033 /// the same `at`. The name may be bound again later ([`bind_name`](Store::bind_name),
1034 /// [`bind_class`](Store::bind_class)), with a `tx` after `at`. Each close is one row of the
1035 /// binding history (with `written_at`). `at` must be later than the latest binding of the
1036 /// name; a name with no binding, or whose latest binding is closed, is [`Error::NotFound`]
1037 /// (`what` is `binding`). A malformed instant is `E_CANON_INSTANT`. The default is
1038 /// [`Error::Unsupported`]. Since 0.6.0.
1039 fn close_binding(&self, name: &str, at: &str) -> Result<()> {
1040 let _ = (name, at);
1041 Err(Error::Unsupported("closing a binding needs a store of 0.6.0".into()))
1042 }
1043 /// The class hash `class_name` meant as of `asof`: the hash of
1044 /// [`resolve_class_binding`](Store::resolve_class_binding)'s binding. `None` before the
1045 /// first binding, and for a name whose binding as of `asof` is a function's. Since 0.4.1.
1046 fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>>;
1047 /// The class binding of `class_name` that answers as of `asof`: the latest with
1048 /// `tx <= asof`, with its class hash and its `tx` (when it began; binding the same hash
1049 /// again begins again), as [`resolve_binding`](Store::resolve_binding) does for functions.
1050 /// `None` before the first, and for a function name. The function accessors
1051 /// ([`resolve_name`](Store::resolve_name), [`resolve_binding`](Store::resolve_binding))
1052 /// answer `None` for a class name: a bindings answer (9.7) has `fn_hash` or `class_hash`,
1053 /// never both. Since 0.4.1.
1054 fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>>;
1055 /// The class names whose class binding as of `at` (the latest with `tx <= at`, as
1056 /// [`resolve_class_binding`](Store::resolve_class_binding) takes it) is `class_hash`, in byte
1057 /// order, each once. A name rebound to another hash is no longer listed from that binding's
1058 /// `tx` on. Function names are never listed. Empty when none is bound (also when the hash is
1059 /// not stored, or `at` is before the first binding). A malformed hash is `E_CANON_HEX`, a
1060 /// malformed instant `E_CANON_INSTANT`. The default is [`Error::Unsupported`]. Since 0.5.3.
1061 fn class_names_bound_to(&self, class_hash: &str, at: &str) -> Result<Vec<String>> {
1062 let _ = (class_hash, at);
1063 Err(Error::Unsupported("class names need a store of 0.5.3".into()))
1064 }
1065
1066 /// Records that `receipt_hash` (stored, a receipt of `cell_id` at `tx`) is a computed
1067 /// version of the cell. Insert-only, in any order (an older version may be added after a
1068 /// newer one): `tx` need not be later than anything. The version's asof is the
1069 /// receipt's. Idempotent for the same (cell_id, tx, asof, receipt_hash); another receipt
1070 /// for an existing (cell_id, tx, asof) is [`Error::Conflict`] (its `hash` is the receipt
1071 /// refused) and the stored one is kept. The receipt is checked as for
1072 /// [`put_version`](Store::put_version): [`Error::NotFound`] when it is not stored,
1073 /// [`Error::Mismatch`] when it is of another cell or at another tx. Since 0.2.0.
1074 fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
1075 /// The computed version that answers as of `asof`: the one with the greatest asof <=
1076 /// `asof` (between equal asof, the greatest tx), or `None`. Since 0.2.0.
1077 fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
1078 /// The stored version that answers as of `asof`: the latest version (by tx) with `tx <=
1079 /// asof` whose receipt's asof is also `<= asof`, or `None`. A version whose receipt is
1080 /// late-signed (asof later than tx) answers only from its asof on; until then the
1081 /// version before it answers. ([`version_asof`](Store::version_asof) keeps its tx-only
1082 /// meaning.) Since 0.2.0.
1083 fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
1084 /// The cells that read `cell_id`: the cell ids of the stored receipts that list, among
1085 /// their inputs, any stored receipt of `cell_id` (lineage: edges joined to receipts),
1086 /// or (since 0.3.1) a slice entry whose stored manifest lists one as a member.
1087 /// Ascending, each once. Since 0.2.0.
1088 fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>>;
1089
1090 /// Stores a manifest (SPEC 15.13), `{"members": [...], "slice": {...}}`: parsed strictly
1091 /// and checked by the core (`Manifest::from_json`: structure, members, their order and
1092 /// limit, the slice object), kept in canonical form under its entry
1093 /// `slice:<slice id>:<members hash>`, which it returns, and recorded for each member
1094 /// ([`member_manifests`](Store::member_manifests)). The members need not be stored.
1095 /// Idempotent; insert-only (the entry is a hash of the content, so a stored entry
1096 /// always has these bytes). Served by [`manifest`](Resolver::manifest). Since 0.3.1.
1097 fn put_manifest(&self, bytes: &[u8]) -> Result<String>;
1098 /// The entries of the stored manifests that list `receipt_hash` among their members,
1099 /// ascending: from a member, the slices it was read in (then
1100 /// [`slice_dependents`](Store::slice_dependents)). Since 0.3.1.
1101 fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>>;
1102 /// The slice entries among the inputs of a stored receipt, ascending. Since 0.3.1.
1103 fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>>;
1104 /// The stored receipts whose inputs list the slice entry `entry`, by hash, ascending.
1105 /// An entry is `slice:` and two 64-digit hashes (`E_CANON_HEX` otherwise). Since 0.3.1.
1106 fn slice_dependents(&self, entry: &str) -> Result<Vec<String>>;
1107 /// The members of `slice` as of `asof` (SPEC 15.13), with the stored version of each
1108 /// that answers as of `asof` and its receipt's bytes.
1109 ///
1110 /// For a slice of cells: the cells of the slice's function (its `fn_hash`, `ns` and
1111 /// `fn`, with the same argument names) whose bound arguments are the same typed scalar,
1112 /// whose ranged arguments are of the range's type and within it (`lo <= v <= hi`,
1113 /// inclusive, in the type's order: numbers as exact decimals, dates and instants
1114 /// chronologically, strings by code point; `lo` after `hi` is empty), any value for an
1115 /// open argument, and that have a stored version answering as of `asof`: as
1116 /// [`stored_asof`](Store::stored_asof), the latest version with `tx <= asof` whose
1117 /// receipt's `asof <= asof` (so a late-signed version is not a member's answer before
1118 /// its asof, and a correction replaces a member's version from its asof on). Computed
1119 /// versions are not members. In key order: by the open and ranged arguments in
1120 /// ascending name order, each in its type's order (`false` before `true`; blobs as
1121 /// text); the cell id last, for two cells whose key arguments are of different types.
1122 ///
1123 /// For a version slice `{"cell", "from", "to"}`: [`versions_between`](Store::versions_between)
1124 /// of its cell. Empty when nothing matches. Since 0.3.1.
1125 fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>>;
1126 /// The stored versions of `cell_id` with `from <= tx <= to` that answer as of `asof`
1127 /// (`tx <= asof` and the receipt's `asof <= asof`), ascending by tx, each with its
1128 /// receipt's bytes: SPEC 15.13's version slice. Empty when `from` is after `to`. Since
1129 /// 0.3.1.
1130 fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>>;
1131 /// The members [`slice_members`](Store::slice_members) gives, in its order and by its
1132 /// answering rule, each as its version, its receipt's typed value and its cell (with its
1133 /// arguments), without the receipt's bytes (the value is a stored column of the receipt
1134 /// and the cell comes from the typed-argument index, neither parsed per call).
1135 /// Since 0.3.2.
1136 fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>>;
1137 /// Whether the members of `slice`, or their versions, may answer differently as of some
1138 /// time after `asof`: whether a cell matching the slice has a stored version whose
1139 /// receipt's `asof` is after `asof` (its `tx` is never later than that), for a version
1140 /// slice one with `tx` in `[from, to]`. `false` means [`slice_members`](Store::slice_members)
1141 /// (and `slice_values`) give the same answer as of every time from `asof` on, until a
1142 /// version is stored with an asof after it; `true` may be conservative (a late-signed
1143 /// version superseded before its asof never answers). Index scans only, whatever the
1144 /// slice's size: two bounded probes (at most 10,001 entries each) choose whether to walk
1145 /// the function's receipts with an asof after `asof` or the slice's candidate cells,
1146 /// whichever is fewer, and one query walks it, stopping at the first match. Since 0.3.2.
1147 fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool>;
1148 /// The latest withdrawal among the cells that match `slice` (SPEC 8.2, spec-0.7.0): among
1149 /// the cells whose version answering as of `asof` (the rule of `stored_asof`) is a
1150 /// withdrawal, the greatest by `tx`, then by `asof`; its `(tx, asof)`. `None` when no such
1151 /// cell. A version slice's one cell counts when its answering version is a withdrawal with
1152 /// a `tx` in the slice's range. A malformed instant is `E_CANON_INSTANT`. The default is
1153 /// [`Error::Unsupported`]. Since 0.6.0.
1154 fn slice_withdrawn_latest(&self, slice: &Slice, asof: &str) -> Result<Option<(String, String)>> {
1155 let _ = (slice, asof);
1156 Err(Error::Unsupported("the withdrawn cells of a slice need a store of 0.6.0".into()))
1157 }
1158 /// The cells of `slice` (matched as [`slice_values`](Store::slice_values) matches them: the
1159 /// fixed arguments, `fn_hash`, `ns`, `fn` and the number of arguments) that have a computed
1160 /// version answering as of `asof`: one with `tx <= asof` whose receipt's asof is `<= asof`
1161 /// (the rule of [`computed_asof`](Store::computed_asof)). Ascending by cell id, at most
1162 /// `limit` (`slice_values` takes no limit), each with its arguments from the typed-argument
1163 /// index. A cell with only a stored version is not returned. Since 0.4.2.
1164 fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>>;
1165 /// Whether any name binding or class binding has a name starting with `namespace` and `/`
1166 /// (so `"a.example/n"` is not a namespace of `"a.example/ns/f"`). Since 0.4.2.
1167 fn has_bindings_under(&self, namespace: &str) -> Result<bool>;
1168
1169 /// Inserts or replaces catalogue entries, keyed by (kind, name); returns each entry's id,
1170 /// in order. All or nothing: every entry is checked first (the name by the core's rules,
1171 /// `hash` as 64 hex digits, the bounds of [`CatalogEntry`]) and refused with
1172 /// [`Error::Invalid`] before anything is written. An operator's entry never replaces a
1173 /// publisher's: that entry is kept, and the call still answers its id. A publisher's
1174 /// replaces either. Replacing an entry's label or description drops its embedding.
1175 /// Since 0.5.0.
1176 fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>>;
1177 /// Inserts or replaces the values of `key` of `owner` (a function or class name): each
1178 /// value's label and aliases are replaced, and its `n_cells` is kept. Values not in
1179 /// `values` stay (an upsert adds and replaces, it does not prune). Returns each value's
1180 /// id, in order. Replacing a value's label drops its embedding. Since 0.5.0.
1181 fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>>;
1182 /// Sets every dictionary value's `n_cells` to the number of cells of the function named
1183 /// by its owner that have that value for the key; returns the number of rows refreshed
1184 /// (every value, changed or not). Since 0.5.0.
1185 fn refresh_value_counts(&self) -> Result<u64>;
1186 /// The entries and dictionary values that match every word of `query` (split on white
1187 /// space; a word matches case-insensitively, literally, in any field of the entry or
1188 /// value, and scores 1.0 as a whole field, 0.8 as one of a field's words, 0.5 inside a
1189 /// field; a score is the mean over the words, in (0, 1]). Best first, ties by name; at
1190 /// most `limit`. A blank query finds nothing. Since 0.5.0.
1191 fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>>;
1192 /// The entries and values nearest to `vec` by cosine similarity, among those with an
1193 /// embedding for `model`: each score is 1 minus the cosine distance (1.0 for the same
1194 /// direction), best first, at most `limit`. `vec` has 384 finite values, not all zero
1195 /// ([`Error::Invalid`] otherwise). [`Error::Unsupported`] where
1196 /// [`vector_available`](Store::vector_available) is false. Since 0.5.0.
1197 fn vector_find(&self, model: &str, vec: &[f32], limit: usize) -> Result<Vec<Hit>>;
1198 /// Stores embeddings for `model`, one per (kind, id, model): an existing one is replaced.
1199 /// All or nothing; a reference to an entry or value that is not stored is
1200 /// [`Error::NotFound`], and a vector is checked as [`vector_find`](Store::vector_find)
1201 /// checks it. [`Error::Unsupported`] where `vector_available` is false. Since 0.5.0.
1202 fn put_embeddings(&self, model: &str, items: &[Embedding]) -> Result<()>;
1203 /// Up to `limit` entries and values with no embedding for `model`, with the text to embed
1204 /// (see [`PendingEmbedding`]). Empty where `vector_available` is false (nothing can be
1205 /// stored there). Since 0.5.0.
1206 fn pending_embeddings(&self, model: &str, limit: usize) -> Result<Vec<PendingEmbedding>>;
1207 /// Whether vectors can be stored and searched by this store: PostgreSQL with the `vector`
1208 /// extension, where the migration made the `embeddings` table. Looked at when the store
1209 /// is opened (migrate before opening, as the schema is then in place). Since 0.5.0.
1210 fn vector_available(&self) -> bool;
1211 /// Records a find that found nothing: the query's text (trimmed, at most 512 bytes; a
1212 /// blank query records nothing) and the time. The store keeps at most
1213 /// [`FIND_MISSES_CAP`] rows, pruning the oldest. Since 0.5.0.
1214 fn log_miss(&self, query: &str) -> Result<()>;
1215 /// The catalogue as an operator reads it: every entry with its label and its cell count,
1216 /// and every dictionary with its first 50 values (by value) and how many it has. Since 0.5.0.
1217 fn catalog_summary(&self) -> Result<Summary>;
1218
1219 /// Stores a function test, if its (fn_hash, case) has none: `Ok(true)` when the row is
1220 /// inserted, `Ok(false)` when one exists, in which case nothing changes (the first
1221 /// writer's `signed_by` and `test_json` stay). The test is checked first: a 64-digit
1222 /// hash, a 16-digit case, a canonical `test_json`, a signer of 1 to 256 bytes, an instant
1223 /// and result if it carries them, and branch counts with covered not above total, each
1224 /// at most `i32::MAX`; a failing check is [`Error::Invalid`] and nothing is stored.
1225 /// Since 0.5.1.
1226 fn put_function_test(&self, test: &FunctionTest) -> Result<bool>;
1227 /// Every test of `fn_hash`, ordered by case ascending; empty when there are none. Since 0.5.1.
1228 fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>>;
1229 /// Records a run of the test (`fn_hash`, `case`): sets its `last_run_at` (the instant
1230 /// `run_at`), `last_result` and `last_detail`. `Ok(true)` when the test exists; `Ok(false)`
1231 /// when it does not, and nothing is inserted. `result` must be `pass`, `fail` or `error`:
1232 /// any other value is [`Error::Invalid`], and nothing changes. Since 0.5.1.
1233 fn record_function_test(&self, fn_hash: &str, case: &str, run_at: &str, result: &str, detail: &str)
1234 -> Result<bool>;
1235 /// Sets `branches_total` and `branches_covered` on every test of `fn_hash`. A function
1236 /// with no tests is a no-op, not an error. `covered` above `total` is [`Error::Invalid`].
1237 /// Since 0.5.1.
1238 fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()>;
1239 /// The function hashes of the stored descriptors whose `inputs` contain `name` (a fully
1240 /// qualified function name), distinct, ascending. Answered from the index of descriptor
1241 /// inputs, which [`put_descriptor`](Store::put_descriptor) fills; the migration that
1242 /// introduced the index filled it from the descriptors stored before. Since 0.5.1.
1243 fn function_readers(&self, name: &str) -> Result<Vec<String>>;
1244 /// Every fully qualified name ever bound (by [`bind_name`](Store::bind_name)) to
1245 /// `fn_hash`, distinct, ascending. A name since bound to another hash still lists this
1246 /// one. Since 0.5.1.
1247 fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>>;
1248
1249 /// Sets the function name of tests of `fn_hash`: each `(case, fn_name)` names the test of
1250 /// that case, if it has no name yet. A name once set is never changed, and a case with no
1251 /// test changes nothing. Returns the number of tests named (rows changed); an empty list
1252 /// is 0. The default is [`Error::Unsupported`]. Since 0.5.2.
1253 fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
1254 let _ = (fn_hash, names);
1255 Err(Error::Unsupported("naming function tests needs a store of 0.5.2".into()))
1256 }
1257 /// Up to `limit` tests that have no function name, ordered by (function hash, case), each
1258 /// as [`function_tests`](Store::function_tests) gives it. Naming them drains the list. The
1259 /// default is [`Error::Unsupported`]. Since 0.5.2.
1260 fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
1261 let _ = limit;
1262 Err(Error::Unsupported("unnamed tests need a store of 0.5.2".into()))
1263 }
1264 /// The summary of the tests of `fn_hash` in one aggregate: every test of the hash when
1265 /// `fn_name` is `None`, else only those named `fn_name`. A hash with no such test gives the
1266 /// zero summary ([`TestSummary::default`]). The default computes it from
1267 /// [`function_tests`](Store::function_tests) when `fn_name` is `None`, and is
1268 /// [`Error::Unsupported`] for a name (0.5.1 does not give a test's name). Since 0.5.2.
1269 fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
1270 if fn_name.is_some() {
1271 return Err(Error::Unsupported("a summary by function name needs a store of 0.5.2".into()));
1272 }
1273 let mut s = TestSummary::default();
1274 for t in self.function_tests(fn_hash)? {
1275 s.count += 1;
1276 match t.last_result.as_deref() {
1277 Some("pass") => s.pass += 1,
1278 Some("fail") => s.fail += 1,
1279 Some("error") => s.error += 1,
1280 _ => s.not_run += 1,
1281 }
1282 if let Some(at) = t.last_run_at {
1283 if s.last_run_at.as_ref().is_none_or(|latest| at > *latest) {
1284 s.last_run_at = Some(at);
1285 }
1286 }
1287 s.branches_total = s.branches_total.max(t.branches_total);
1288 s.branches_covered = s.branches_covered.max(t.branches_covered);
1289 }
1290 Ok(s)
1291 }
1292 /// A page of the tests of `fn_hash` by case ascending: those named `fn_name` (or all, when
1293 /// `None`), with a case after `after_case` (exclusive, when given), at most `limit`.
1294 /// Whole rows, as [`function_tests`](Store::function_tests) gives them. The default is the
1295 /// page of [`function_tests`](Store::function_tests) when `fn_name` is `None`, and is
1296 /// [`Error::Unsupported`] for a name. Since 0.5.2.
1297 fn function_tests_page(
1298 &self,
1299 fn_hash: &str,
1300 fn_name: Option<&str>,
1301 after_case: Option<&str>,
1302 limit: usize,
1303 ) -> Result<Vec<FunctionTest>> {
1304 if fn_name.is_some() {
1305 return Err(Error::Unsupported("a page by function name needs a store of 0.5.2".into()));
1306 }
1307 Ok(self
1308 .function_tests(fn_hash)?
1309 .into_iter()
1310 .filter(|t| after_case.is_none_or(|after| t.case.as_str() > after))
1311 .take(limit)
1312 .collect())
1313 }
1314 /// The receipts (bytes, as [`receipt`](Resolver::receipt) returns them) of the latest
1315 /// stored version of up to `limit` cells of `ns`/`fn_name`/`fn_hash` that have one, lowest
1316 /// cell id first: at most `limit` cells are read. The default is [`Error::Unsupported`]
1317 /// (0.5.1 has no read of a function's cells without a slice). Since 0.5.2.
1318 fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
1319 let _ = (ns, fn_name, fn_hash, limit);
1320 Err(Error::Unsupported("stored receipts of a function need a store of 0.5.2".into()))
1321 }
1322 /// [`slice_values`](Store::slice_values) with at most `limit` members: the first `limit` of
1323 /// its order (the same members, in the same order). The default takes them from
1324 /// `slice_values`. Since 0.5.2.
1325 fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
1326 let mut values = self.slice_values(slice, asof)?;
1327 values.truncate(limit);
1328 Ok(values)
1329 }
1330 /// [`versions`](Store::versions) with at most `limit` versions: the first `limit`, in tx
1331 /// order. The default takes them from `versions`. Since 0.5.2.
1332 fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
1333 let mut versions = self.versions(cell_id, from, to)?;
1334 versions.truncate(limit);
1335 Ok(versions)
1336 }
1337 /// The number of cells of `ns`/`fn_name`/`fn_hash` that have a stored version (a second
1338 /// version of a cell is not a second cell). The default is [`Error::Unsupported`]. Since
1339 /// 0.5.2.
1340 fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
1341 let _ = (ns, fn_name, fn_hash);
1342 Err(Error::Unsupported("counting a function's cells needs a store of 0.5.2".into()))
1343 }
1344 /// Whether `owner` has the dictionary value `value` for `key`, exactly (the value's text,
1345 /// case-sensitive; no prefix, substring or label match). Indexed in the native stores. The
1346 /// default asks [`text_find`](Store::text_find) for `value` and keeps the exact match.
1347 /// Since 0.5.2.
1348 fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
1349 Ok(self.text_find(value, usize::MAX)?.iter().any(
1350 |h| matches!(h, Hit::Value { owner: o, key: k, value: v, .. } if o == owner && k == key && v == value),
1351 ))
1352 }
1353 /// The number of dictionary values `owner` has for `key`. The default is
1354 /// [`Error::Unsupported`]. Since 0.5.2.
1355 fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
1356 let _ = (owner, key);
1357 Err(Error::Unsupported("counting a dictionary needs a store of 0.5.2".into()))
1358 }
1359 /// Marks the key `key` of `owner` open: it takes no automatic values from now on. Marking
1360 /// an open key again changes nothing. Its existing values stay. The default is
1361 /// [`Error::Unsupported`]. Since 0.5.2.
1362 fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
1363 let _ = (owner, key);
1364 Err(Error::Unsupported("open keys need a store of 0.5.2".into()))
1365 }
1366 /// Whether the key `key` of `owner` has been marked open ([`mark_key_open`](Store::mark_key_open)).
1367 /// The default is [`Error::Unsupported`]. Since 0.5.2.
1368 fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
1369 let _ = (owner, key);
1370 Err(Error::Unsupported("open keys need a store of 0.5.2".into()))
1371 }
1372 /// The number of keys marked open, of any owner ([`mark_key_open`](Store::mark_key_open)).
1373 /// The default is 0, which is exact for a store with no open key. Since 0.5.2.
1374 fn open_key_count(&self) -> Result<u64> {
1375 Ok(0)
1376 }
1377 /// The catalogue entry named `name` (exactly), if there is one. A name may be the name of a
1378 /// function and of a class; the function's entry is given first, then a method's, then a
1379 /// class's. The default is [`Error::Unsupported`]. Since 0.5.2.
1380 fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
1381 let _ = name;
1382 Err(Error::Unsupported("an exact catalogue lookup needs a store of 0.5.2".into()))
1383 }
1384
1385 /// Inserts or replaces catalogue entries with their facets and `extends`, keyed by (kind,
1386 /// name), as [`upsert_catalog`](Store::upsert_catalog) does, and replaces the facets and
1387 /// `extends` of an existing row. Checked first, all or nothing ([`Error::Invalid`]): the
1388 /// facets (a key of domain, thing, measure, region or frequency; 1 to 8 names each, names of
1389 /// at most 32 bytes, ascending and unique), and `extends` (a full function name, on a
1390 /// function only). The store does not check that `extends` names a stored class, nor the key
1391 /// rule of 16.3. Returns each entry's id, in order. The default is [`Error::Unsupported`].
1392 /// Since 0.6.0.
1393 fn upsert_catalog_ext(&self, entries: &[CatalogEntryExt]) -> Result<Vec<i64>> {
1394 let _ = entries;
1395 Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
1396 }
1397 /// The catalogue entry of kind `kind` and name `name` (exactly), with its facets and
1398 /// `extends`, if there is one. The default is [`Error::Unsupported`]. Since 0.6.0.
1399 fn catalog_entry_ext(&self, kind: CatalogKind, name: &str) -> Result<Option<CatalogEntryExt>> {
1400 let _ = (kind, name);
1401 Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
1402 }
1403 /// The entries that have at least one facet, by kind (as text: class, function, method)
1404 /// then name in byte order, each with its first binding time (see [`FacetedEntry`]).
1405 /// The default is [`Error::Unsupported`]. Since 0.6.0.
1406 fn catalog_entries_with_facets(&self) -> Result<Vec<FacetedEntry>> {
1407 Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
1408 }
1409 /// The function entries whose `extends` is `class`, by name in byte order. A `class` that
1410 /// is not a full name is [`Error::Invalid`]. The default is [`Error::Unsupported`]. Since 0.6.0.
1411 fn extensions_of(&self, class: &str) -> Result<Vec<CatalogEntryExt>> {
1412 let _ = class;
1413 Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
1414 }
1415 /// [`extensions_of`](Store::extensions_of) with at most `limit` entries: the first `limit` by name (CONTRACT-round-0.7 R11,
1416 /// the bounded read of a describe). The backends read `limit` rows (`LIMIT`, with the index on `extends`). The default takes
1417 /// them from `extensions_of`. Since 0.6.0.
1418 fn extensions_of_limit(&self, class: &str, limit: usize) -> Result<Vec<CatalogEntryExt>> {
1419 let mut all = self.extensions_of(class)?;
1420 all.truncate(limit);
1421 Ok(all)
1422 }
1423
1424 /// The number of cells of `ns`/`fn_name`/`fn_hash`: every cell with a stored receipt, a
1425 /// second version of a cell not counted again. Read from the counter (PK), not counted
1426 /// over the cells. The default is [`stored_cell_count`](Store::stored_cell_count). Since
1427 /// 0.5.3.
1428 fn cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
1429 self.stored_cell_count(ns, fn_name, fn_hash)
1430 }
1431 /// The test of `fn_hash` with case `case` (16 hex digits), if there is one: one row by
1432 /// primary key, as [`function_tests`](Store::function_tests) gives it. The default takes
1433 /// it from [`function_tests`](Store::function_tests). Since 0.5.3.
1434 fn function_test(&self, fn_hash: &str, case: &str) -> Result<Option<FunctionTest>> {
1435 Ok(self.function_tests(fn_hash)?.into_iter().find(|t| t.case == case))
1436 }
1437 /// Up to `limit` tests of `fn_hash` whose last result is `fail` or `error`, by case
1438 /// ascending, among those named `fn_name` (or all, when `None`). A SQL limit: the rows
1439 /// past it are not read. The default pages [`function_tests_page`](Store::function_tests_page)
1440 /// (which is [`Error::Unsupported`] for a name). Since 0.5.3.
1441 fn function_tests_failing(&self, fn_hash: &str, fn_name: Option<&str>, limit: usize) -> Result<Vec<FunctionTest>> {
1442 let mut out = Vec::new();
1443 if limit == 0 {
1444 return Ok(out);
1445 }
1446 let mut after: Option<String> = None;
1447 loop {
1448 let page = self.function_tests_page(fn_hash, fn_name, after.as_deref(), 256)?;
1449 let Some(last) = page.last() else { return Ok(out) };
1450 after = Some(last.case.clone());
1451 for t in page {
1452 if matches!(t.last_result.as_deref(), Some("fail") | Some("error")) {
1453 out.push(t);
1454 if out.len() == limit {
1455 return Ok(out);
1456 }
1457 }
1458 }
1459 }
1460 }
1461 /// The stored `test_case` cells of any namespace whose `function_hash` argument is
1462 /// `fn_hash` and whose latest version is `false`: each as (cell id, the bytes of the
1463 /// receipt of that latest version), at most `limit`, in one query. The default is
1464 /// [`Error::Unsupported`]. Since 0.5.3.
1465 fn false_test_cells(&self, fn_hash: &str, limit: usize) -> Result<Vec<(String, Vec<u8>)>> {
1466 let _ = (fn_hash, limit);
1467 Err(Error::Unsupported("false test cells need a store of 0.5.3".into()))
1468 }
1469 /// The names bound at `at` to a function hash that reads `name` (its descriptor's inputs
1470 /// name it), as (name, fn_hash), at most `limit`. The default walks
1471 /// [`function_readers`](Store::function_readers), [`bound_names`](Store::bound_names) and
1472 /// [`resolve_name`](Store::resolve_name). Since 0.5.3.
1473 fn dependants_of(&self, name: &str, at: &str, limit: usize) -> Result<Vec<(String, String)>> {
1474 let mut out = Vec::new();
1475 if limit == 0 {
1476 return Ok(out);
1477 }
1478 for h in self.function_readers(name)? {
1479 for n in self.bound_names(&h)? {
1480 if self.resolve_name(&n, at)?.as_deref() == Some(h.as_str()) {
1481 out.push((n, h.clone()));
1482 if out.len() == limit {
1483 return Ok(out);
1484 }
1485 }
1486 }
1487 }
1488 Ok(out)
1489 }
1490 /// A page of the members of `slice` as of `asof` in sort-key order (CONTRACT-0.5.1 S2):
1491 /// those whose [`SliceValue::sort_key`] is greater than `after` (exclusive; all of them
1492 /// when `None`), at most `limit`, with the same membership as
1493 /// [`slice_values`](Store::slice_values) (fixed arguments, ranges, the latest version as of
1494 /// `asof`, withdrawals left out), so that a walk of pages, each from the last member's key,
1495 /// gives `slice_values` member for member. A version slice has no key order to page by:
1496 /// [`Error::Unsupported`]. The default takes all of `slice_values` and pages them; the
1497 /// stores read the index of the function's cells. Since 0.6.4.
1498 fn slice_page(&self, slice: &Slice, asof: &str, after: Option<&[u8]>, limit: usize) -> Result<Vec<SliceValue>> {
1499 if slice.is_version_slice() {
1500 return Err(Error::Unsupported("a version slice has no key order to page by".into()));
1501 }
1502 if limit == 0 {
1503 return Ok(Vec::new());
1504 }
1505 let values = self.slice_values(slice, asof)?;
1506 Ok(values.into_iter().filter(|v| after.is_none_or(|a| v.sort_key.as_slice() > a)).take(limit).collect())
1507 }
1508 /// A page of the members of `slice` as of `asof`, by cell id ascending: those whose cell
1509 /// id is after `after_cell_id` (exclusive, when given), at most `limit`, with one value
1510 /// per member. The default takes all of [`slice_values`](Store::slice_values) and pages
1511 /// them. Since 0.5.3.
1512 fn slice_values_page(
1513 &self,
1514 slice: &Slice,
1515 asof: &str,
1516 after_cell_id: Option<&str>,
1517 limit: usize,
1518 ) -> Result<Vec<SliceValue>> {
1519 let mut values = self.slice_values(slice, asof)?;
1520 values.retain(|v| after_cell_id.is_none_or(|a| v.version.cell_id.as_str() > a));
1521 values.sort_by(|a, b| a.version.cell_id.cmp(&b.version.cell_id));
1522 values.truncate(limit);
1523 Ok(values)
1524 }
1525 /// Up to `limit` catalogue entries as (kind, name, label, description), with no counts.
1526 /// The default is [`Error::Unsupported`]. Since 0.5.3.
1527 fn catalog_entries_all(&self, limit: usize) -> Result<Vec<(CatalogKind, String, String, String)>> {
1528 let _ = limit;
1529 Err(Error::Unsupported("the catalogue's entries need a store of 0.5.3".into()))
1530 }
1531 /// The values of dictionary `key` of `owner`, in insertion order, at most `limit`. The
1532 /// default is [`Error::Unsupported`]. Since 0.5.3.
1533 fn dictionary_values_ordered(&self, owner: &str, key: &str, limit: usize) -> Result<Vec<String>> {
1534 let _ = (owner, key, limit);
1535 Err(Error::Unsupported("ordered dictionary values need a store of 0.5.3".into()))
1536 }
1537 /// [`computed_asof`](Store::computed_asof) and the bytes of the version's receipt (as
1538 /// [`receipt`](Resolver::receipt) returns them), which is what a caller reads next.
1539 /// The default asks for the two in turn (a receipt that cannot be read then is
1540 /// [`Error::NotFound`]); [`PgStore`] and [`SqliteStore`] answer both with one query.
1541 /// Since 0.2.0.
1542 fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1543 match self.computed_asof(cell_id, asof)? {
1544 Some(v) => with_receipt(self, v).map(Some),
1545 None => Ok(None),
1546 }
1547 }
1548 /// [`stored_asof`](Store::stored_asof) and the bytes of the version's receipt, as
1549 /// [`computed_asof_with_receipt`](Store::computed_asof_with_receipt) does. Since 0.2.0.
1550 fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1551 match self.stored_asof(cell_id, asof)? {
1552 Some(v) => with_receipt(self, v).map(Some),
1553 None => Ok(None),
1554 }
1555 }
1556
1557 // ---- Listings (0.7.0, CONTRACT-http-listing L3; see the `listings` module) -------------------
1558
1559 /// Writes the listing `l`, all or nothing. Checked first ([`Error::Invalid`]): `host` a DNS name;
1560 /// `name` a function name whose first segment is `host`; `fn_hash` 64 lowercase hex digits and
1561 /// the hash of `descriptor` as [`put_descriptor`](Store::put_descriptor) computes it (a
1562 /// descriptor that does not parse, or hashes to another, is refused); `subjects` 1 to
1563 /// [`LISTING_SUBJECTS_MAX`], ascending and unique, each key a name of at most 32 bytes;
1564 /// `key_id` 1 to 256 bytes; `label` at most 120 bytes; `description` 1 to 1024 bytes;
1565 /// `fetched_at` and `listed_at` instants.
1566 ///
1567 /// When the stored row of `name` equals `l` in every field but `fetched_at` and `listed_at`,
1568 /// nothing is written ([`ListingWrite::Unchanged`]). Otherwise the row is inserted
1569 /// ([`ListingWrite::Inserted`]) or replaced ([`ListingWrite::Changed`], keeping the stored
1570 /// `listed_at`), and in the same transaction: the descriptor is put in `descriptors`; the
1571 /// catalogue entry (kind function, `name`, hash `fn_hash`, `label`, `description`, no args, no
1572 /// examples, source [`CatalogSource::Listed`], `signed_by` = `host`, facets = each subject
1573 /// key's distinct values, ascending, at most 8 per key) is upserted, its embedding dropped when
1574 /// its text changes (as [`upsert_catalog_ext`](Store::upsert_catalog_ext) does). Never touched:
1575 /// `name_bindings`, the namespace checks, `cells`, `receipts`, `versions`. The default is
1576 /// [`Error::Unsupported`]. Since 0.7.0.
1577 fn put_listing(&self, l: &Listing) -> Result<ListingWrite> {
1578 let _ = l;
1579 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1580 }
1581 /// The listing of `name`, if there is one. The default is [`Error::Unsupported`]. Since 0.7.0.
1582 fn listing(&self, name: &str) -> Result<Option<Listing>> {
1583 let _ = name;
1584 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1585 }
1586 /// The listings of `host`, by name in byte order. The default is [`Error::Unsupported`]. Since 0.7.0.
1587 fn listings_of(&self, host: &str) -> Result<Vec<Listing>> {
1588 let _ = host;
1589 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1590 }
1591 /// The number of listings of every host. The default is [`Error::Unsupported`]. Since 0.7.0.
1592 fn listing_count(&self) -> Result<u64> {
1593 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1594 }
1595 /// Removes the listing of `name` and its catalogue entry of source listed (with the entry's
1596 /// embeddings), in one transaction; the descriptor stays in `descriptors`. `Ok(false)` when there
1597 /// was none. The default is [`Error::Unsupported`]. Since 0.7.0.
1598 fn delete_listing(&self, name: &str) -> Result<bool> {
1599 let _ = name;
1600 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1601 }
1602 /// Writes the row of a listed host. Checked first ([`Error::Invalid`]): `host` a DNS name,
1603 /// `last_seen` a date, `unreachable_since` an instant. When the stored row equals `h`, nothing
1604 /// is written and the answer is `Ok(false)`; otherwise it is inserted or replaced, `Ok(true)`.
1605 /// The default is [`Error::Unsupported`]. Since 0.7.0.
1606 fn put_listed_host(&self, h: &ListedHost) -> Result<bool> {
1607 let _ = h;
1608 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1609 }
1610 /// The row of the listed host `host`, if there is one. The default is [`Error::Unsupported`].
1611 /// Since 0.7.0.
1612 fn listed_host(&self, host: &str) -> Result<Option<ListedHost>> {
1613 let _ = host;
1614 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1615 }
1616 /// Every listed host's row, by host in byte order. The default is [`Error::Unsupported`].
1617 /// Since 0.7.0.
1618 fn listed_hosts(&self) -> Result<Vec<ListedHost>> {
1619 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1620 }
1621 /// Removes the row of `host` and every listing of `host` (as [`delete_listing`](Store::delete_listing)
1622 /// does), in one transaction. `Ok(false)` when there was no host row. The default is
1623 /// [`Error::Unsupported`]. Since 0.7.0.
1624 fn delete_listed_host(&self, host: &str) -> Result<bool> {
1625 let _ = host;
1626 Err(Error::Unsupported("listings need a store of 0.7.0".into()))
1627 }
1628}
1629
1630/// The seal of [`Store`]: a public trait in a private module, so no other crate can name it,
1631/// and so none can implement `Store`.
1632mod sealed {
1633 pub trait Sealed {}
1634 impl Sealed for crate::PgStore {}
1635 #[cfg(feature = "sqlite")]
1636 impl Sealed for crate::SqliteStore {}
1637}
1638
1639/// A receipt as the store reads it when it is put (crate-internal, since 0.6.0): a valued
1640/// receipt, or a withdrawal (8.1), which has no value.
1641pub(crate) struct Parsed {
1642 /// The canonical (JCS) bytes, `sig` included: what the store keeps.
1643 pub(crate) canonical: Vec<u8>,
1644 pub(crate) hash: String,
1645 pub(crate) cell_id: String,
1646 pub(crate) tx: String,
1647 pub(crate) asof: String,
1648 pub(crate) fn_hash: String,
1649 pub(crate) publisher: String,
1650 /// The receipt's cell (its arguments are indexed by the SQLite store).
1651 #[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
1652 pub(crate) cell: Cell,
1653 /// The signer's host (the namespace whose keys verify it).
1654 pub(crate) host: String,
1655 /// The slice entries (`slice:` inputs) and the receipt inputs (edges), in the receipt's order.
1656 pub(crate) entries: Vec<String>,
1657 pub(crate) inputs: Vec<String>,
1658 /// The value's type and lexical form; `None` for a withdrawal.
1659 #[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
1660 pub(crate) value: Option<(String, String)>,
1661}
1662
1663/// The `value_type` and `value` columns of a withdrawal: empty, which no valued receipt has
1664/// (a receipt's type is a name). Since 0.6.0; both backends.
1665#[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
1666pub(crate) const WITHDRAWN_VALUE: &str = "";
1667
1668/// Parses receipt bytes as a valued [`Receipt`] or, failing that, a [`Withdrawal`] (steps 1-4
1669/// of either). The error is the receipt's when the bytes are neither.
1670pub(crate) fn parse_receipt(bytes: &[u8]) -> Result<Parsed> {
1671 // A receipt with a `withdrawn` member is a withdrawal: parsed by the core's `Withdrawal`
1672 // alone, so its own error (not the receipt's) is the one refused.
1673 let withdrawal = datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some());
1674 if withdrawal {
1675 let w = datumesh_core::Withdrawal::from_json(bytes)?;
1676 return Ok(Parsed {
1677 canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
1678 hash: w.hash().to_string(),
1679 cell_id: w.cell().id(),
1680 tx: w.tx().to_string(),
1681 asof: w.asof().to_string(),
1682 fn_hash: w.cell().fn_hash.clone(),
1683 publisher: w.publisher().to_string(),
1684 cell: w.cell().clone(),
1685 host: w.signer_host().to_string(),
1686 entries: Vec::new(),
1687 inputs: Vec::new(),
1688 value: None,
1689 });
1690 }
1691 match datumesh_core::Receipt::from_json(bytes) {
1692 Ok(r) => {
1693 let (entries, inputs): (Vec<String>, Vec<String>) =
1694 r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
1695 let value = r.value();
1696 Ok(Parsed {
1697 canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
1698 hash: r.hash().to_string(),
1699 cell_id: r.cell().id(),
1700 tx: r.tx().to_string(),
1701 asof: r.asof().to_string(),
1702 fn_hash: r.cell().fn_hash.clone(),
1703 publisher: r.publisher().to_string(),
1704 cell: r.cell().clone(),
1705 host: r.signer_host().to_string(),
1706 entries,
1707 inputs,
1708 value: Some((value.ty().as_str().to_string(), value.lexical().to_string())),
1709 })
1710 }
1711 Err(e) => {
1712 let Ok(w) = datumesh_core::Withdrawal::from_json(bytes) else { return Err(e.into()) };
1713 Ok(Parsed {
1714 canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
1715 hash: w.hash().to_string(),
1716 cell_id: w.cell().id(),
1717 tx: w.tx().to_string(),
1718 asof: w.asof().to_string(),
1719 fn_hash: w.cell().fn_hash.clone(),
1720 publisher: w.publisher().to_string(),
1721 cell: w.cell().clone(),
1722 host: w.signer_host().to_string(),
1723 entries: Vec::new(),
1724 inputs: Vec::new(),
1725 value: None,
1726 })
1727 }
1728 }
1729}
1730
1731/// The value of stored receipt bytes: `Some` for a valued receipt, `None` for a withdrawal.
1732/// An error when the bytes are neither.
1733pub(crate) fn stored_value(bytes: &[u8]) -> std::result::Result<Option<Scalar>, datumesh_core::Error> {
1734 match datumesh_core::Receipt::from_json(bytes) {
1735 Ok(r) => Ok(Some(r.value().clone())),
1736 Err(e) => match datumesh_core::Withdrawal::from_json(bytes) {
1737 Ok(_) => Ok(None),
1738 Err(_) => Err(e),
1739 },
1740 }
1741}
1742
1743/// The error of closing a name with no binding to close (never bound, or closed already).
1744pub(crate) fn unbound(name: &str) -> Error {
1745 Error::NotFound { what: "binding", key: name.to_string() }
1746}
1747
1748/// `Ok` when `at` is later than the latest binding `latest` of `key` (a closing's tx).
1749pub(crate) fn later_than(what: &'static str, key: &str, at: &str, latest: &str) -> Result<()> {
1750 if at <= latest {
1751 return Err(Error::NotLater { what, key: key.to_string(), given: at.to_string(), latest: latest.to_string() });
1752 }
1753 Ok(())
1754}
1755
1756/// A version and its receipt's bytes, for the default `*_with_receipt` methods.
1757fn with_receipt<S: Store + ?Sized>(store: &S, v: Version) -> Result<(Version, Cow<'_, [u8]>)> {
1758 match store.receipt(&v.receipt_hash) {
1759 Some(bytes) => Ok((v, bytes)),
1760 None => Err(Error::NotFound { what: "receipt", key: v.receipt_hash }),
1761 }
1762}