#![forbid(unsafe_code)]
#![deny(missing_docs)]
use std::borrow::Cow;
use datumesh_core::lexical::{check_hex, check_instant};
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 type RecordingClock = std::sync::Arc<dyn Fn() -> String + Send + Sync>;
pub(crate) fn instant_after(s: &str) -> String {
if s.len() != 27 || !s.is_ascii() || s.as_bytes()[19] != b'.' || s.as_bytes()[26] != b'Z' {
return s.to_string();
}
let num = |r: std::ops::Range<usize>| s[r].parse::<u64>().ok();
let (Some(mut y), Some(mut mo), Some(mut d), Some(mut h), Some(mut mi), Some(mut se), Some(mut us)) =
(num(0..4), num(5..7), num(8..10), num(11..13), num(14..16), num(17..19), num(20..26))
else {
return s.to_string();
};
us += 1;
if us == 1_000_000 {
us = 0;
se += 1;
}
if se == 60 {
se = 0;
mi += 1;
}
if mi == 60 {
mi = 0;
h += 1;
}
if h == 24 {
h = 0;
d += 1;
}
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
let dim = match mo {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return s.to_string(),
};
if d > dim {
d = 1;
mo += 1;
}
if mo == 13 {
mo = 1;
y += 1;
}
format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{se:02}.{us:06}Z")
}
pub(crate) fn later_of(a: &str, b: &str) -> String {
if a >= b {
a.to_string()
} else {
b.to_string()
}
}
pub(crate) fn recorded_at(clock: Option<&RecordingClock>, tx: &str) -> String {
match clock {
Some(now) => {
let now = now();
if now.as_str() > tx {
now
} else {
tx.to_string()
}
}
None => tx.to_string(),
}
}
pub use catalogue::{
CatalogEntry, CatalogEntryExt, CatalogKind, CatalogSource, Dictionary, DictionaryValue, EmbedRef, Embedding,
FacetedEntry, Facets, 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};
pub fn sort_key(args: &[(&str, &str, &str)]) -> Vec<u8> {
let mut sorted: Vec<&(&str, &str, &str)> = args.iter().collect();
sorted.sort_by(|a, b| a.0.cmp(b.0));
sorted.iter().flat_map(|(_, ty, value)| slices::sort_item(ty, value)).collect()
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MemberSet {
pub entry: String,
pub slice_id: String,
pub members_hash: String,
pub fn_hash: String,
pub slice: Vec<u8>,
pub members: u64,
pub tx: Option<String>,
pub asof: String,
pub licences: Vec<String>,
pub seen_seq: i64,
}
impl MemberSet {
pub fn from_manifest(manifest: &datumesh_core::Manifest, tx: Option<&str>, asof: &str) -> MemberSet {
let slice = manifest.slice();
MemberSet {
entry: manifest.entry(),
slice_id: slice.id().to_string(),
members_hash: manifest.members_hash().to_string(),
fn_hash: slice.fn_hash().to_string(),
slice: slice.canonical(),
members: manifest.members().len() as u64,
tx: tx.map(str::to_string),
asof: asof.to_string(),
licences: Vec::new(),
seen_seq: 0,
}
}
}
pub(crate) fn check_member_entry(entry: &str) -> Result<(&str, &str)> {
let bad = || Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "a member-set entry"));
let rest = entry.strip_prefix("slice:").ok_or_else(bad)?;
let (id, members_hash) = rest.split_once(':').ok_or_else(bad)?;
check_hex(id, 64, "slice_id")?;
check_hex(members_hash, 64, "members_hash")?;
Ok((id, members_hash))
}
pub(crate) fn hashes_limited(members: Vec<SliceMember>, limit: usize) -> Vec<String> {
let mut members: Vec<SliceMember> = members.into_iter().filter(|m| !m.version.withdrawn).collect();
members.truncate(limit);
members.into_iter().map(|m| m.version.receipt_hash).collect()
}
pub(crate) fn normal_licences(list: &[String]) -> Result<Vec<String>> {
if list.iter().any(|l| l.is_empty()) {
return Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"an empty licence",
)));
}
let mut out = list.to_vec();
out.sort();
out.dedup();
Ok(out)
}
pub(crate) fn licences_text(list: &[String]) -> String {
let arr =
datumesh_core::json::Value::Array(list.iter().map(|s| datumesh_core::json::Value::String(s.clone())).collect());
String::from_utf8(arr.to_jcs()).unwrap_or_default()
}
pub(crate) fn licences_of(text: &str) -> Result<Vec<String>> {
let bad =
|| Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "a stored licence list"));
match datumesh_core::json::parse(text.as_bytes()).map_err(Error::Invalid)? {
datumesh_core::json::Value::Array(items) => {
items.iter().map(|i| i.as_str().map(str::to_string).ok_or_else(bad)).collect()
}
_ => Err(bad()),
}
}
pub(crate) fn check_member_set(set: &MemberSet) -> Result<()> {
let (id, members_hash) = check_member_entry(&set.entry)?;
if set.members_hash != members_hash {
return Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"members_hash is not the entry's",
)));
}
if set.slice_id != id {
return Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"slice_id is not the entry's",
)));
}
check_hex(&set.fn_hash, 64, "fn_hash")?;
let slice = Slice::from_json(&set.slice).map_err(Error::Invalid)?;
if slice.id() != set.slice_id || slice.fn_hash() != set.fn_hash || slice.canonical() != set.slice {
return Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"the slice bytes are not the canonical slice of the id and function hash",
)));
}
check_instant(&set.asof, "asof")?;
if let Some(tx) = &set.tx {
check_instant(tx, "tx")?;
}
if set.members > 1_048_576 {
return Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"members is over the limit",
)));
}
Ok(())
}
#[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,
pub withdrawn: bool,
pub recorded: String,
pub seq: i64,
}
#[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,
pub sort_key: Vec<u8>,
}
#[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_member_set(&self, set: &MemberSet) -> Result<bool> {
let mut set = set.clone();
set.licences = normal_licences(&set.licences)?;
check_member_set(&set)?;
self.put_member_set_checked(&set)
}
fn slice_seq(&self, slice: &Slice) -> Result<i64> {
self.slice_seq_checked(slice)
}
fn recording_time(&self, signed_tx: &str) -> String {
crate::recorded_at(self.recording_clock_of().as_ref(), signed_tx)
}
#[doc(hidden)]
fn recording_clock_of(&self) -> Option<RecordingClock> {
None
}
fn barrier(&self) -> Result<()> {
self.barrier_checked()
}
#[doc(hidden)]
fn barrier_checked(&self) -> Result<()> {
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no barrier here")))
}
fn slice_member_hashes(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<String>> {
Ok(hashes_limited(self.slice_members(slice, asof)?, limit))
}
fn later_bound(&self, cell_id: &str, recorded: &str) -> Result<Option<String>> {
check_hex(cell_id, 64, "cell_id")?;
check_instant(recorded, "recorded")?;
self.later_bound_checked(cell_id, recorded)
}
#[doc(hidden)]
fn later_bound_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<String>> {
let _ = (cell_id, recorded);
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no versions here")))
}
fn slice_member_hashes_within(
&self,
slice: &Slice,
asof: &str,
limit: usize,
timeout: std::time::Duration,
) -> Result<Vec<String>> {
self.slice_member_hashes_within_checked(slice, asof, limit, timeout)
}
#[doc(hidden)]
fn slice_member_hashes_within_checked(
&self,
slice: &Slice,
asof: &str,
limit: usize,
timeout: std::time::Duration,
) -> Result<Vec<String>> {
let _ = timeout;
self.slice_member_hashes(slice, asof, limit)
}
fn next_version_after(&self, cell_id: &str, recorded: &str) -> Result<Option<Version>> {
check_hex(cell_id, 64, "cell_id")?;
check_instant(recorded, "recorded")?;
self.next_version_after_checked(cell_id, recorded)
}
#[doc(hidden)]
fn next_version_after_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<Version>> {
let _ = (cell_id, recorded);
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no versions here")))
}
fn fn_seq(&self, fn_hash: &str) -> Result<i64> {
check_hex(fn_hash, 64, "fn_hash")?;
self.fn_seq_checked(fn_hash)
}
#[doc(hidden)]
fn fn_seq_checked(&self, fn_hash: &str) -> Result<i64> {
let _ = fn_hash;
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no fn seq here")))
}
#[doc(hidden)]
fn slice_seq_checked(&self, slice: &Slice) -> Result<i64> {
let _ = slice;
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no slice seq here")))
}
fn member_set(&self, entry: &str) -> Result<Option<MemberSet>> {
check_member_entry(entry)?;
self.member_set_checked(entry)
}
fn put_slice_definition(&self, slice: &Slice) -> Result<bool> {
self.put_slice_definition_checked(slice)
}
fn slice_definition(&self, slice_id: &str) -> Result<Option<Slice>> {
check_hex(slice_id, 64, "slice_id")?;
self.slice_definition_checked(slice_id)
}
#[doc(hidden)]
fn put_member_set_checked(&self, set: &MemberSet) -> Result<bool> {
let _ = set;
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no member sets here")))
}
#[doc(hidden)]
fn member_set_checked(&self, entry: &str) -> Result<Option<MemberSet>> {
let _ = entry;
Err(Error::Invalid(datumesh_core::Error::new(datumesh_core::ErrorCode::Schema, "$", "no member sets here")))
}
#[doc(hidden)]
fn put_slice_definition_checked(&self, slice: &Slice) -> Result<bool> {
let _ = slice;
Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"no slice definitions here",
)))
}
#[doc(hidden)]
fn slice_definition_checked(&self, slice_id: &str) -> Result<Option<Slice>> {
let _ = slice_id;
Err(Error::Invalid(datumesh_core::Error::new(
datumesh_core::ErrorCode::Schema,
"$",
"no slice definitions here",
)))
}
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 close_binding(&self, name: &str, at: &str) -> Result<()> {
let _ = (name, at);
Err(Error::Unsupported("closing a binding needs a store of 0.6.0".into()))
}
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 class_names_bound_to(&self, class_hash: &str, at: &str) -> Result<Vec<String>> {
let _ = (class_hash, at);
Err(Error::Unsupported("class names need a store of 0.5.3".into()))
}
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 slice_withdrawn_latest(&self, slice: &Slice, asof: &str) -> Result<Option<(String, String)>> {
let _ = (slice, asof);
Err(Error::Unsupported("the withdrawn cells of a slice need a store of 0.6.0".into()))
}
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 upsert_catalog_ext(&self, entries: &[CatalogEntryExt]) -> Result<Vec<i64>> {
let _ = entries;
Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
}
fn catalog_entry_ext(&self, kind: CatalogKind, name: &str) -> Result<Option<CatalogEntryExt>> {
let _ = (kind, name);
Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
}
fn catalog_entries_with_facets(&self) -> Result<Vec<FacetedEntry>> {
Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
}
fn extensions_of(&self, class: &str) -> Result<Vec<CatalogEntryExt>> {
let _ = class;
Err(Error::Unsupported("catalogue facets need a store of 0.5.3".into()))
}
fn extensions_of_limit(&self, class: &str, limit: usize) -> Result<Vec<CatalogEntryExt>> {
let mut all = self.extensions_of(class)?;
all.truncate(limit);
Ok(all)
}
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_page(&self, slice: &Slice, asof: &str, after: Option<&[u8]>, limit: usize) -> Result<Vec<SliceValue>> {
if slice.is_version_slice() {
return Err(Error::Unsupported("a version slice has no key order to page by".into()));
}
if limit == 0 {
return Ok(Vec::new());
}
let values = self.slice_values(slice, asof)?;
Ok(values.into_iter().filter(|v| after.is_none_or(|a| v.sort_key.as_slice() > a)).take(limit).collect())
}
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 {}
}
pub(crate) struct Parsed {
pub(crate) canonical: Vec<u8>,
pub(crate) hash: String,
pub(crate) cell_id: String,
pub(crate) tx: String,
pub(crate) asof: String,
pub(crate) fn_hash: String,
pub(crate) publisher: String,
#[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
pub(crate) cell: Cell,
pub(crate) host: String,
pub(crate) entries: Vec<String>,
pub(crate) inputs: Vec<String>,
#[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
pub(crate) value: Option<(String, String)>,
}
#[cfg_attr(not(feature = "sqlite"), allow(dead_code))]
pub(crate) const WITHDRAWN_VALUE: &str = "";
pub(crate) fn parse_receipt(bytes: &[u8]) -> Result<Parsed> {
let withdrawal = datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some());
if withdrawal {
let w = datumesh_core::Withdrawal::from_json(bytes)?;
return Ok(Parsed {
canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
hash: w.hash().to_string(),
cell_id: w.cell().id(),
tx: w.tx().to_string(),
asof: w.asof().to_string(),
fn_hash: w.cell().fn_hash.clone(),
publisher: w.publisher().to_string(),
cell: w.cell().clone(),
host: w.signer_host().to_string(),
entries: Vec::new(),
inputs: Vec::new(),
value: None,
});
}
match datumesh_core::Receipt::from_json(bytes) {
Ok(r) => {
let (entries, inputs): (Vec<String>, Vec<String>) =
r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
let value = r.value();
Ok(Parsed {
canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
hash: r.hash().to_string(),
cell_id: r.cell().id(),
tx: r.tx().to_string(),
asof: r.asof().to_string(),
fn_hash: r.cell().fn_hash.clone(),
publisher: r.publisher().to_string(),
cell: r.cell().clone(),
host: r.signer_host().to_string(),
entries,
inputs,
value: Some((value.ty().as_str().to_string(), value.lexical().to_string())),
})
}
Err(e) => {
let Ok(w) = datumesh_core::Withdrawal::from_json(bytes) else { return Err(e.into()) };
Ok(Parsed {
canonical: datumesh_core::json::parse(bytes)?.to_jcs(),
hash: w.hash().to_string(),
cell_id: w.cell().id(),
tx: w.tx().to_string(),
asof: w.asof().to_string(),
fn_hash: w.cell().fn_hash.clone(),
publisher: w.publisher().to_string(),
cell: w.cell().clone(),
host: w.signer_host().to_string(),
entries: Vec::new(),
inputs: Vec::new(),
value: None,
})
}
}
}
pub(crate) fn stored_value(bytes: &[u8]) -> std::result::Result<Option<Scalar>, datumesh_core::Error> {
match datumesh_core::Receipt::from_json(bytes) {
Ok(r) => Ok(Some(r.value().clone())),
Err(e) => match datumesh_core::Withdrawal::from_json(bytes) {
Ok(_) => Ok(None),
Err(_) => Err(e),
},
}
}
pub(crate) fn unbound(name: &str) -> Error {
Error::NotFound { what: "binding", key: name.to_string() }
}
pub(crate) fn later_than(what: &'static str, key: &str, at: &str, latest: &str) -> Result<()> {
if at <= latest {
return Err(Error::NotLater { what, key: key.to_string(), given: at.to_string(), latest: latest.to_string() });
}
Ok(())
}
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 }),
}
}