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(any(
feature = "registry-sqlite",
feature = "registry-postgres",
feature = "registry-mysql"
))]
use persistant_kv::KvOnRelational;
use persistant_relational::ConnectionSecret;
#[cfg(any(
feature = "registry-sqlite",
feature = "registry-postgres",
feature = "registry-mysql"
))]
use persistant_sqlx::Bounded;
#[cfg(feature = "registry-mysql")]
use persistant_sqlx::MysqlBackend;
#[cfg(feature = "registry-postgres")]
use persistant_sqlx::PgBackend;
#[cfg(feature = "registry-sqlite")]
use persistant_sqlx::SqliteBackend;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Endpoint {
None,
Path(PathBuf),
Url(String),
Secret(ConnectionSecret),
}
impl Endpoint {
pub fn path(p: impl AsRef<Path>) -> Self {
Endpoint::Path(p.as_ref().to_path_buf())
}
pub fn url_env(name: impl Into<String>) -> Self {
Endpoint::Secret(ConnectionSecret::Env(name.into()))
}
fn kind(&self) -> &'static str {
match self {
Endpoint::None => "none",
Endpoint::Path(_) => "path",
Endpoint::Url(_) | Endpoint::Secret(_) => "url",
}
}
fn url(&self) -> Result<Option<String>, OpenError> {
match self {
Endpoint::Url(u) => Ok(Some(u.clone())),
Endpoint::Secret(sec) => sec
.resolve()
.map(|r| Some(r.expose().to_string()))
.map_err(|e| OpenError::Open(format!("could not read the connection URL: {e}"))),
_ => Ok(None),
}
}
fn fits(&self, spec: &EndpointSpec) -> Result<bool, OpenError> {
Ok(match (self, spec) {
(Endpoint::None, EndpointSpec::None) => true,
(Endpoint::Path(_), EndpointSpec::Path) => true,
(Endpoint::Url(_) | Endpoint::Secret(_), EndpointSpec::Url { schemes }) => self
.url()?
.and_then(|u| u.split_once(':').map(|(s, _)| s.to_string()))
.is_some_and(|s| schemes.contains(&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),
BoundRequired {
id: &'static str,
},
BoundUnsupported {
id: &'static str,
},
ServerMismatch {
id: &'static str,
found: String,
},
CaseInsensitiveFilesystem {
id: &'static str,
path: PathBuf,
},
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::BoundRequired { id } => write!(
f,
"backend `{id}`: the needs include kv.bounded_call, which holds only when opened with OpenOptions::call_bound"
),
OpenError::BoundUnsupported { id } => {
write!(f, "backend `{id}` cannot be opened with a call bound")
}
OpenError::ServerMismatch { id, found } => {
write!(
f,
"backend `{id}` was asked for, but the server is `{found}`"
)
}
OpenError::CaseInsensitiveFilesystem { id, path } => write!(
f,
"backend `{id}` cannot be used at {}: the filesystem there ignores case, so keys that differ only by case would share one file and one value. Choose `sqlite`, `sqlite-full`, `postgres`, `mysql` or `mariadb` (each needs its `registry-*` Cargo feature), or a directory on a case-sensitive filesystem",
path.display()
),
OpenError::Open(m) => write!(f, "could not open: {m}"),
}
}
}
impl std::error::Error for OpenError {}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct OpenOptions {
pub call_bound: Option<Duration>,
}
impl OpenOptions {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn call_bound(mut self, bound: Duration) -> Self {
self.call_bound = Some(bound);
self
}
}
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,
reason = "v is pushed to only when a registry-sqlite, -postgres or -mysql feature is enabled"
)]
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.",
"Refuses to open in a directory on a filesystem that ignores case (the Windows and macOS defaults): a key is a file path, so `Key` and `key` would be one value. The check is made at open, on the directory itself, not assumed from the operating system.",
],
},
];
#[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.",
],
});
}
#[cfg(feature = "registry-postgres")]
v.push(Spec {
id: "postgres",
title: "PostgreSQL server",
kv_backend: "kv-on-relational:postgres",
facts: &[("dialect", "postgres")],
endpoint: || EndpointSpec::Url {
schemes: vec!["postgres".to_string(), "postgresql".to_string()],
},
notes: &[
"Opens from a connection URL (`postgres://...`); pass it as a secret (environment variable or file) so it is never printed.",
"Offered only on the server versions the recorded matrix covers; any other server version is refused at open with the unmet ids.",
"A full disk fails loud (a write returns an error and every acknowledged key is kept).",
],
});
#[cfg(feature = "registry-mysql")]
{
v.push(Spec {
id: "mysql",
title: "MySQL server",
kv_backend: "kv-on-relational:mysql",
facts: &[("dialect", "mysql")],
endpoint: || EndpointSpec::Url {
schemes: vec!["mysql".to_string()],
},
notes: &[
"Opens from a connection URL (`mysql://...`); pass it as a secret. A MariaDB server behind this id is refused: use `mariadb`.",
"Offered only on the server versions the recorded matrix covers.",
"CAVEAT: a full disk makes MySQL STALL, not fail: the call gets no answer and no error. Give every call your own timeout (the backend reports `call_bound`).",
],
});
v.push(Spec {
id: "mariadb",
title: "MariaDB server",
kv_backend: "kv-on-relational:mariadb",
facts: &[("dialect", "mariadb")],
endpoint: || EndpointSpec::Url {
schemes: vec!["mysql".to_string(), "mariadb".to_string()],
},
notes: &[
"Opens from a connection URL (`mysql://...` or `mariadb://...`); pass it as a secret. A MySQL server behind this id is refused: use `mysql`.",
"Offered only on the server versions the recorded matrix covers.",
"No durability class is declared for MariaDB (no power-loss run exists for it), so a need above Volatile does not list it.",
],
});
}
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,
reason = "m is merged into only when a registry-sqlite, -postgres or -mysql feature is enabled"
)]
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"),
);
#[cfg(feature = "registry-postgres")]
m.merge(
Matrix::parse(include_str!("../matrix/sqlx-postgres.tsv"))
.expect("embedded matrix/sqlx-postgres.tsv"),
);
#[cfg(feature = "registry-mysql")]
for text in [
include_str!("../matrix/sqlx-mysql.tsv"),
include_str!("../matrix/sqlx-mariadb.tsv"),
] {
m.merge(Matrix::parse(text).expect("embedded mysql/mariadb matrix"));
}
m
})
}
fn with_bound(config: &Config, bounded: bool) -> Config {
let kept: Vec<String> = config
.to_string()
.split(';')
.filter(|kv| !kv.is_empty() && !kv.starts_with("call_bound="))
.map(str::to_string)
.collect();
let mut c = Config::parse(&kept.join(";")).expect("config facts parse");
c = c.with("call_bound", if bounded { "set" } else { "unset" });
c
}
fn surface_for(s: &Spec, matrix: &Matrix, bounded: bool) -> 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(),
with_bound(&r.config, bounded),
),
None => {
let mut c = Config::new();
for (k, v) in s.facts {
c = c.with(*k, *v);
}
Surface::new(s.kv_backend, "", with_bound(&c, bounded))
}
}
}
fn provider_for(s: &Spec, matrix: &Matrix, bounded: bool) -> Provider {
Provider::new(
s.id,
vec![surface_for(s, matrix, bounded)],
persistant_kv::choose::declared_durability(s.kv_backend),
(s.endpoint)(),
)
}
fn table(matrix: &Matrix, bounded: bool) -> Vec<Provider> {
specs()
.iter()
.map(|s| provider_for(s, matrix, bounded))
.collect()
}
fn wants_bound(needs: &ProviderNeeds) -> bool {
needs.ids().iter().any(|i| i.as_str() == "kv.bounded_call")
}
#[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 recorded: String,
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)
));
}
if let Some((_, server)) = self.recorded.split_once('+') {
out.push(format!("recorded on version {server} only"));
}
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, bounded: bool) -> 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(),
recorded: s.provider.primary().version.clone(),
p50_ns: s.p50_ns,
notes: {
let mut n = spec.notes.to_vec();
if bounded {
n.push(
"kv.bounded_call: holds only when opened with a call bound (OpenOptions::call_bound); open_named refuses the open without one.",
);
}
n
},
}
}
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 bounded = wants_bound(needs);
let sorted = provider::select(&table(m, bounded), needs, m, speed)?;
Ok(sorted.iter().map(|s| listing(s, bounded)).collect())
}
#[derive(Debug)]
#[non_exhaustive]
pub enum AnyKv {
Blob(KvOnBlob<OpendalBlob>),
#[cfg(feature = "registry-sqlite")]
Sqlite(KvOnRelational<SqliteBackend>),
#[cfg(feature = "registry-sqlite")]
SqliteBounded(KvOnRelational<Bounded<SqliteBackend>>),
#[cfg(feature = "registry-postgres")]
Postgres(KvOnRelational<PgBackend>),
#[cfg(feature = "registry-postgres")]
PostgresBounded(KvOnRelational<Bounded<PgBackend>>),
#[cfg(feature = "registry-mysql")]
Mysql(KvOnRelational<MysqlBackend>),
#[cfg(feature = "registry-mysql")]
MysqlBounded(KvOnRelational<Bounded<MysqlBackend>>),
}
macro_rules! each {
($self:ident, $k:ident => $e:expr) => {
match $self {
AnyKv::Blob($k) => $e,
#[cfg(feature = "registry-sqlite")]
AnyKv::Sqlite($k) => $e,
#[cfg(feature = "registry-sqlite")]
AnyKv::SqliteBounded($k) => $e,
#[cfg(feature = "registry-postgres")]
AnyKv::Postgres($k) => $e,
#[cfg(feature = "registry-postgres")]
AnyKv::PostgresBounded($k) => $e,
#[cfg(feature = "registry-mysql")]
AnyKv::Mysql($k) => $e,
#[cfg(feature = "registry-mysql")]
AnyKv::MysqlBounded($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 count(&self, prefix: &str) -> Result<u64, KvError> {
each!(self, k => k.count(prefix).await)
}
async fn take(&self, key: &str) -> Result<Option<Vec<u8>>, KvError> {
each!(self, k => k.take(key).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 fn into_kv(self) -> AnyKv {
self.kv
}
}
pub async fn open_named(
id: &str,
endpoint: &Endpoint,
needs: &ProviderNeeds,
) -> Result<Handle, OpenError> {
open_named_with(id, endpoint, needs, &OpenOptions::new()).await
}
pub async fn open_named_with(
id: &str,
endpoint: &Endpoint,
needs: &ProviderNeeds,
options: &OpenOptions,
) -> 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(),
});
};
if wants_bound(needs) && options.call_bound.is_none() {
return Err(OpenError::BoundRequired { id: spec.id });
}
if options.call_bound.is_some() && matches!(spec.id, "memory" | "fs") {
return Err(OpenError::BoundUnsupported { id: spec.id });
}
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, options.call_bound.is_some());
provider::providers(std::slice::from_ref(&p), needs, m).map_err(OpenError::Unmet)?;
let kv = open_kv(spec.id, endpoint, options.call_bound).await?;
if kv.backend() != spec.kv_backend {
return Err(OpenError::ServerMismatch {
id: spec.id,
found: kv.backend().to_string(),
});
}
let actual = Provider::new(
spec.id,
vec![Surface::new(
kv.backend(),
kv.version(),
with_bound(&p.primary().config, kv.call_bound().is_some()),
)],
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 })
}
fn path_exists(p: &Path) -> bool {
p.symlink_metadata().is_ok()
}
fn directory_ignores_case(dir: &Path, exists: fn(&Path) -> bool) -> std::io::Result<bool> {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
let name = format!(".Persistant-Case-Probe-{}-{nanos}", std::process::id());
let flipped: String = name
.chars()
.map(|c| {
if c.is_ascii_lowercase() {
c.to_ascii_uppercase()
} else {
c.to_ascii_lowercase()
}
})
.collect();
debug_assert_ne!(name, flipped);
let probe = dir.join(&name);
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&probe)?;
let aliased = exists(&dir.join(&flipped));
std::fs::remove_file(&probe)?;
Ok(aliased)
}
async fn open_kv(
id: &str,
endpoint: &Endpoint,
bound: Option<Duration>,
) -> 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))?;
if directory_ignores_case(root, path_exists).map_err(|e| open(&e))? {
return Err(OpenError::CaseInsensitiveFilesystem {
id: "fs",
path: root.clone(),
});
}
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" | "sqlite-full", Endpoint::Path(file)) => {
let durable = id == "sqlite-full";
let connect = || async {
if durable {
SqliteBackend::open_durable(file).await
} else {
SqliteBackend::open(file).await
}
.map_err(|e| open(&e))
};
let db = connect().await?;
let kv = KvOnRelational::open(db).await.map_err(|e| open(&e))?;
match bound {
None => Ok(AnyKv::Sqlite(kv)),
Some(b) => {
drop(kv);
let db = Bounded::new(connect().await?, b);
Ok(AnyKv::SqliteBounded(
KvOnRelational::open(db).await.map_err(|e| open(&e))?,
))
}
}
}
#[cfg(feature = "registry-postgres")]
("postgres", Endpoint::Url(_) | Endpoint::Secret(_)) => {
let url = endpoint.url()?.unwrap_or_default();
let db = PgBackend::connect(&url).await.map_err(|e| open(&e))?;
let kv = KvOnRelational::open(db).await.map_err(|e| open(&e))?;
match bound {
None => Ok(AnyKv::Postgres(kv)),
Some(b) => {
drop(kv);
let db = PgBackend::connect(&url).await.map_err(|e| open(&e))?;
Ok(AnyKv::PostgresBounded(
KvOnRelational::open(Bounded::new(db, b))
.await
.map_err(|e| open(&e))?,
))
}
}
}
#[cfg(feature = "registry-mysql")]
("mysql" | "mariadb", Endpoint::Url(_) | Endpoint::Secret(_)) => {
let url = endpoint.url()?.unwrap_or_default();
let db = MysqlBackend::connect(&url).await.map_err(|e| open(&e))?;
let kv = KvOnRelational::open(db).await.map_err(|e| open(&e))?;
match bound {
None => Ok(AnyKv::Mysql(kv)),
Some(b) => {
drop(kv);
let db = MysqlBackend::connect(&url).await.map_err(|e| open(&e))?;
Ok(AnyKv::MysqlBounded(
KvOnRelational::open(Bounded::new(db, b))
.await
.map_err(|e| open(&e))?,
))
}
}
}
_ => Err(OpenError::Open(format!("no opener for `{id}`"))),
}
}
#[cfg(test)]
mod case_probe_tests {
use super::*;
#[test]
fn a_stand_in_that_sees_the_flipped_name_means_case_is_ignored() {
let dir = tempfile::tempdir().unwrap();
assert!(directory_ignores_case(dir.path(), |_| true).unwrap());
}
#[test]
fn a_stand_in_that_does_not_see_it_means_case_is_kept_and_the_probe_is_removed() {
let dir = tempfile::tempdir().unwrap();
assert!(!directory_ignores_case(dir.path(), |_| false).unwrap());
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
0,
"the probe file is gone"
);
assert!(directory_ignores_case(dir.path(), |_| true).unwrap());
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}
#[test]
fn a_directory_that_cannot_be_written_is_an_error_not_case_sensitive() {
let missing = std::env::temp_dir().join("persistant-no-such-dir-for-the-probe/x");
assert!(directory_ignores_case(&missing, path_exists).is_err());
}
#[test]
fn the_real_lookup_agrees_with_the_operating_system_default() {
let dir = tempfile::tempdir().unwrap();
let ignores = directory_ignores_case(dir.path(), path_exists).unwrap();
if cfg!(windows) {
assert!(ignores, "NTFS ignores case by default");
} else if cfg!(target_os = "linux") {
assert!(!ignores, "a Linux temp directory keeps case");
}
}
}