datumesh_store/lib.rs
1//! A store for [Datumesh](https://datumesh.com): function descriptors, receipts, blobs,
2//! versions of cells over transaction time, lineage, namespaces and function names, on
3//! PostgreSQL or (since 0.4.0) in one SQLite file. [`PgStore`] and [`SqliteStore`] implement
4//! [`Store`], and through it `datumesh_core`'s [`Resolver`], so `datumesh_core::verify` can
5//! recompute receipts of stored cells from either; the two behave the same (one
6//! conformance suite runs against both).
7//!
8//! The API is synchronous (the `postgres` driver and a small connection pool; `rusqlite`
9//! with SQLite compiled in, feature `sqlite`, on by default). Async callers run it on a
10//! blocking thread, e.g. `tokio::task::spawn_blocking`.
11//!
12//! [`SqliteStore::open`] takes a file path ([`SqliteStore::connect`] a `sqlite:` URL); the
13//! file is in WAL mode, every write is one `BEGIN IMMEDIATE` transaction, and the
14//! append-only rules are triggers in the file, so they hold for writers in several
15//! threads and processes on one machine. Its schema comes from [`migrate::sqlite::apply`].
16//!
17//! [`PgStore::connect`] / [`PgStore::connect_with`] take a URL and [`PoolOptions`]; TLS
18//! (rustls) is used as the URL's `sslmode` says and always verifies the server's
19//! certificate and host name, against the Mozilla roots plus those added with
20//! [`PoolOptions::tls_root_certificates_pem`]. No type of the driver or of a TLS crate is
21//! part of the API, except in [`pg_unstable`] (any connection function, the driver
22//! itself), which is outside semver until 1.0.
23//!
24//! What is stored, and how:
25//!
26//! * Descriptors are checked by the core (`FunctionDescriptor::from_json`: since 0.3.1,
27//! spec-0.4.0's, with `signature.order` and argument `extent`) and stored in canonical
28//! form (JCS) under their hash. Receipts are verified (`datumesh_core::verify`, SPEC 10.1
29//! steps 1-6) against the key document stored for their signer host, so nothing
30//! unverified enters the store, and are stored canonical under their hash. Storing the
31//! same thing twice stores it once. A second, different valid signature over the same
32//! payload (possible only with a randomised signer: the payload names the key, so a
33//! rotated key gives a new hash) is refused ([`Error::Conflict`]) and the stored receipt
34//! kept.
35//! * Blobs are stored in the database, under the SHA-256 of their content.
36//! * Versions: from transaction time `tx` on, cell `cell_id` has the value of a receipt.
37//! Append-only and in tx order per cell, enforced by the database (triggers) as well as by
38//! [`Store::put_version`], which also checks that the receipt is stored and is of that
39//! cell at that tx.
40//! * Computed versions: from transaction time `tx` on, cell `cell_id` has the value a
41//! receipt computed, as of the receipt's asof. Derived rather than facts, so they are
42//! added in any order, keyed on (cell, tx, asof), insert-only
43//! ([`Store::put_computed`], [`Store::computed_asof`]).
44//! * Answering as of A: a receipt answers as of A only when its `tx` and its `asof` are
45//! both at or before A ([`Store::stored_asof`], and the [`Resolver`]'s `evaluate` of a
46//! stored function; [`Store::version_asof`] looks at `tx` only).
47//! * Lineage: `put_receipt` records an edge to each of the receipt's `inputs`, held or not:
48//! receipt hashes ([`Store::inputs`], [`Store::dependents`]) and, since 0.3.1, slice
49//! entries ([`Store::slice_entries`], [`Store::slice_dependents`]);
50//! [`Store::cell_dependents`] lifts both to cells.
51//! * Slices (0.3.1, SPEC 15.13): every stored receipt's cell is indexed by its typed
52//! arguments, so that [`Store::slice_members`] finds the members of a slice as of A with
53//! a range scan, in key order; [`Store::versions_between`] gives a version slice.
54//! [`Store::slice_values`] gives the members' values without receipts (0.3.2) and
55//! [`Store::slice_changed_after`] whether they may answer differently later.
56//! Manifests ([`Store::put_manifest`], served by [`Resolver::manifest`]) are kept by
57//! entry and found from each member ([`Store::member_manifests`]). A receipt citing a
58//! slice can be stored before its manifest, and a manifest before its members.
59//! * Namespaces: a host's key document (checked as SPEC 9.2 requires), with when it was
60//! validated. Store it before the host's receipts. Replacing it later (a key revoked or
61//! dropped) does not touch receipts already stored: they verified when they were stored,
62//! and putting one of them again is still idempotent.
63//! * Names: which function hash a fully qualified function name meant from a transaction
64//! time on. Append-only, like versions. [`Store::resolve_binding`] gives the binding
65//! answering as of A with when it began; [`Store::resolve_name`] its hash.
66//! * Classes (0.4.1, SPEC 16.1 to 16.3): a flattened class descriptor, checked by the core and
67//! stored canonical under its class hash ([`Store::put_class`], [`Store::class`]). A class
68//! name is bound over transaction time to a class hash, and binding it binds each method
69//! `<class name>/<m>` to the method's function hash in the same transaction
70//! ([`Store::bind_class`], [`Store::resolve_class`], [`Store::resolve_class_binding`]).
71//! Class names and function names are one namespace: a name bound as one kind cannot be
72//! bound as the other ([`Error::NameTaken`]).
73//! * Owner: a class's owner is the definer's check (SPEC 16.2 step 1), made when the class is
74//! defined, not the store's. The store records what it is given; the HTTP service and the
75//! engine enforce the owner rule. [`Store::put_class`] and [`Store::bind_class`] do not take a
76//! key document or check the name against the steward.
77//! * Namespace suspension (since 0.4.1): new writes under a suspended namespace are refused
78//! with [`Error::NamespaceSuspended`] (`put_class`: the steward's namespace; `bind_class`: the
79//! host of the class name); reads are never refused.
80//!
81//! Instants are compared as text (fixed width, `COLLATE "C"`; SQLite's default collation
82//! is the same byte order), which is exact; on PostgreSQL each is also stored as
83//! `timestamptz`, which round-trips every instant of the specification exactly. Numbers in
84//! the typed-argument index compare as exact decimals (PostgreSQL `numeric`; on SQLite a
85//! text encoding that sorts as the decimal does).
86//!
87//! Every [`Store`] method returns a `Result`: a malformed argument is [`Error::Invalid`] with
88//! the core's code, a database failure [`Error::Database`]. The [`Resolver`] methods keep the
89//! core's `Option` signatures; there a failure is logged with `tracing` (target
90//! `datumesh_store`) and answered `None`, which `verify` reports as unavailable.
91//!
92//! [`Store`] is sealed: only this crate implements it. The store is the trust boundary:
93//! everything in it was checked on the way in (every receipt verified against its host's
94//! key document), and its callers rely on that rather than checking again. A `dyn Store`
95//! is still a trait object as before.
96//!
97//! The schema comes from [`migrate::apply`] (PostgreSQL) or [`migrate::sqlite::apply`]
98//! (SQLite) (the `datumesh-store migrate` command, for either), through a store on the
99//! (possibly empty) database.
100
101#![forbid(unsafe_code)]
102#![deny(missing_docs)]
103
104use std::borrow::Cow;
105
106pub use datumesh_core::Resolver;
107use datumesh_core::{Cell, Scalar, Slice};
108
109mod error;
110pub mod migrate;
111mod pg;
112pub mod pg_unstable;
113mod pool;
114mod slices;
115mod sql;
116#[cfg(feature = "sqlite")]
117mod sqlite;
118#[cfg(feature = "sqlite")]
119mod sqlite_sql;
120mod tls;
121
122pub use error::{DatabaseError, Error, Result};
123pub use pg::PgStore;
124pub use pool::PoolOptions;
125#[cfg(feature = "sqlite")]
126pub use sqlite::{SqliteOptions, SqliteStore};
127
128/// A version of a cell: from transaction time `tx` on, the cell's value is that of the
129/// receipt `receipt_hash`, which states it as of `asof`.
130///
131/// A stored version ([`Store::put_version`]) or a computed one ([`Store::put_computed`]).
132#[non_exhaustive]
133#[derive(Clone, Debug, PartialEq, Eq, Hash)]
134pub struct Version {
135 /// The cell id.
136 pub cell_id: String,
137 /// The transaction time (an instant, SPEC 3.3).
138 pub tx: String,
139 /// The receipt stating the value.
140 pub receipt_hash: String,
141 /// The receipt's `asof` (an instant; never earlier than `tx`). Since 0.2.0.
142 pub asof: String,
143}
144
145/// A member of a slice ([`Store::slice_members`], [`Store::versions_between`]): a stored
146/// version and the bytes of its receipt (as [`receipt`](Resolver::receipt) returns them).
147/// Since 0.3.1.
148#[non_exhaustive]
149#[derive(Clone, Debug, PartialEq, Eq, Hash)]
150pub struct SliceMember {
151 /// The version answering (its cell, tx, receipt hash and asof).
152 pub version: Version,
153 /// The receipt's bytes, canonical JSON.
154 pub receipt: Vec<u8>,
155}
156
157/// A member of a slice with its value and without its receipt's bytes
158/// ([`Store::slice_values`]). Since 0.3.2.
159#[non_exhaustive]
160#[derive(Clone, Debug, PartialEq, Eq, Hash)]
161pub struct SliceValue {
162 /// The version answering (its cell, tx, receipt hash and asof).
163 pub version: Version,
164 /// The receipt's typed value.
165 pub value: Scalar,
166 /// The member's cell, with its arguments (from the store's typed-argument index; equal
167 /// to the receipt's `cell`, and `cell.id()` is `version.cell_id`).
168 pub cell: Cell,
169}
170
171/// A name binding: from transaction time `tx` on, a fully qualified function name means the
172/// function `fn_hash` ([`Store::bind_name`]). Since 0.3.0.
173#[non_exhaustive]
174#[derive(Clone, Debug, PartialEq, Eq, Hash)]
175pub struct Binding {
176 /// The function hash the name means.
177 pub fn_hash: String,
178 /// When the binding began: the transaction time from which the name means `fn_hash`
179 /// (an instant, SPEC 3.3).
180 pub tx: String,
181}
182
183/// A class-name binding: from transaction time `tx` on, a class name means the class
184/// `class_hash` ([`Store::bind_class`]). The class counterpart of [`Binding`]; the bindings
185/// answer of SPEC 9.7 gives `class_hash` in place of `fn_hash` for such a name. Since 0.4.1.
186#[non_exhaustive]
187#[derive(Clone, Debug, PartialEq, Eq, Hash)]
188pub struct ClassBinding {
189 /// The class hash the name means.
190 pub class_hash: String,
191 /// When the binding began (an instant, SPEC 3.3).
192 pub tx: String,
193}
194
195/// A namespace's host and its key document.
196#[non_exhaustive]
197#[derive(Clone, Debug, PartialEq, Eq, Hash)]
198pub struct Namespace {
199 /// The host (a DNS name).
200 pub host: String,
201 /// The key document, canonical (JCS).
202 pub keydoc: Vec<u8>,
203 /// When the document was last retrieved and checked.
204 pub validated_at: String,
205 /// When the namespace was suspended, if it is: the single record of suspension. Set by
206 /// [`record_namespace_failure`](Store::record_namespace_failure) when the consecutive
207 /// failures reach its threshold, cleared by
208 /// [`record_namespace_success`](Store::record_namespace_success). While it is set the
209 /// store refuses new writes under the host ([`Error::NamespaceSuspended`]).
210 pub suspended_at: Option<String>,
211 /// How many checks of the host's key document have failed in a row (zero after a
212 /// success). Since the namespace checks (since 0.4.1).
213 pub consecutive_failures: u32,
214 /// When the host's key document was last checked, successfully or not; `None` before
215 /// the first check recorded. Since the namespace checks (since 0.4.1).
216 pub last_checked_at: Option<String>,
217}
218
219/// The namespace after a check at `at`: a failed one (`threshold` is `Some`) adds to the
220/// consecutive failures and suspends at the threshold (an existing suspension keeps its
221/// time), a successful one (`None`) resets them and reinstates.
222/// The refusal of class descriptor bytes that are not the canonical form of the descriptor
223/// (`E_SCHEMA`, nothing stored): the class hash is the hash of the bytes stored, so only the
224/// canonical bytes are stored. Shared by both backends (since 0.4.1).
225pub(crate) fn not_canonical_class() -> Error {
226 Error::Invalid(datumesh_core::Error::new(
227 datumesh_core::ErrorCode::Schema,
228 "$",
229 "class descriptor is not in canonical form (JCS): put the canonical bytes",
230 ))
231}
232
233pub(crate) fn apply_check(ns: &mut Namespace, at: &str, threshold: Option<u32>) {
234 ns.last_checked_at = Some(at.to_string());
235 match threshold {
236 None => {
237 ns.consecutive_failures = 0;
238 ns.suspended_at = None;
239 }
240 Some(t) => {
241 ns.consecutive_failures = ns.consecutive_failures.saturating_add(1);
242 if ns.suspended_at.is_none() && ns.consecutive_failures >= t.max(1) {
243 ns.suspended_at = Some(at.to_string());
244 }
245 }
246 }
247}
248
249/// A Datumesh store: a [`Resolver`] that can also be written to.
250///
251/// Instants are SPEC 3.3 instants (`YYYY-MM-DDTHH:MM:SS.ffffffZ`), hashes and cell ids 64
252/// lowercase hex digits, hosts DNS names and function names fully qualified. Every method,
253/// read or write, refuses anything else with the core's error code ([`Error::Invalid`]),
254/// and reports a database failure as [`Error::Database`] (or [`Error::PoolTimeout`]): a read
255/// answers `Ok(None)` / `Ok(vec![])` only when the store really holds nothing.
256///
257/// The [`Resolver`] methods keep the core's `Option` signatures: there a malformed argument
258/// or a database failure is `None` (logged with `tracing` when it is a failure), which
259/// `verify` reports as unavailable.
260///
261/// Only this crate implements `Store` (it is sealed, since 0.3.0; [`PgStore`] and, since
262/// 0.4.0, [`SqliteStore`]): the store is the trust boundary, where every receipt is verified against its host's key document before it is
263/// kept, and what a store answers is relied on as checked. An implementation elsewhere
264/// could answer anything. `Store` stays object-safe (`Arc<dyn Store + Send + Sync>`). Even a complete implementation that
265/// delegates every method to a [`PgStore`] is refused (`E0277`: the private supertrait is
266/// not implemented; `tests/sealed.rs` checks that this is the only error):
267///
268/// ```compile_fail
269/// use std::borrow::Cow;
270/// use datumesh_core::{Cell, Scalar};
271/// use datumesh_core::Slice;
272/// use datumesh_store::{Binding, ClassBinding, Namespace, PgStore, Resolver, Result, SliceMember, SliceValue, Store, Version};
273///
274/// struct Wrapper(PgStore);
275/// impl Resolver for Wrapper {
276/// fn descriptor(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.descriptor(h) }
277/// fn receipt(&self, h: &str) -> Option<Cow<'_, [u8]>> { self.0.receipt(h) }
278/// fn evaluate(&self, c: &Cell, a: &str) -> Option<Scalar> { self.0.evaluate(c, a) }
279/// fn manifest(&self, e: &str) -> Option<Cow<'_, [u8]>> { self.0.manifest(e) }
280/// }
281/// impl Store for Wrapper {
282/// fn put_descriptor(&self, b: &[u8]) -> Result<String> { self.0.put_descriptor(b) }
283/// fn put_receipt(&self, b: &[u8]) -> Result<String> { self.0.put_receipt(b) }
284/// fn put_blob(&self, b: &[u8]) -> Result<String> { self.0.put_blob(b) }
285/// fn blob(&self, s: &str) -> Result<Option<Cow<'_, [u8]>>> { self.0.blob(s) }
286/// fn put_version(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_version(c, t, r) }
287/// fn version_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.version_asof(c, a) }
288/// fn versions(&self, c: &str, f: &str, t: &str) -> Result<Vec<Version>> { self.0.versions(c, f, t) }
289/// fn latest(&self, c: &str) -> Result<Option<Version>> { self.0.latest(c) }
290/// fn dependents(&self, r: &str) -> Result<Vec<String>> { self.0.dependents(r) }
291/// fn inputs(&self, r: &str) -> Result<Vec<String>> { self.0.inputs(r) }
292/// fn put_namespace(&self, h: &str, k: &[u8], v: &str) -> Result<()> { self.0.put_namespace(h, k, v) }
293/// fn namespace(&self, h: &str) -> Result<Option<Namespace>> { self.0.namespace(h) }
294/// fn namespaces(&self) -> Result<Vec<Namespace>> { self.0.namespaces() }
295/// fn record_namespace_failure(&self, h: &str, a: &str, n: u32) -> Result<Option<Namespace>> { self.0.record_namespace_failure(h, a, n) }
296/// fn record_namespace_success(&self, h: &str, a: &str) -> Result<Option<Namespace>> { self.0.record_namespace_success(h, a) }
297/// fn bind_name(&self, n: &str, f: &str, t: &str) -> Result<()> { self.0.bind_name(n, f, t) }
298/// fn resolve_name(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_name(n, a) }
299/// fn resolve_binding(&self, n: &str, a: &str) -> Result<Option<Binding>> { self.0.resolve_binding(n, a) }
300/// fn put_class(&self, b: &[u8]) -> Result<String> { self.0.put_class(b) }
301/// fn class(&self, h: &str) -> Result<Option<Vec<u8>>> { self.0.class(h) }
302/// fn bind_class(&self, n: &str, h: &str, t: &str) -> Result<()> { self.0.bind_class(n, h, t) }
303/// fn resolve_class(&self, n: &str, a: &str) -> Result<Option<String>> { self.0.resolve_class(n, a) }
304/// fn resolve_class_binding(&self, n: &str, a: &str) -> Result<Option<ClassBinding>> { self.0.resolve_class_binding(n, a) }
305/// fn put_computed(&self, c: &str, t: &str, r: &str) -> Result<()> { self.0.put_computed(c, t, r) }
306/// fn computed_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.computed_asof(c, a) }
307/// fn stored_asof(&self, c: &str, a: &str) -> Result<Option<Version>> { self.0.stored_asof(c, a) }
308/// fn cell_dependents(&self, c: &str) -> Result<Vec<String>> { self.0.cell_dependents(c) }
309/// fn put_manifest(&self, b: &[u8]) -> Result<String> { self.0.put_manifest(b) }
310/// fn member_manifests(&self, r: &str) -> Result<Vec<String>> { self.0.member_manifests(r) }
311/// fn slice_entries(&self, r: &str) -> Result<Vec<String>> { self.0.slice_entries(r) }
312/// fn slice_dependents(&self, e: &str) -> Result<Vec<String>> { self.0.slice_dependents(e) }
313/// fn slice_members(&self, s: &Slice, a: &str) -> Result<Vec<SliceMember>> { self.0.slice_members(s, a) }
314/// fn versions_between(&self, c: &str, f: &str, t: &str, a: &str) -> Result<Vec<SliceMember>> { self.0.versions_between(c, f, t, a) }
315/// fn slice_values(&self, s: &Slice, a: &str) -> Result<Vec<SliceValue>> { self.0.slice_values(s, a) }
316/// fn slice_changed_after(&self, s: &Slice, a: &str) -> Result<bool> { self.0.slice_changed_after(s, a) }
317/// fn computed_cells(&self, s: &Slice, a: &str, n: usize) -> Result<Vec<Cell>> { self.0.computed_cells(s, a, n) }
318/// fn has_bindings_under(&self, n: &str) -> Result<bool> { self.0.has_bindings_under(n) }
319/// }
320/// ```
321pub trait Store: Resolver + sealed::Sealed {
322 /// Stores a descriptor (checked and canonicalised by the core); returns its function
323 /// hash. Idempotent.
324 fn put_descriptor(&self, bytes: &[u8]) -> Result<String>;
325 /// Stores a receipt that verifies (SPEC 10.1 steps 1-6) against the key document stored
326 /// for its signer host with [`put_namespace`](Store::put_namespace), in canonical form,
327 /// with an edge to each of its inputs; returns its hash. An input that is a slice entry
328 /// (`slice:<slice id>:<members hash>`, since 0.3.1) is recorded as such
329 /// ([`slice_entries`](Store::slice_entries)); its manifest need not be stored, before or
330 /// after (it is needed only to recompute, SPEC 10.1 step 7.5). The receipt's cell is
331 /// indexed by its typed arguments ([`slice_members`](Store::slice_members)). A receipt that does not verify
332 /// is refused with `verify`'s code (no key document for the host: `E_KEY_UNAVAILABLE`).
333 /// Idempotent: bytes whose canonical form is the stored copy return its hash without
334 /// checking the signature again (it verified when stored), even if the key has since
335 /// been revoked. Other bytes with a stored hash are verified first, then refused as
336 /// [`Error::Conflict`].
337 fn put_receipt(&self, bytes: &[u8]) -> Result<String>;
338 /// Stores blob content; returns its SHA-256 (lowercase hex). Idempotent.
339 fn put_blob(&self, bytes: &[u8]) -> Result<String>;
340 /// Blob content by SHA-256.
341 fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>>;
342 /// Appends a version: from `tx` on, `cell_id` has the value of receipt `receipt_hash`,
343 /// which must be stored, of that cell and at that tx. `tx` must be later than the cell's
344 /// latest version ([`Error::NotLater`]).
345 fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
346 /// The cell's latest version with `tx <= asof`.
347 fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
348 /// The cell's versions with `from <= tx <= to`, in tx order.
349 fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>>;
350 /// The cell's latest version.
351 fn latest(&self, cell_id: &str) -> Result<Option<Version>>;
352 /// The stored receipts that list `receipt_hash` among their inputs, by hash. Only as
353 /// an input of its own: a receipt read as a member of a slice is found through its
354 /// manifests ([`member_manifests`](Store::member_manifests), then
355 /// [`slice_dependents`](Store::slice_dependents)).
356 fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>>;
357 /// The inputs of a stored receipt that are receipt hashes (whether or not they are
358 /// stored). Its slice entries are [`slice_entries`](Store::slice_entries).
359 fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>>;
360 /// Records a host's key document, checked as a 200 response for that host would be
361 /// (SPEC 9.2, 9.3), validated at `validated_at`. Re-validation replaces the document; a
362 /// `validated_at` earlier than the recorded one is [`Error::NotLater`]. Receipts already
363 /// stored are not re-checked: they verified when they were stored (and putting one again
364 /// stays idempotent).
365 fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()>;
366 /// A host's recorded key document.
367 fn namespace(&self, host: &str) -> Result<Option<Namespace>>;
368 /// Every recorded namespace, by host. Since the namespace checks (since 0.4.1).
369 fn namespaces(&self) -> Result<Vec<Namespace>>;
370 /// Records a failed check of `host`'s key document at `checked_at` (domain validation):
371 /// the consecutive failures grow by one, and when they reach `threshold` (zero counts as
372 /// one) the namespace is suspended at `checked_at`, unless it already is (the first
373 /// suspension's time is kept). While it is suspended the store refuses new writes under
374 /// the host: `put_receipt` of a receipt signed by it, `put_version` of such a receipt
375 /// and `bind_name` of a name under it ([`Error::NamespaceSuspended`]); reads,
376 /// verification and the stored key document are not affected, and neither is putting a
377 /// receipt that is already stored. Returns the namespace as recorded, or `None` for a
378 /// host with no namespace (there is nothing to suspend). A `checked_at` earlier than the
379 /// latest check is [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
380 fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>>;
381 /// Records a successful check of `host`'s key document at `checked_at`: the consecutive
382 /// failures are reset to zero and a suspension is lifted (the namespace is reinstated).
383 /// The document itself is recorded with [`put_namespace`](Store::put_namespace) (which
384 /// neither suspends nor reinstates). Returns the namespace as recorded, or `None` for a
385 /// host with no namespace. A `checked_at` earlier than the latest check is
386 /// [`Error::NotLater`]. Since the namespace checks (since 0.4.1).
387 fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>>;
388 /// Appends a binding: from `tx` on, the fully qualified function name `fn_name` means
389 /// `fn_hash`, whose descriptor must be stored. `tx` must be later than the name's latest
390 /// binding ([`Error::NotLater`]).
391 fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()>;
392 /// The function hash `fn_name` meant as of `asof`: the hash of
393 /// [`resolve_binding`](Store::resolve_binding)'s binding.
394 fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>>;
395 /// The binding of `fn_name` that answers as of `asof`: the one with the latest `tx <=
396 /// asof`, with its function hash and its `tx`, when it began; `None` before the first.
397 /// A name bound again to a hash it meant before (even the hash of the binding before
398 /// it) begins again: the later binding's `tx`. Since 0.3.0.
399 fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>>;
400
401 /// Stores a class descriptor (SPEC 16.1, 16.2) under its class hash and returns the hash.
402 /// Since 0.4.1.
403 ///
404 /// `bytes` must be a **flattened** descriptor in **canonical form** (the bytes
405 /// `ClassDescriptor::canonical` gives, 6.2: what the class hash hashes). The core checks it
406 /// (`ClassDescriptor::from_json`: strict JSON, then 16.1 in its check order; a flattened
407 /// descriptor passes). Bytes that are a valid descriptor but not the canonical form of
408 /// it (white space, members out of order) are refused with [`Error::Invalid`], code
409 /// `E_SCHEMA`, and nothing is stored: unlike [`put_descriptor`](Store::put_descriptor),
410 /// which canonicalises, the bytes put are the bytes stored, so the class hash is the
411 /// SHA-256 of what [`class`](Store::class) returns. Idempotent for the same bytes.
412 ///
413 /// The store does not flatten (that is define's, with the parent in hand), and does not
414 /// need the parent, the method functions or the interfaces to be stored (`bind_class`
415 /// needs the methods' descriptors). It does not check the owner either (16.2 step 1 is the
416 /// definer's check: the store records, http and the engine enforce). It is a write under
417 /// the class's steward namespace (`steward.namespace`): refused with
418 /// [`Error::NamespaceSuspended`] while that namespace is suspended, even for a class
419 /// already stored.
420 fn put_class(&self, bytes: &[u8]) -> Result<String>;
421 /// The canonical bytes of the class descriptor with this class hash, as stored
422 /// ([`put_class`](Store::put_class)); `None` when no such class is stored. A malformed
423 /// hash is `E_CANON_HEX`. Never refused under a suspended namespace. Since 0.4.1.
424 fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>>;
425 /// Binds the class name `class_name` (a full name, 2.3) to the stored class `class_hash`
426 /// from `tx` on and, in the same transaction, binds each method `<class_name>/<m>` of the
427 /// stored (flattened, so inherited methods included) descriptor to the method's function
428 /// hash from the same `tx` (SPEC 16.3, 9.7). All of it or nothing:
429 ///
430 /// - the class must be stored ([`Error::NotFound`], `what` `"class"`), and so must every
431 /// method's function descriptor ([`Error::NotFound`], `what` `"descriptor"`, the missing
432 /// function hash; the first in JCS order of method names);
433 /// - class names and function names share one namespace of names: `class_name`, or a
434 /// method name, whose latest binding is of the other kind (a function for `class_name`,
435 /// a class for a method name) is refused with [`Error::NameTaken`]. A method name bound
436 /// as a function, to whatever hash, is simply bound again;
437 /// - `tx` must be later than the latest binding of `class_name` and of each method name
438 /// ([`Error::NotLater`], `what` `"name"`, the name that is not);
439 /// - while the namespace of `class_name`'s host is suspended: [`Error::NamespaceSuspended`].
440 ///
441 /// The store does not check that the class name is under the steward's namespace, nor
442 /// who binds it (the definer's check, 16.2 step 1). Since 0.4.1.
443 fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()>;
444 /// The class hash `class_name` meant as of `asof`: the hash of
445 /// [`resolve_class_binding`](Store::resolve_class_binding)'s binding. `None` before the
446 /// first binding, and for a name whose binding as of `asof` is a function's. Since 0.4.1.
447 fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>>;
448 /// The class binding of `class_name` that answers as of `asof`: the latest with
449 /// `tx <= asof`, with its class hash and its `tx` (when it began; binding the same hash
450 /// again begins again), as [`resolve_binding`](Store::resolve_binding) does for functions.
451 /// `None` before the first, and for a function name. The function accessors
452 /// ([`resolve_name`](Store::resolve_name), [`resolve_binding`](Store::resolve_binding))
453 /// answer `None` for a class name: a bindings answer (9.7) has `fn_hash` or `class_hash`,
454 /// never both. Since 0.4.1.
455 fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>>;
456
457 /// Records that `receipt_hash` (stored, a receipt of `cell_id` at `tx`) is a computed
458 /// version of the cell. Insert-only, in any order (an older version may be added after a
459 /// newer one): `tx` need not be later than anything. The version's asof is the
460 /// receipt's. Idempotent for the same (cell_id, tx, asof, receipt_hash); another receipt
461 /// for an existing (cell_id, tx, asof) is [`Error::Conflict`] (its `hash` is the receipt
462 /// refused) and the stored one is kept. The receipt is checked as for
463 /// [`put_version`](Store::put_version): [`Error::NotFound`] when it is not stored,
464 /// [`Error::Mismatch`] when it is of another cell or at another tx. Since 0.2.0.
465 fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
466 /// The computed version that answers as of `asof`: the one with the greatest asof <=
467 /// `asof` (between equal asof, the greatest tx), or `None`. Since 0.2.0.
468 fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
469 /// The stored version that answers as of `asof`: the latest version (by tx) with `tx <=
470 /// asof` whose receipt's asof is also `<= asof`, or `None`. A version whose receipt is
471 /// late-signed (asof later than tx) answers only from its asof on; until then the
472 /// version before it answers. ([`version_asof`](Store::version_asof) keeps its tx-only
473 /// meaning.) Since 0.2.0.
474 fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
475 /// The cells that read `cell_id`: the cell ids of the stored receipts that list, among
476 /// their inputs, any stored receipt of `cell_id` (lineage: edges joined to receipts),
477 /// or (since 0.3.1) a slice entry whose stored manifest lists one as a member.
478 /// Ascending, each once. Since 0.2.0.
479 fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>>;
480
481 /// Stores a manifest (SPEC 15.13), `{"members": [...], "slice": {...}}`: parsed strictly
482 /// and checked by the core (`Manifest::from_json`: structure, members, their order and
483 /// limit, the slice object), kept in canonical form under its entry
484 /// `slice:<slice id>:<members hash>`, which it returns, and recorded for each member
485 /// ([`member_manifests`](Store::member_manifests)). The members need not be stored.
486 /// Idempotent; insert-only (the entry is a hash of the content, so a stored entry
487 /// always has these bytes). Served by [`manifest`](Resolver::manifest). Since 0.3.1.
488 fn put_manifest(&self, bytes: &[u8]) -> Result<String>;
489 /// The entries of the stored manifests that list `receipt_hash` among their members,
490 /// ascending: from a member, the slices it was read in (then
491 /// [`slice_dependents`](Store::slice_dependents)). Since 0.3.1.
492 fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>>;
493 /// The slice entries among the inputs of a stored receipt, ascending. Since 0.3.1.
494 fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>>;
495 /// The stored receipts whose inputs list the slice entry `entry`, by hash, ascending.
496 /// An entry is `slice:` and two 64-digit hashes (`E_CANON_HEX` otherwise). Since 0.3.1.
497 fn slice_dependents(&self, entry: &str) -> Result<Vec<String>>;
498 /// The members of `slice` as of `asof` (SPEC 15.13), with the stored version of each
499 /// that answers as of `asof` and its receipt's bytes.
500 ///
501 /// For a slice of cells: the cells of the slice's function (its `fn_hash`, `ns` and
502 /// `fn`, with the same argument names) whose bound arguments are the same typed scalar,
503 /// whose ranged arguments are of the range's type and within it (`lo <= v <= hi`,
504 /// inclusive, in the type's order: numbers as exact decimals, dates and instants
505 /// chronologically, strings by code point; `lo` after `hi` is empty), any value for an
506 /// open argument, and that have a stored version answering as of `asof`: as
507 /// [`stored_asof`](Store::stored_asof), the latest version with `tx <= asof` whose
508 /// receipt's `asof <= asof` (so a late-signed version is not a member's answer before
509 /// its asof, and a correction replaces a member's version from its asof on). Computed
510 /// versions are not members. In key order: by the open and ranged arguments in
511 /// ascending name order, each in its type's order (`false` before `true`; blobs as
512 /// text); the cell id last, for two cells whose key arguments are of different types.
513 ///
514 /// For a version slice `{"cell", "from", "to"}`: [`versions_between`](Store::versions_between)
515 /// of its cell. Empty when nothing matches. Since 0.3.1.
516 fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>>;
517 /// The stored versions of `cell_id` with `from <= tx <= to` that answer as of `asof`
518 /// (`tx <= asof` and the receipt's `asof <= asof`), ascending by tx, each with its
519 /// receipt's bytes: SPEC 15.13's version slice. Empty when `from` is after `to`. Since
520 /// 0.3.1.
521 fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>>;
522 /// The members [`slice_members`](Store::slice_members) gives, in its order and by its
523 /// answering rule, each as its version, its receipt's typed value and its cell (with its
524 /// arguments), without the receipt's bytes (the value is a stored column of the receipt
525 /// and the cell comes from the typed-argument index, neither parsed per call).
526 /// Since 0.3.2.
527 fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>>;
528 /// Whether the members of `slice`, or their versions, may answer differently as of some
529 /// time after `asof`: whether a cell matching the slice has a stored version whose
530 /// receipt's `asof` is after `asof` (its `tx` is never later than that), for a version
531 /// slice one with `tx` in `[from, to]`. `false` means [`slice_members`](Store::slice_members)
532 /// (and `slice_values`) give the same answer as of every time from `asof` on, until a
533 /// version is stored with an asof after it; `true` may be conservative (a late-signed
534 /// version superseded before its asof never answers). Index scans only, whatever the
535 /// slice's size: two bounded probes (at most 10,001 entries each) choose whether to walk
536 /// the function's receipts with an asof after `asof` or the slice's candidate cells,
537 /// whichever is fewer, and one query walks it, stopping at the first match. Since 0.3.2.
538 fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool>;
539 /// The cells of `slice` (matched as [`slice_values`](Store::slice_values) matches them: the
540 /// fixed arguments, `fn_hash`, `ns`, `fn` and the number of arguments) that have a computed
541 /// version answering as of `asof`: one with `tx <= asof` whose receipt's asof is `<= asof`
542 /// (the rule of [`computed_asof`](Store::computed_asof)). Ascending by cell id, at most
543 /// `limit` (`slice_values` takes no limit), each with its arguments from the typed-argument
544 /// index. A cell with only a stored version is not returned. Since 0.4.2.
545 fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>>;
546 /// Whether any name binding or class binding has a name starting with `namespace` and `/`
547 /// (so `"a.example/n"` is not a namespace of `"a.example/ns/f"`). Since 0.4.2.
548 fn has_bindings_under(&self, namespace: &str) -> Result<bool>;
549
550 /// [`computed_asof`](Store::computed_asof) and the bytes of the version's receipt (as
551 /// [`receipt`](Resolver::receipt) returns them), which is what a caller reads next.
552 /// The default asks for the two in turn (a receipt that cannot be read then is
553 /// [`Error::NotFound`]); [`PgStore`] and [`SqliteStore`] answer both with one query.
554 /// Since 0.2.0.
555 fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
556 match self.computed_asof(cell_id, asof)? {
557 Some(v) => with_receipt(self, v).map(Some),
558 None => Ok(None),
559 }
560 }
561 /// [`stored_asof`](Store::stored_asof) and the bytes of the version's receipt, as
562 /// [`computed_asof_with_receipt`](Store::computed_asof_with_receipt) does. Since 0.2.0.
563 fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
564 match self.stored_asof(cell_id, asof)? {
565 Some(v) => with_receipt(self, v).map(Some),
566 None => Ok(None),
567 }
568 }
569}
570
571/// The seal of [`Store`]: a public trait in a private module, so no other crate can name it,
572/// and so none can implement `Store`.
573mod sealed {
574 pub trait Sealed {}
575 impl Sealed for crate::PgStore {}
576 #[cfg(feature = "sqlite")]
577 impl Sealed for crate::SqliteStore {}
578}
579
580/// A version and its receipt's bytes, for the default `*_with_receipt` methods.
581fn with_receipt<S: Store + ?Sized>(store: &S, v: Version) -> Result<(Version, Cow<'_, [u8]>)> {
582 match store.receipt(&v.receipt_hash) {
583 Some(bytes) => Ok((v, bytes)),
584 None => Err(Error::NotFound { what: "receipt", key: v.receipt_hash }),
585 }
586}