use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::Duration;
use persistant_core::choose::{Declared, Durability, Need};
use persistant_core::provider::{
self, EndpointSpec, Provider, ProviderNeeds, Sorted, Surface, Unmet,
};
use persistant_core::{CapabilityId, Config, Matrix};
use persistant_kv::{BatchOp, BoundedProbe, KeyPage, KvBackend, KvError, KvOnBlob, ValuePage};
use persistant_opendal::OpendalBlob;
#[cfg(feature = "registry-sqlite")]
use persistant_kv::KvOnRelational;
#[cfg(feature = "registry-sqlite")]
use persistant_sqlx::SqliteBackend;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Endpoint {
None,
Path(PathBuf),
Url(String),
}
impl Endpoint {
pub fn path(p: impl AsRef<Path>) -> Self {
Endpoint::Path(p.as_ref().to_path_buf())
}
fn kind(&self) -> &'static str {
match self {
Endpoint::None => "none",
Endpoint::Path(_) => "path",
Endpoint::Url(_) => "url",
}
}
fn fits(&self, spec: &EndpointSpec) -> bool {
match (self, spec) {
(Endpoint::None, EndpointSpec::None) => true,
(Endpoint::Path(_), EndpointSpec::Path) => true,
(Endpoint::Url(u), EndpointSpec::Url { schemes }) => u
.split_once(':')
.is_some_and(|(s, _)| schemes.iter().any(|x| x == s)),
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum OpenError {
UnknownBackend {
id: String,
known: Vec<&'static str>,
},
WrongEndpoint {
id: &'static str,
wanted: EndpointSpec,
got: &'static str,
},
Unmet(Unmet),
Open(String),
}
impl fmt::Display for OpenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OpenError::UnknownBackend { id, known } => {
write!(
f,
"unknown backend id `{id}`; this build offers: {}",
known.join(", ")
)
}
OpenError::WrongEndpoint { id, wanted, got } => {
write!(f, "backend `{id}` opens from {wanted:?}, not a {got}")
}
OpenError::Unmet(u) => write!(f, "{u}"),
OpenError::Open(m) => write!(f, "could not open: {m}"),
}
}
}
impl std::error::Error for OpenError {}
struct Spec {
id: &'static str,
title: &'static str,
kv_backend: &'static str,
facts: &'static [(&'static str, &'static str)],
endpoint: fn() -> EndpointSpec,
notes: &'static [&'static str],
}
fn specs() -> Vec<Spec> {
#[allow(unused_mut)]
let mut v = vec![
Spec {
id: "memory",
title: "In-process memory",
kv_backend: "kv-on-blob:opendal-memory",
facts: &[("put_mode", "atomic")],
endpoint: || EndpointSpec::None,
notes: &["Lost when the process exits: for tests and caches only."],
},
Spec {
id: "fs",
title: "Files in a local directory",
kv_backend: "kv-on-blob:opendal-fs",
facts: &[("atomic_write_dir", "set"), ("put_mode", "atomic")],
endpoint: || EndpointSpec::Path,
notes: &[
"Opens from a directory path; writes go through a scratch directory beside it (`<dir>.persistant-atomic`) so a reader never sees a half-written value.",
"Survives the process exiting or crashing; no fsync is asserted, so a power cut can lose recent writes.",
],
},
];
#[cfg(feature = "registry-sqlite")]
{
v.push(Spec {
id: "sqlite",
title: "SQLite file (default durability)",
kv_backend: "kv-on-relational:sqlite",
facts: &[("dialect", "sqlite")],
endpoint: || EndpointSpec::Path,
notes: &[
"Survives the process exiting or crashing. SQLite's `synchronous` setting is not asserted here, so after a power cut the most recent writes may be lost.",
"Pick `sqlite-full` instead if the data must survive a power cut.",
],
});
v.push(Spec {
id: "sqlite-full",
title: "SQLite file, synchronous=FULL (survives power loss)",
kv_backend: "kv-on-relational:sqlite-full",
facts: &[("dialect", "sqlite")],
endpoint: || EndpointSpec::Path,
notes: &[
"Same storage as `sqlite`, opened with journal_mode=WAL and synchronous=FULL set explicitly: each acknowledged write is flushed before it returns. Slower writes than `sqlite`.",
"Verified by powering off a Hyper-V guest after acknowledged writes (nothing lost); NOT verified for host power loss, NTFS or the disk's own cache.",
],
});
}
v
}
pub fn known_ids() -> Vec<&'static str> {
specs().iter().map(|s| s.id).collect()
}
fn matrix() -> &'static Matrix {
static M: OnceLock<Matrix> = OnceLock::new();
M.get_or_init(|| {
#[allow(unused_mut)]
let mut m = Matrix::parse(include_str!("../matrix/opendal.tsv"))
.expect("embedded matrix/opendal.tsv");
#[cfg(feature = "registry-sqlite")]
m.merge(
Matrix::parse(include_str!("../matrix/sqlx-sqlite.tsv"))
.expect("embedded matrix/sqlx-sqlite.tsv"),
);
m
})
}
fn surface_for(s: &Spec, matrix: &Matrix) -> Surface {
let row = matrix.rows().iter().find(|r| {
r.backend == s.kv_backend && s.facts.iter().all(|(k, v)| r.config.get(k) == Some(v))
});
match row {
Some(r) => Surface::new(s.kv_backend, r.version.clone(), r.config.clone()),
None => {
let mut c = Config::new();
for (k, v) in s.facts {
c = c.with(*k, *v);
}
Surface::new(s.kv_backend, "", c)
}
}
}
fn provider_for(s: &Spec, matrix: &Matrix) -> Provider {
Provider::new(
s.id,
vec![surface_for(s, matrix)],
persistant_kv::choose::declared_durability(s.kv_backend),
(s.endpoint)(),
)
}
fn table(matrix: &Matrix) -> Vec<Provider> {
specs().iter().map(|s| provider_for(s, matrix)).collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Listing {
pub id: &'static str,
pub title: &'static str,
pub endpoint: EndpointSpec,
pub durability: Option<Declared>,
pub preferred: Vec<(CapabilityId, bool)>,
pub p50_ns: Option<u64>,
pub notes: Vec<&'static str>,
}
impl Listing {
pub fn why(&self) -> Vec<String> {
let mut out = Vec::new();
let join = |met: bool| {
self.preferred
.iter()
.filter(|(_, m)| *m == met)
.map(|(id, _)| id.as_str())
.collect::<Vec<_>>()
.join(", ")
};
if !self.preferred.is_empty() {
out.push(format!(
"preferred, in your order of importance: meets [{}]; lacks [{}]",
join(true),
join(false)
));
}
match self.p50_ns {
Some(ns) => out.push(format!("speed: median {ns} ns on the ranking workload")),
None => out.push("speed: not measured for the ranking workload here".to_string()),
}
match self.durability {
Some(d) => out.push(format!(
"durability: {} (verified: {}); {}",
d.class.as_str(),
d.verified.map_or("nothing", Durability::as_str),
d.basis
)),
None => out.push("durability: not declared".to_string()),
}
out.extend(self.notes.iter().map(|n| (*n).to_string()));
out
}
}
fn listing(s: &Sorted) -> Listing {
let spec = specs()
.into_iter()
.find(|x| x.id == s.provider.name())
.expect("a sorted provider came from the table");
Listing {
id: spec.id,
title: spec.title,
endpoint: s.provider.endpoint().clone(),
durability: s.provider.declared(),
preferred: s.preferred.clone(),
p50_ns: s.p50_ns,
notes: spec.notes.to_vec(),
}
}
pub fn providers(needs: &ProviderNeeds) -> Result<Vec<Listing>, Unmet> {
providers_ranked(needs, None)
}
pub fn providers_ranked(
needs: &ProviderNeeds,
speed: Option<(&Need, &persistant_core::bench::SpeedTable)>,
) -> Result<Vec<Listing>, Unmet> {
let m = matrix();
let sorted = provider::select(&table(m), needs, m, speed)?;
Ok(sorted.iter().map(listing).collect())
}
#[derive(Debug)]
#[non_exhaustive]
pub enum AnyKv {
Blob(KvOnBlob<OpendalBlob>),
#[cfg(feature = "registry-sqlite")]
Sqlite(KvOnRelational<SqliteBackend>),
}
macro_rules! each {
($self:ident, $k:ident => $e:expr) => {
match $self {
AnyKv::Blob($k) => $e,
#[cfg(feature = "registry-sqlite")]
AnyKv::Sqlite($k) => $e,
}
};
}
impl KvBackend for AnyKv {
fn backend(&self) -> &str {
each!(self, k => k.backend())
}
fn version(&self) -> &str {
each!(self, k => k.version())
}
fn call_bound(&self) -> Option<Duration> {
each!(self, k => k.call_bound())
}
async fn bounded_call_probe(&self) -> Result<BoundedProbe, KvError> {
each!(self, k => k.bounded_call_probe().await)
}
async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, KvError> {
each!(self, k => k.get(key).await)
}
async fn put(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<(), KvError> {
each!(self, k => k.put(key, value, ttl).await)
}
async fn delete(&self, key: &str) -> Result<(), KvError> {
each!(self, k => k.delete(key).await)
}
async fn put_if_absent(
&self,
key: &str,
value: Vec<u8>,
ttl: Option<Duration>,
) -> Result<bool, KvError> {
each!(self, k => k.put_if_absent(key, value, ttl).await)
}
async fn prefix_list(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<KeyPage, KvError> {
each!(self, k => k.prefix_list(prefix, after, limit).await)
}
async fn ordered_scan(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<KeyPage, KvError> {
each!(self, k => k.ordered_scan(prefix, after, limit).await)
}
async fn compare_and_swap(
&self,
key: &str,
expected: &[u8],
new: Vec<u8>,
ttl: Option<Duration>,
) -> Result<bool, KvError> {
each!(self, k => k.compare_and_swap(key, expected, new, ttl).await)
}
async fn compare_and_delete(&self, key: &str, expected: &[u8]) -> Result<bool, KvError> {
each!(self, k => k.compare_and_delete(key, expected).await)
}
async fn ttl_remaining(&self, key: &str) -> Result<Option<Duration>, KvError> {
each!(self, k => k.ttl_remaining(key).await)
}
async fn purge_expired(&self) -> Result<u64, KvError> {
each!(self, k => k.purge_expired().await)
}
async fn batch(&self, ops: &[BatchOp]) -> Result<bool, KvError> {
each!(self, k => k.batch(ops).await)
}
async fn ordered_scan_values(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<ValuePage, KvError> {
each!(self, k => k.ordered_scan_values(prefix, after, limit).await)
}
}
#[derive(Debug)]
pub struct Handle {
id: &'static str,
kv: AnyKv,
}
impl Handle {
pub fn id(&self) -> &'static str {
self.id
}
pub fn kv(&self) -> &AnyKv {
&self.kv
}
}
pub async fn open_named(
id: &str,
endpoint: &Endpoint,
needs: &ProviderNeeds,
) -> Result<Handle, OpenError> {
let m = matrix();
let all = specs();
let Some(spec) = all.iter().find(|s| s.id == id) else {
return Err(OpenError::UnknownBackend {
id: id.to_string(),
known: all.iter().map(|s| s.id).collect(),
});
};
let want = (spec.endpoint)();
if !endpoint.fits(&want) {
return Err(OpenError::WrongEndpoint {
id: spec.id,
wanted: want,
got: endpoint.kind(),
});
}
let p = provider_for(spec, m);
provider::providers(std::slice::from_ref(&p), needs, m).map_err(OpenError::Unmet)?;
let kv = open_kv(spec.id, endpoint).await?;
let actual = Provider::new(
spec.id,
vec![Surface::new(
kv.backend(),
kv.version(),
p.primary().config.clone(),
)],
persistant_kv::choose::declared_durability(kv.backend()),
p.endpoint().clone(),
);
provider::providers(std::slice::from_ref(&actual), needs, m).map_err(OpenError::Unmet)?;
Ok(Handle { id: spec.id, kv })
}
async fn open_kv(id: &str, endpoint: &Endpoint) -> Result<AnyKv, OpenError> {
let open = |e: &dyn fmt::Display| OpenError::Open(e.to_string());
match (id, endpoint) {
("memory", _) => Ok(AnyKv::Blob(KvOnBlob::new(
OpendalBlob::memory().map_err(|e| open(&e))?,
))),
("fs", Endpoint::Path(root)) => {
let mut scratch = root.clone().into_os_string();
scratch.push(".persistant-atomic");
let scratch = PathBuf::from(scratch);
std::fs::create_dir_all(root).map_err(|e| open(&e))?;
std::fs::create_dir_all(&scratch).map_err(|e| open(&e))?;
Ok(AnyKv::Blob(KvOnBlob::new(
OpendalBlob::fs(root, Some(&scratch)).map_err(|e| open(&e))?,
)))
}
#[cfg(feature = "registry-sqlite")]
("sqlite", Endpoint::Path(file)) => {
let db = SqliteBackend::open(file).await.map_err(|e| open(&e))?;
Ok(AnyKv::Sqlite(
KvOnRelational::open(db).await.map_err(|e| open(&e))?,
))
}
#[cfg(feature = "registry-sqlite")]
("sqlite-full", Endpoint::Path(file)) => {
let db = SqliteBackend::open_durable(file)
.await
.map_err(|e| open(&e))?;
Ok(AnyKv::Sqlite(
KvOnRelational::open(db).await.map_err(|e| open(&e))?,
))
}
_ => Err(OpenError::Open(format!("no opener for `{id}`"))),
}
}