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