datumesh_store/lib.rs
1//! A PostgreSQL store for [Datumesh](https://datumesh.com): function descriptors, receipts,
2//! blobs, versions of cells over transaction time, lineage, namespaces and function names.
3//! [`PgStore`] implements [`Store`], and through it `datumesh_core`'s [`Resolver`], so
4//! `datumesh_core::verify` can recompute receipts of stored cells from it.
5//!
6//! The API is synchronous (the `postgres` driver, a small connection pool). Async callers run
7//! it on a blocking thread, e.g. `tokio::task::spawn_blocking`.
8//!
9//! [`PgStore::connect`] / [`PgStore::connect_with`] take a URL and [`PoolOptions`]; TLS
10//! (rustls) is used as the URL's `sslmode` says and always verifies the server's
11//! certificate and host name, against the Mozilla roots plus those added with
12//! [`PoolOptions::tls_root_certificates_pem`]. No type of the driver or of a TLS crate is
13//! part of the API, except in [`pg_unstable`] (any connection function, the driver
14//! itself), which is outside semver until 1.0.
15//!
16//! What is stored, and how:
17//!
18//! * Descriptors are checked by the core (`Descriptor::from_json`) and stored in canonical
19//! form (JCS) under their hash. Receipts are verified (`datumesh_core::verify`, SPEC 10.1
20//! steps 1-6) against the key document stored for their signer host, so nothing
21//! unverified enters the store, and are stored canonical under their hash. Storing the
22//! same thing twice stores it once. A second, different valid signature over the same
23//! payload (possible only with a randomised signer: the payload names the key, so a
24//! rotated key gives a new hash) is refused ([`Error::Conflict`]) and the stored receipt
25//! kept.
26//! * Blobs are stored in the database, under the SHA-256 of their content.
27//! * Versions: from transaction time `tx` on, cell `cell_id` has the value of a receipt.
28//! Append-only and in tx order per cell, enforced by the database (triggers) as well as by
29//! [`Store::put_version`], which also checks that the receipt is stored and is of that
30//! cell at that tx.
31//! * Computed versions: from transaction time `tx` on, cell `cell_id` has the value a
32//! receipt computed, as of the receipt's asof. Derived rather than facts, so they are
33//! added in any order, keyed on (cell, tx, asof), insert-only
34//! ([`Store::put_computed`], [`Store::computed_asof`]).
35//! * Answering as of A: a receipt answers as of A only when its `tx` and its `asof` are
36//! both at or before A ([`Store::stored_asof`]; [`Store::version_asof`] looks at `tx`
37//! only).
38//! * Lineage: `put_receipt` records an edge to each of the receipt's `inputs`, held or not;
39//! [`Store::cell_dependents`] lifts it to cells.
40//! * Namespaces: a host's key document (checked as SPEC 9.2 requires), with when it was
41//! validated. Store it before the host's receipts. Replacing it later (a key revoked or
42//! dropped) does not touch receipts already stored: they verified when they were stored,
43//! and putting one of them again is still idempotent.
44//! * Names: which function hash a fully qualified function name meant from a transaction
45//! time on. Append-only, like versions.
46//!
47//! Instants are compared as text (fixed width, `COLLATE "C"`), which is exact; each is also
48//! stored as `timestamptz`, which round-trips every instant of the specification exactly.
49//!
50//! Every [`Store`] method returns a `Result`: a malformed argument is [`Error::Invalid`] with
51//! the core's code, a database failure [`Error::Database`]. The [`Resolver`] methods keep the
52//! core's `Option` signatures; there a failure is logged with `tracing` (target
53//! `datumesh_store`) and answered `None`, which `verify` reports as unavailable.
54//!
55//! The schema comes from [`migrate::apply`] (the `datumesh-store migrate` command), through
56//! a store on the (possibly empty) database.
57
58#![forbid(unsafe_code)]
59#![deny(missing_docs)]
60
61use std::borrow::Cow;
62
63pub use datumesh_core::Resolver;
64
65mod error;
66pub mod migrate;
67mod pg;
68pub mod pg_unstable;
69mod pool;
70mod sql;
71mod tls;
72
73pub use error::{DatabaseError, Error, Result};
74pub use pg::PgStore;
75pub use pool::PoolOptions;
76
77/// A version of a cell: from transaction time `tx` on, the cell's value is that of the
78/// receipt `receipt_hash`, which states it as of `asof`.
79///
80/// A stored version ([`Store::put_version`]) or a computed one ([`Store::put_computed`]).
81#[non_exhaustive]
82#[derive(Clone, Debug, PartialEq, Eq, Hash)]
83pub struct Version {
84 /// The cell id.
85 pub cell_id: String,
86 /// The transaction time (an instant, SPEC 3.3).
87 pub tx: String,
88 /// The receipt stating the value.
89 pub receipt_hash: String,
90 /// The receipt's `asof` (an instant; never earlier than `tx`). Since 0.2.0.
91 pub asof: String,
92}
93
94/// A namespace's host and its key document.
95#[non_exhaustive]
96#[derive(Clone, Debug, PartialEq, Eq, Hash)]
97pub struct Namespace {
98 /// The host (a DNS name).
99 pub host: String,
100 /// The key document, canonical (JCS).
101 pub keydoc: Vec<u8>,
102 /// When the document was last retrieved and checked.
103 pub validated_at: String,
104 /// When the namespace was suspended, if it is. Nothing in this version sets it.
105 pub suspended_at: Option<String>,
106}
107
108/// A Datumesh store: a [`Resolver`] that can also be written to.
109///
110/// Instants are SPEC 3.3 instants (`YYYY-MM-DDTHH:MM:SS.ffffffZ`), hashes and cell ids 64
111/// lowercase hex digits, hosts DNS names and function names fully qualified. Every method,
112/// read or write, refuses anything else with the core's error code ([`Error::Invalid`]),
113/// and reports a database failure as [`Error::Database`] (or [`Error::PoolTimeout`]): a read
114/// answers `Ok(None)` / `Ok(vec![])` only when the store really holds nothing.
115///
116/// The [`Resolver`] methods keep the core's `Option` signatures: there a malformed argument
117/// or a database failure is `None` (logged with `tracing` when it is a failure), which
118/// `verify` reports as unavailable.
119pub trait Store: Resolver {
120 /// Stores a descriptor (checked and canonicalised by the core); returns its function
121 /// hash. Idempotent.
122 fn put_descriptor(&self, bytes: &[u8]) -> Result<String>;
123 /// Stores a receipt that verifies (SPEC 10.1 steps 1-6) against the key document stored
124 /// for its signer host with [`put_namespace`](Store::put_namespace), in canonical form,
125 /// with an edge to each of its inputs; returns its hash. A receipt that does not verify
126 /// is refused with `verify`'s code (no key document for the host: `E_KEY_UNAVAILABLE`).
127 /// Idempotent: bytes whose canonical form is the stored copy return its hash without
128 /// checking the signature again (it verified when stored), even if the key has since
129 /// been revoked. Other bytes with a stored hash are verified first, then refused as
130 /// [`Error::Conflict`].
131 fn put_receipt(&self, bytes: &[u8]) -> Result<String>;
132 /// Stores blob content; returns its SHA-256 (lowercase hex). Idempotent.
133 fn put_blob(&self, bytes: &[u8]) -> Result<String>;
134 /// Blob content by SHA-256.
135 fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>>;
136 /// Appends a version: from `tx` on, `cell_id` has the value of receipt `receipt_hash`,
137 /// which must be stored, of that cell and at that tx. `tx` must be later than the cell's
138 /// latest version ([`Error::NotLater`]).
139 fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
140 /// The cell's latest version with `tx <= asof`.
141 fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
142 /// The cell's versions with `from <= tx <= to`, in tx order.
143 fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>>;
144 /// The cell's latest version.
145 fn latest(&self, cell_id: &str) -> Result<Option<Version>>;
146 /// The stored receipts that list `receipt_hash` among their inputs, by hash.
147 fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>>;
148 /// The inputs of a stored receipt, by hash (whether or not they are stored).
149 fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>>;
150 /// Records a host's key document, checked as a 200 response for that host would be
151 /// (SPEC 9.2, 9.3), validated at `validated_at`. Re-validation replaces the document; a
152 /// `validated_at` earlier than the recorded one is [`Error::NotLater`]. Receipts already
153 /// stored are not re-checked: they verified when they were stored (and putting one again
154 /// stays idempotent).
155 fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()>;
156 /// A host's recorded key document.
157 fn namespace(&self, host: &str) -> Result<Option<Namespace>>;
158 /// Appends a binding: from `tx` on, the fully qualified function name `fn_name` means
159 /// `fn_hash`, whose descriptor must be stored. `tx` must be later than the name's latest
160 /// binding ([`Error::NotLater`]).
161 fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()>;
162 /// The function hash `fn_name` meant as of `asof`.
163 fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>>;
164
165 /// Records that `receipt_hash` (stored, a receipt of `cell_id` at `tx`) is a computed
166 /// version of the cell. Insert-only, in any order (an older version may be added after a
167 /// newer one): `tx` need not be later than anything. The version's asof is the
168 /// receipt's. Idempotent for the same (cell_id, tx, asof, receipt_hash); another receipt
169 /// for an existing (cell_id, tx, asof) is [`Error::Conflict`] (its `hash` is the receipt
170 /// refused) and the stored one is kept. The receipt is checked as for
171 /// [`put_version`](Store::put_version): [`Error::NotFound`] when it is not stored,
172 /// [`Error::Mismatch`] when it is of another cell or at another tx. Since 0.2.0.
173 fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
174 /// The computed version that answers as of `asof`: the one with the greatest asof <=
175 /// `asof` (between equal asof, the greatest tx), or `None`. Since 0.2.0.
176 fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
177 /// The stored version that answers as of `asof`: the latest version (by tx) with `tx <=
178 /// asof` whose receipt's asof is also `<= asof`, or `None`. A version whose receipt is
179 /// late-signed (asof later than tx) answers only from its asof on; until then the
180 /// version before it answers. ([`version_asof`](Store::version_asof) keeps its tx-only
181 /// meaning.) Since 0.2.0.
182 fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
183 /// The cells that read `cell_id`: the cell ids of the stored receipts that list, among
184 /// their inputs, any stored receipt of `cell_id` (lineage: edges joined to receipts).
185 /// Ascending, each once. Since 0.2.0.
186 fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>>;
187
188 /// [`computed_asof`](Store::computed_asof) and the bytes of the version's receipt (as
189 /// [`receipt`](Resolver::receipt) returns them), which is what a caller reads next.
190 /// The default asks for the two in turn (a receipt that cannot be read then is
191 /// [`Error::NotFound`]); [`PgStore`] answers both with one query. Since 0.2.0.
192 fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
193 match self.computed_asof(cell_id, asof)? {
194 Some(v) => with_receipt(self, v).map(Some),
195 None => Ok(None),
196 }
197 }
198 /// [`stored_asof`](Store::stored_asof) and the bytes of the version's receipt, as
199 /// [`computed_asof_with_receipt`](Store::computed_asof_with_receipt) does. Since 0.2.0.
200 fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
201 match self.stored_asof(cell_id, asof)? {
202 Some(v) => with_receipt(self, v).map(Some),
203 None => Ok(None),
204 }
205 }
206}
207
208/// A version and its receipt's bytes, for the default `*_with_receipt` methods.
209fn with_receipt<S: Store + ?Sized>(store: &S, v: Version) -> Result<(Version, Cow<'_, [u8]>)> {
210 match store.receipt(&v.receipt_hash) {
211 Some(bytes) => Ok((v, bytes)),
212 None => Err(Error::NotFound { what: "receipt", key: v.receipt_hash }),
213 }
214}