#![forbid(unsafe_code)]
#![deny(missing_docs)]
use std::borrow::Cow;
pub use datumesh_core::Resolver;
use datumesh_core::{Cell, Scalar, Slice};
mod catalogue;
mod error;
mod functions;
pub mod migrate;
mod pg;
pub mod pg_unstable;
mod pool;
mod slices;
mod sql;
#[cfg(feature = "sqlite")]
mod sqlite;
#[cfg(feature = "sqlite")]
mod sqlite_sql;
mod tls;
pub use catalogue::{
CatalogEntry, CatalogKind, CatalogSource, Dictionary, DictionaryValue, EmbedRef, Embedding, Hit, KeyValue,
PendingEmbedding, Summary, SummaryEntry, FIND_MISSES_CAP,
};
pub use error::{DatabaseError, Error, Result};
pub use pg::PgStore;
pub use pool::PoolOptions;
#[cfg(feature = "sqlite")]
pub use sqlite::{SqliteOptions, SqliteStore};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Version {
pub cell_id: String,
pub tx: String,
pub receipt_hash: String,
pub asof: String,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CellWrite<'a> {
pub receipt: &'a [u8],
pub version: Option<(&'a str, &'a str)>,
}
impl<'a> CellWrite<'a> {
pub fn new(receipt: &'a [u8], version: Option<(&'a str, &'a str)>) -> Self {
CellWrite { receipt, version }
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SliceMember {
pub version: Version,
pub receipt: Vec<u8>,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SliceValue {
pub version: Version,
pub value: Scalar,
pub cell: Cell,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Binding {
pub fn_hash: String,
pub tx: String,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ClassBinding {
pub class_hash: String,
pub tx: String,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FunctionTest {
pub fn_hash: String,
pub case: String,
pub test_json: Vec<u8>,
pub signed_by: String,
pub last_run_at: Option<String>,
pub last_result: Option<String>,
pub last_detail: Option<String>,
pub branches_total: u32,
pub branches_covered: u32,
}
impl FunctionTest {
pub fn new(fn_hash: &str, case: &str, test_json: &[u8], signed_by: &str) -> FunctionTest {
FunctionTest {
fn_hash: fn_hash.to_string(),
case: case.to_string(),
test_json: test_json.to_vec(),
signed_by: signed_by.to_string(),
last_run_at: None,
last_result: None,
last_detail: None,
branches_total: 0,
branches_covered: 0,
}
}
}
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct TestSummary {
pub count: u64,
pub pass: u64,
pub fail: u64,
pub error: u64,
pub not_run: u64,
pub last_run_at: Option<String>,
pub branches_total: u32,
pub branches_covered: u32,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Namespace {
pub host: String,
pub keydoc: Vec<u8>,
pub validated_at: String,
pub suspended_at: Option<String>,
pub consecutive_failures: u32,
pub last_checked_at: Option<String>,
}
pub(crate) fn not_canonical_class() -> Error {
Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"class descriptor is not in canonical form (JCS): put the canonical bytes",
))
}
pub(crate) fn apply_check(ns: &mut Namespace, at: &str, threshold: Option<u32>) {
ns.last_checked_at = Some(at.to_string());
match threshold {
None => {
ns.consecutive_failures = 0;
ns.suspended_at = None;
}
Some(t) => {
ns.consecutive_failures = ns.consecutive_failures.saturating_add(1);
if ns.suspended_at.is_none() && ns.consecutive_failures >= t.max(1) {
ns.suspended_at = Some(at.to_string());
}
}
}
}
pub trait Store: Resolver + sealed::Sealed {
fn put_descriptor(&self, bytes: &[u8]) -> Result<String>;
fn put_receipt(&self, bytes: &[u8]) -> Result<String>;
fn put_blob(&self, bytes: &[u8]) -> Result<String>;
fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>>;
fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>>;
fn latest(&self, cell_id: &str) -> Result<Option<Version>>;
fn latest_many(&self, cell_ids: &[&str]) -> Result<Vec<Option<Version>>> {
cell_ids.iter().map(|id| self.latest(id)).collect()
}
fn receipts_many(&self, hashes: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
Ok(hashes.iter().map(|h| self.receipt(h).map(|b| b.into_owned())).collect())
}
fn put_cells(&self, items: &[CellWrite<'_>]) -> Result<Vec<String>> {
items
.iter()
.map(|w| {
let hash = self.put_receipt(w.receipt)?;
if let Some((cell_id, tx)) = w.version {
self.put_version(cell_id, tx, &hash)?;
}
Ok(hash)
})
.collect()
}
fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>>;
fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>>;
fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()>;
fn namespace(&self, host: &str) -> Result<Option<Namespace>>;
fn namespaces(&self) -> Result<Vec<Namespace>>;
fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>>;
fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>>;
fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()>;
fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>>;
fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>>;
fn put_class(&self, bytes: &[u8]) -> Result<String>;
fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>>;
fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()>;
fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>>;
fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>>;
fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()>;
fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>>;
fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>>;
fn put_manifest(&self, bytes: &[u8]) -> Result<String>;
fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>>;
fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>>;
fn slice_dependents(&self, entry: &str) -> Result<Vec<String>>;
fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>>;
fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>>;
fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>>;
fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool>;
fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>>;
fn has_bindings_under(&self, namespace: &str) -> Result<bool>;
fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>>;
fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>>;
fn refresh_value_counts(&self) -> Result<u64>;
fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>>;
fn vector_find(&self, model: &str, vec: &[f32], limit: usize) -> Result<Vec<Hit>>;
fn put_embeddings(&self, model: &str, items: &[Embedding]) -> Result<()>;
fn pending_embeddings(&self, model: &str, limit: usize) -> Result<Vec<PendingEmbedding>>;
fn vector_available(&self) -> bool;
fn log_miss(&self, query: &str) -> Result<()>;
fn catalog_summary(&self) -> Result<Summary>;
fn put_function_test(&self, test: &FunctionTest) -> Result<bool>;
fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>>;
fn record_function_test(&self, fn_hash: &str, case: &str, run_at: &str, result: &str, detail: &str)
-> Result<bool>;
fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()>;
fn function_readers(&self, name: &str) -> Result<Vec<String>>;
fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>>;
fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
let _ = (fn_hash, names);
Err(Error::Unsupported("naming function tests needs a store of 0.5.2".into()))
}
fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
let _ = limit;
Err(Error::Unsupported("unnamed tests need a store of 0.5.2".into()))
}
fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
if fn_name.is_some() {
return Err(Error::Unsupported("a summary by function name needs a store of 0.5.2".into()));
}
let mut s = TestSummary::default();
for t in self.function_tests(fn_hash)? {
s.count += 1;
match t.last_result.as_deref() {
Some("pass") => s.pass += 1,
Some("fail") => s.fail += 1,
Some("error") => s.error += 1,
_ => s.not_run += 1,
}
if let Some(at) = t.last_run_at {
if s.last_run_at.as_ref().is_none_or(|latest| at > *latest) {
s.last_run_at = Some(at);
}
}
s.branches_total = s.branches_total.max(t.branches_total);
s.branches_covered = s.branches_covered.max(t.branches_covered);
}
Ok(s)
}
fn function_tests_page(
&self,
fn_hash: &str,
fn_name: Option<&str>,
after_case: Option<&str>,
limit: usize,
) -> Result<Vec<FunctionTest>> {
if fn_name.is_some() {
return Err(Error::Unsupported("a page by function name needs a store of 0.5.2".into()));
}
Ok(self
.function_tests(fn_hash)?
.into_iter()
.filter(|t| after_case.is_none_or(|after| t.case.as_str() > after))
.take(limit)
.collect())
}
fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
let _ = (ns, fn_name, fn_hash, limit);
Err(Error::Unsupported("stored receipts of a function need a store of 0.5.2".into()))
}
fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
let mut values = self.slice_values(slice, asof)?;
values.truncate(limit);
Ok(values)
}
fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
let mut versions = self.versions(cell_id, from, to)?;
versions.truncate(limit);
Ok(versions)
}
fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
let _ = (ns, fn_name, fn_hash);
Err(Error::Unsupported("counting a function's cells needs a store of 0.5.2".into()))
}
fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
Ok(self.text_find(value, usize::MAX)?.iter().any(
|h| matches!(h, Hit::Value { owner: o, key: k, value: v, .. } if o == owner && k == key && v == value),
))
}
fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
let _ = (owner, key);
Err(Error::Unsupported("counting a dictionary needs a store of 0.5.2".into()))
}
fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
let _ = (owner, key);
Err(Error::Unsupported("open keys need a store of 0.5.2".into()))
}
fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
let _ = (owner, key);
Err(Error::Unsupported("open keys need a store of 0.5.2".into()))
}
fn open_key_count(&self) -> Result<u64> {
Ok(0)
}
fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
let _ = name;
Err(Error::Unsupported("an exact catalogue lookup needs a store of 0.5.2".into()))
}
fn cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
self.stored_cell_count(ns, fn_name, fn_hash)
}
fn function_test(&self, fn_hash: &str, case: &str) -> Result<Option<FunctionTest>> {
Ok(self.function_tests(fn_hash)?.into_iter().find(|t| t.case == case))
}
fn function_tests_failing(&self, fn_hash: &str, fn_name: Option<&str>, limit: usize) -> Result<Vec<FunctionTest>> {
let mut out = Vec::new();
if limit == 0 {
return Ok(out);
}
let mut after: Option<String> = None;
loop {
let page = self.function_tests_page(fn_hash, fn_name, after.as_deref(), 256)?;
let Some(last) = page.last() else { return Ok(out) };
after = Some(last.case.clone());
for t in page {
if matches!(t.last_result.as_deref(), Some("fail") | Some("error")) {
out.push(t);
if out.len() == limit {
return Ok(out);
}
}
}
}
}
fn false_test_cells(&self, fn_hash: &str, limit: usize) -> Result<Vec<(String, Vec<u8>)>> {
let _ = (fn_hash, limit);
Err(Error::Unsupported("false test cells need a store of 0.5.3".into()))
}
fn dependants_of(&self, name: &str, at: &str, limit: usize) -> Result<Vec<(String, String)>> {
let mut out = Vec::new();
if limit == 0 {
return Ok(out);
}
for h in self.function_readers(name)? {
for n in self.bound_names(&h)? {
if self.resolve_name(&n, at)?.as_deref() == Some(h.as_str()) {
out.push((n, h.clone()));
if out.len() == limit {
return Ok(out);
}
}
}
}
Ok(out)
}
fn slice_values_page(
&self,
slice: &Slice,
asof: &str,
after_cell_id: Option<&str>,
limit: usize,
) -> Result<Vec<SliceValue>> {
let mut values = self.slice_values(slice, asof)?;
values.retain(|v| after_cell_id.is_none_or(|a| v.version.cell_id.as_str() > a));
values.sort_by(|a, b| a.version.cell_id.cmp(&b.version.cell_id));
values.truncate(limit);
Ok(values)
}
fn catalog_entries_all(&self, limit: usize) -> Result<Vec<(CatalogKind, String, String, String)>> {
let _ = limit;
Err(Error::Unsupported("the catalogue's entries need a store of 0.5.3".into()))
}
fn dictionary_values_ordered(&self, owner: &str, key: &str, limit: usize) -> Result<Vec<String>> {
let _ = (owner, key, limit);
Err(Error::Unsupported("ordered dictionary values need a store of 0.5.3".into()))
}
fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
match self.computed_asof(cell_id, asof)? {
Some(v) => with_receipt(self, v).map(Some),
None => Ok(None),
}
}
fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
match self.stored_asof(cell_id, asof)? {
Some(v) => with_receipt(self, v).map(Some),
None => Ok(None),
}
}
}
mod sealed {
pub trait Sealed {}
impl Sealed for crate::PgStore {}
#[cfg(feature = "sqlite")]
impl Sealed for crate::SqliteStore {}
}
fn with_receipt<S: Store + ?Sized>(store: &S, v: Version) -> Result<(Version, Cow<'_, [u8]>)> {
match store.receipt(&v.receipt_hash) {
Some(bytes) => Ok((v, bytes)),
None => Err(Error::NotFound { what: "receipt", key: v.receipt_hash }),
}
}