use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::OnceLock;
use std::time::Duration;
use persistant_blob::{BlobBackend, BlobError, BlobSink, Entry, KeyLayout, Page};
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, Dialect, Isolation, RelError, RelationalBackend, RelationalTx, Row, Value,
};
#[cfg(any(
feature = "registry-sqlite",
feature = "registry-postgres",
feature = "registry-mysql"
))]
use persistant_sqlx::{Bounded, BoundedTx};
#[cfg(feature = "registry-mysql")]
use persistant_sqlx::{MysqlBackend, MysqlTx};
#[cfg(feature = "registry-postgres")]
use persistant_sqlx::{PgBackend, PgTx};
#[cfg(feature = "registry-sqlite")]
use persistant_sqlx::{SqliteBackend, SqliteTx};
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Endpoint {
None,
Path(PathBuf),
#[deprecated(
since = "0.17.0",
note = "use `Endpoint::Secret(ConnectionSecret::literal(url))` or `Endpoint::url_env(name)`: a URL usually carries a password"
)]
Url(String),
Secret(ConnectionSecret),
}
fn redact_url(url: &str) -> String {
let Some((scheme, rest)) = url.split_once("://") else {
return "<redacted>".to_string();
};
let (rest, fragment) = match rest.split_once('#') {
Some((r, _)) => (r, true),
None => (rest, false),
};
let (location, query) = match rest.split_once('?') {
Some((l, q)) => (l, Some(q)),
None => (rest, None),
};
let location = match location.rsplit_once('@') {
Some((_, after)) => format!("<redacted>@{after}"),
None => location.to_string(),
};
let mut out = format!("{scheme}://{location}");
if let Some(q) = query {
let pairs: Vec<String> = q
.split('&')
.map(|pair| match pair.split_once('=') {
Some((name, _)) => format!("{name}=<redacted>"),
None => "<redacted>".to_string(),
})
.collect();
out.push('?');
out.push_str(&pairs.join("&"));
}
if fragment {
out.push_str("#<redacted>");
}
out
}
#[allow(
deprecated,
reason = "`Endpoint::Url` is deprecated (0.17.0); the registry still accepts it until it is removed"
)]
impl fmt::Debug for Endpoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Endpoint::None => f.write_str("None"),
Endpoint::Path(p) => f.debug_tuple("Path").field(p).finish(),
Endpoint::Url(u) => f
.debug_tuple("Url")
.field(&format_args!("{}", redact_url(u)))
.finish(),
Endpoint::Secret(sec) => f.debug_tuple("Secret").field(sec).finish(),
}
}
}
#[allow(
deprecated,
reason = "`Endpoint::Url` is deprecated (0.17.0); the registry still accepts it until it is removed"
)]
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),
}
}
pub 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,
},
LiveCheckUnsupported {
id: &'static str,
},
LiveCheck {
id: &'static str,
reason: String,
},
ServerMismatch {
id: &'static str,
found: String,
},
CaseInsensitiveFilesystem {
id: &'static str,
path: PathBuf,
},
KindNotServed {
id: &'static str,
kind: &'static str,
},
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::LiveCheckUnsupported { id } => write!(
f,
"backend `{id}` has no relational layer to run a live check on (`sqlite`, `sqlite-full`, `postgres`, `mysql` and `mariadb` do)"
),
OpenError::LiveCheck { id, reason } => {
write!(f, "backend `{id}`: the live check at open failed: {reason}")
}
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::KindNotServed { id, kind } => write!(
f,
"backend `{id}` has every {kind}.* capability asked for, but this release's handle does not serve that kind yet"
),
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>,
pub live_check: bool,
}
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
}
#[must_use]
pub fn with_live_check(mut self) -> Self {
self.live_check = true;
self
}
}
async fn run_live_check<R: RelationalBackend>(db: &R) -> Result<(), String> {
const T: &str = "persistant_live_check";
let drop = match db.dialect() {
Dialect::MySql | Dialect::MariaDb => format!("DROP TEMPORARY TABLE {T}"),
_ => format!("DROP TABLE {T}"),
};
let mut tx = db
.begin(Isolation::ReadCommitted)
.await
.map_err(|e| format!("begin a transaction: {e}"))?;
let steps: Result<(), String> = async {
tx.execute(
&format!("CREATE TEMPORARY TABLE {T} (id BIGINT PRIMARY KEY, v BIGINT NOT NULL)"),
&[],
)
.await
.map_err(|e| format!("create a temporary table (does the role hold TEMP?): {e}"))?;
tx.execute(&format!("INSERT INTO {T} (id, v) VALUES (1, 7)"), &[])
.await
.map_err(|e| format!("write to a temporary table: {e}"))?;
let rows = tx
.query(&format!("SELECT v FROM {T} WHERE id = 1"), &[])
.await
.map_err(|e| format!("read a temporary table: {e}"))?;
if rows.len() != 1 {
return Err(format!(
"the row just written was read back {} time(s), not once",
rows.len()
));
}
tx.execute(&drop, &[])
.await
.map_err(|e| format!("drop the temporary table: {e}"))?;
Ok(())
}
.await;
let rolled = tx.rollback().await;
steps?;
rolled.map_err(|e| format!("roll back: {e}"))
}
struct Spec {
id: &'static str,
title: &'static str,
kv_backend: &'static str,
facts: &'static [(&'static str, &'static str)],
blob: Option<Layer>,
rel: Option<Layer>,
endpoint: fn() -> EndpointSpec,
notes: &'static [&'static str],
}
type Layer = (&'static str, &'static [(&'static str, &'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")],
blob: Some(("opendal-memory", &[])),
rel: None,
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")],
blob: Some(("opendal-fs", &[("atomic_write_dir", "set")])),
rel: None,
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.",
"A key is stored under its bytes in lower-case hex (`kvx/` in the directory), so keys that differ only by case stay apart on a filesystem that ignores case (Windows, macOS), whatever the key contains. A directory written by 0.9.41 or earlier is migrated at open.",
"Needs the directory and its scratch directory on one filesystem with hard links (the exclusive create links a finished scratch file to the key).",
],
},
];
#[cfg(feature = "registry-sqlite")]
{
v.push(Spec {
id: "sqlite",
title: "SQLite file (default durability)",
kv_backend: "kv-on-relational:sqlite",
facts: &[("dialect", "sqlite")],
blob: None,
rel: Some(("sqlite", &[("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.",
"`kv.delete_erased` and the text index's erased removal are recorded off here: stale in-page fragments of earlier writes (page splits, made while `secure_delete` was off) stay in the file once there are many records. Pick `sqlite-secure` to forget data.",
],
});
v.push(Spec {
id: "sqlite-full",
title: "SQLite file, synchronous=FULL (survives power loss)",
kv_backend: "kv-on-relational:sqlite-full",
facts: &[("dialect", "sqlite")],
blob: None,
rel: Some(("sqlite-full", &[("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.",
"`kv.delete_erased` and the text index's erased removal are recorded off here, as on `sqlite`: stale in-page fragments of earlier writes stay in the file. Pick `sqlite-secure` to forget data.",
],
});
}
#[cfg(feature = "registry-sqlite")]
v.push(Spec {
id: "sqlite-secure",
title: "SQLite file, secure delete (freed content zeroed)",
kv_backend: "kv-on-relational:sqlite",
facts: &[("dialect", "sqlite"), ("secure_delete", "on")],
blob: None,
rel: Some((
"sqlite",
&[("dialect", "sqlite"), ("secure_delete", "on")],
)),
endpoint: || EndpointSpec::Path,
notes: &[
"Same engine and rollback journal as `sqlite` (default durability, no `synchronous` assertion), opened with `secure_delete` on for every connection: a delete or an overwrite leaves no old bytes in the database file. Slower writes.",
"Not WAL: `secure_delete` does not reach a WAL file's earlier page images, so there is no durable form; on a WAL database use `kv.delete_erased`, which checkpoints. The rollback journal's pre-images are removed, not zeroed, at the end of each transaction, and file systems, snapshots and backups can keep copies.",
],
});
#[cfg(feature = "registry-postgres")]
v.push(Spec {
id: "postgres",
title: "PostgreSQL server",
kv_backend: "kv-on-relational:postgres",
facts: &[("dialect", "postgres")],
blob: None,
rel: Some(("postgres", &[("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")],
blob: None,
rel: Some(("mysql", &[("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")],
blob: None,
rel: Some(("mariadb", &[("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
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Kv,
Blob,
Rel,
}
fn kind_of(id: &str) -> Kind {
if id.starts_with("blob.") {
Kind::Blob
} else if id.starts_with("rel.") {
Kind::Rel
} else {
Kind::Kv
}
}
fn kinds_named(needs: &ProviderNeeds) -> Vec<Kind> {
let mut v: Vec<Kind> = [Kind::Kv, Kind::Blob, Kind::Rel]
.into_iter()
.filter(|k| needs.ids().iter().any(|i| kind_of(i.as_str()) == *k))
.collect();
if v.is_empty() {
v.push(Kind::Kv);
}
v
}
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 layer_surface(layer: Layer, matrix: &Matrix) -> Surface {
let (backend, facts) = layer;
let row = matrix
.rows()
.iter()
.find(|r| r.backend == backend && facts.iter().all(|(k, v)| r.config.get(k) == Some(v)));
match row {
Some(r) => Surface::new(backend, r.version.clone(), r.config.clone()),
None => {
let mut c = Config::new();
for (k, v) in facts {
c = c.with(*k, *v);
}
Surface::new(backend, "", c)
}
}
}
fn surfaces_for(s: &Spec, matrix: &Matrix, bounded: bool, kinds: &[Kind]) -> Vec<(Kind, Surface)> {
let mut out: Vec<(Kind, Surface)> = kinds
.iter()
.filter_map(|k| match k {
Kind::Kv => Some((Kind::Kv, surface_for(s, matrix, bounded))),
Kind::Blob => s.blob.map(|l| (Kind::Blob, layer_surface(l, matrix))),
Kind::Rel => s.rel.map(|l| (Kind::Rel, layer_surface(l, matrix))),
})
.collect();
if out.is_empty() {
out.push((Kind::Kv, surface_for(s, matrix, bounded)));
}
out
}
fn weakest_declared(surfaces: &[(Kind, Surface)]) -> Option<Declared> {
let mut weakest: Option<Declared> = None;
for (kind, surface) in surfaces {
let d = match kind {
Kind::Kv => persistant_kv::choose::declared_durability(&surface.backend),
Kind::Blob => persistant_blob::choose::declared_durability(&surface.backend),
Kind::Rel => persistant_relational::choose::declared_durability(&surface.backend),
}?;
weakest = match weakest {
Some(w) if w.class <= d.class => Some(w),
_ => Some(d),
};
}
weakest
}
fn provider_for(s: &Spec, matrix: &Matrix, bounded: bool, kinds: &[Kind]) -> Provider {
let surfaces = surfaces_for(s, matrix, bounded, kinds);
let declared = weakest_declared(&surfaces);
Provider::new(
s.id,
surfaces.into_iter().map(|(_, surface)| surface).collect(),
declared,
(s.endpoint)(),
)
}
fn table(matrix: &Matrix, bounded: bool, kinds: &[Kind]) -> Vec<Provider> {
specs()
.iter()
.map(|s| provider_for(s, matrix, bounded, kinds))
.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, kinds: &[Kind]) -> 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.",
);
}
if kinds.len() > 1 {
n.push(
"The need names more than one kind: the durability shown is the weakest of them, and a speed ranking uses the first kind named.",
);
}
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 kinds = kinds_named(needs);
let sorted = provider::select(&table(m, bounded, &kinds), needs, m, speed)?;
Ok(sorted.iter().map(|s| listing(s, bounded, &kinds)).collect())
}
pub fn explain(needs: &ProviderNeeds, id: &str) -> Option<Vec<String>> {
let m = matrix();
let bounded = wants_bound(needs);
let kinds = kinds_named(needs);
provider::explain(&table(m, bounded, &kinds), needs, m, id)
}
#[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 delete_erased(&self, key: &str) -> Result<(), KvError> {
each!(self, k => k.delete_erased(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)]
#[non_exhaustive]
pub enum AnyRel {
#[doc(hidden)]
Never(std::convert::Infallible),
#[cfg(feature = "registry-sqlite")]
Sqlite(SqliteBackend),
#[cfg(feature = "registry-sqlite")]
SqliteBounded(Bounded<SqliteBackend>),
#[cfg(feature = "registry-postgres")]
Postgres(PgBackend),
#[cfg(feature = "registry-postgres")]
PostgresBounded(Bounded<PgBackend>),
#[cfg(feature = "registry-mysql")]
Mysql(MysqlBackend),
#[cfg(feature = "registry-mysql")]
MysqlBounded(Bounded<MysqlBackend>),
}
#[non_exhaustive]
pub enum AnyTx<'a> {
#[doc(hidden)]
Never(std::convert::Infallible, PhantomData<&'a ()>),
#[cfg(feature = "registry-sqlite")]
Sqlite(SqliteTx),
#[cfg(feature = "registry-sqlite")]
SqliteBounded(BoundedTx<SqliteTx>),
#[cfg(feature = "registry-postgres")]
Postgres(PgTx<'a>),
#[cfg(feature = "registry-postgres")]
PostgresBounded(BoundedTx<PgTx<'a>>),
#[cfg(feature = "registry-mysql")]
Mysql(MysqlTx),
#[cfg(feature = "registry-mysql")]
MysqlBounded(BoundedTx<MysqlTx>),
}
macro_rules! each_rel {
($self:ident, $r:ident => $e:expr) => {
match $self {
AnyRel::Never(n) => match *n {},
#[cfg(feature = "registry-sqlite")]
AnyRel::Sqlite($r) => $e,
#[cfg(feature = "registry-sqlite")]
AnyRel::SqliteBounded($r) => $e,
#[cfg(feature = "registry-postgres")]
AnyRel::Postgres($r) => $e,
#[cfg(feature = "registry-postgres")]
AnyRel::PostgresBounded($r) => $e,
#[cfg(feature = "registry-mysql")]
AnyRel::Mysql($r) => $e,
#[cfg(feature = "registry-mysql")]
AnyRel::MysqlBounded($r) => $e,
}
};
}
macro_rules! each_tx {
($self:ident, $t:ident => $e:expr) => {
match $self {
AnyTx::Never(..) => unreachable!("AnyTx::Never is never constructed"),
#[cfg(feature = "registry-sqlite")]
AnyTx::Sqlite($t) => $e,
#[cfg(feature = "registry-sqlite")]
AnyTx::SqliteBounded($t) => $e,
#[cfg(feature = "registry-postgres")]
AnyTx::Postgres($t) => $e,
#[cfg(feature = "registry-postgres")]
AnyTx::PostgresBounded($t) => $e,
#[cfg(feature = "registry-mysql")]
AnyTx::Mysql($t) => $e,
#[cfg(feature = "registry-mysql")]
AnyTx::MysqlBounded($t) => $e,
}
};
}
#[cfg_attr(
not(any(
feature = "registry-sqlite",
feature = "registry-postgres",
feature = "registry-mysql"
)),
allow(
unused_variables,
reason = "with no relational driver built in, every arm but `Never` is compiled out"
)
)]
impl RelationalBackend for AnyRel {
type Tx<'a>
= AnyTx<'a>
where
Self: 'a;
fn backend(&self) -> &str {
each_rel!(self, r => r.backend())
}
fn version(&self) -> &str {
each_rel!(self, r => r.version())
}
fn dialect(&self) -> Dialect {
each_rel!(self, r => r.dialect())
}
async fn execute(&self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
each_rel!(self, r => r.execute(sql, params).await)
}
async fn execute_erased(&self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
each_rel!(self, r => r.execute_erased(sql, params).await)
}
async fn query(&self, sql: &str, params: &[Value]) -> Result<Vec<Row>, RelError> {
each_rel!(self, r => r.query(sql, params).await)
}
async fn begin(&self, isolation: Isolation) -> Result<AnyTx<'_>, RelError> {
match self {
AnyRel::Never(n) => match *n {},
#[cfg(feature = "registry-sqlite")]
AnyRel::Sqlite(r) => Ok(AnyTx::Sqlite(r.begin(isolation).await?)),
#[cfg(feature = "registry-sqlite")]
AnyRel::SqliteBounded(r) => Ok(AnyTx::SqliteBounded(r.begin(isolation).await?)),
#[cfg(feature = "registry-postgres")]
AnyRel::Postgres(r) => Ok(AnyTx::Postgres(r.begin(isolation).await?)),
#[cfg(feature = "registry-postgres")]
AnyRel::PostgresBounded(r) => Ok(AnyTx::PostgresBounded(r.begin(isolation).await?)),
#[cfg(feature = "registry-mysql")]
AnyRel::Mysql(r) => Ok(AnyTx::Mysql(r.begin(isolation).await?)),
#[cfg(feature = "registry-mysql")]
AnyRel::MysqlBounded(r) => Ok(AnyTx::MysqlBounded(r.begin(isolation).await?)),
}
}
fn call_bound(&self) -> Option<Duration> {
each_rel!(self, r => r.call_bound())
}
async fn with_lock_held<'a>(
&'a self,
lock_sql: &'a str,
at_most: Duration,
during: Pin<Box<dyn Future<Output = ()> + Send + 'a>>,
) -> Result<(), RelError> {
each_rel!(self, r => r.with_lock_held(lock_sql, at_most, during).await)
}
}
#[cfg_attr(
not(any(
feature = "registry-sqlite",
feature = "registry-postgres",
feature = "registry-mysql"
)),
allow(
unused_variables,
reason = "with no relational driver built in, every arm but `Never` is compiled out"
)
)]
impl RelationalTx for AnyTx<'_> {
async fn execute(&mut self, sql: &str, params: &[Value]) -> Result<u64, RelError> {
each_tx!(self, t => t.execute(sql, params).await)
}
async fn query(&mut self, sql: &str, params: &[Value]) -> Result<Vec<Row>, RelError> {
each_tx!(self, t => t.query(sql, params).await)
}
async fn erase_on_commit(&mut self) -> Result<(), RelError> {
each_tx!(self, t => t.erase_on_commit().await)
}
async fn commit(self) -> Result<(), RelError> {
each_tx!(self, t => t.commit().await)
}
async fn rollback(self) -> Result<(), RelError> {
each_tx!(self, t => t.rollback().await)
}
}
#[derive(Debug)]
pub struct Handle {
id: &'static str,
kv: AnyKv,
blob: Option<AnyBlob>,
rel: Option<AnyRel>,
}
const RESERVED: [&str; 2] = ["kv", "kvx"];
fn reserved(key: &str) -> Option<&'static str> {
RESERVED.into_iter().find(|r| {
key == *r
|| key
.strip_prefix(r)
.is_some_and(|rest| rest.starts_with('/'))
})
}
fn refuse(key: &str, prefix: &str) -> BlobError {
BlobError::Backend(format!(
"key `{key}` is under `{prefix}/`, which the registry keeps for the key-value store; choose another key"
))
}
#[derive(Debug)]
pub struct AnyBlob {
inner: OpendalBlob,
}
impl AnyBlob {
pub fn config(&self) -> &Config {
self.inner.config()
}
}
fn check(key: &str) -> Result<(), BlobError> {
match reserved(key) {
Some(r) => Err(refuse(key, r)),
None => Ok(()),
}
}
impl BlobBackend for AnyBlob {
fn backend(&self) -> &str {
self.inner.backend()
}
fn version(&self) -> &str {
self.inner.version()
}
fn max_value_size(&self) -> Option<u64> {
self.inner.max_value_size()
}
fn key_layout(&self) -> KeyLayout {
self.inner.key_layout()
}
async fn read(&self, key: &str) -> Result<Option<Vec<u8>>, BlobError> {
check(key)?;
self.inner.read(key).await
}
async fn write(&self, key: &str, bytes: Vec<u8>) -> Result<(), BlobError> {
check(key)?;
self.inner.write(key, bytes).await
}
async fn delete(&self, key: &str) -> Result<(), BlobError> {
check(key)?;
self.inner.delete(key).await
}
async fn delete_erased(&self, key: &str) -> Result<(), BlobError> {
check(key)?;
self.inner.delete_erased(key).await
}
async fn stat(&self, key: &str) -> Result<Option<Entry>, BlobError> {
check(key)?;
self.inner.stat(key).await
}
async fn list(
&self,
prefix: &str,
after: Option<&str>,
limit: usize,
) -> Result<Page, BlobError> {
if let Some(r) = reserved(prefix) {
return Err(refuse(prefix, r));
}
let mut page = self.inner.list(prefix, after, limit).await?;
page.entries.retain(|e| reserved(&e.key).is_none());
Ok(page)
}
async fn create_exclusive(&self, key: &str, bytes: Vec<u8>) -> Result<bool, BlobError> {
check(key)?;
self.inner.create_exclusive(key, bytes).await
}
async fn replace_atomic(&self, key: &str, bytes: Vec<u8>) -> Result<(), BlobError> {
check(key)?;
self.inner.replace_atomic(key, bytes).await
}
async fn append(&self, key: &str, bytes: Vec<u8>) -> Result<(), BlobError> {
check(key)?;
self.inner.append(key, bytes).await
}
async fn read_range(
&self,
key: &str,
offset: u64,
len: u64,
) -> Result<Option<Vec<u8>>, BlobError> {
check(key)?;
self.inner.read_range(key, offset, len).await
}
async fn read_range_if(
&self,
key: &str,
offset: u64,
len: u64,
tag: &str,
) -> Result<Option<Vec<u8>>, BlobError> {
check(key)?;
self.inner.read_range_if(key, offset, len, tag).await
}
async fn write_stream(&self, key: &str) -> Result<Box<dyn BlobSink>, BlobError> {
check(key)?;
self.inner.write_stream(key).await
}
async fn write_stream_atomic(&self, key: &str) -> Result<Box<dyn BlobSink>, BlobError> {
check(key)?;
self.inner.write_stream_atomic(key).await
}
}
impl Handle {
pub fn id(&self) -> &'static str {
self.id
}
pub fn kv(&self) -> &AnyKv {
&self.kv
}
pub fn blob(&self) -> Option<&AnyBlob> {
self.blob.as_ref()
}
pub fn rel(&self) -> Option<&AnyRel> {
self.rel.as_ref()
}
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 });
}
if options.live_check && spec.rel.is_none() {
return Err(OpenError::LiveCheckUnsupported { id: spec.id });
}
let want = (spec.endpoint)();
if !endpoint.fits(&want)? {
return Err(OpenError::WrongEndpoint {
id: spec.id,
wanted: want,
got: endpoint.kind(),
});
}
let kinds = kinds_named(needs);
let p = provider_for(spec, m, options.call_bound.is_some(), &kinds);
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 blob = if kinds.contains(&Kind::Blob) {
Some(open_blob(spec.id, endpoint)?)
} else {
None
};
let rel = if kinds.contains(&Kind::Rel) {
Some(open_rel(spec.id, endpoint, options.call_bound).await?)
} else {
None
};
if options.live_check {
let own;
let db: &AnyRel = match &rel {
Some(r) => r,
None => {
own = open_rel(spec.id, endpoint, options.call_bound).await?;
&own
}
};
run_live_check(db)
.await
.map_err(|reason| OpenError::LiveCheck {
id: spec.id,
reason,
})?;
}
let kv_surface = Surface::new(
kv.backend(),
kv.version(),
with_bound(
&surface_for(spec, m, kv.call_bound().is_some()).config,
kv.call_bound().is_some(),
),
);
let mut opened: Vec<(Kind, Surface)> = Vec::new();
if kinds.contains(&Kind::Kv) {
opened.push((Kind::Kv, kv_surface.clone()));
}
if let Some(b) = &blob {
opened.push((
Kind::Blob,
Surface::new(b.backend(), b.version(), b.config().clone()),
));
}
if let Some(r) = &rel {
let dialect = r.dialect().to_string();
opened.push((
Kind::Rel,
Surface::new(
r.backend(),
r.version(),
Config::new().with("dialect", dialect),
),
));
}
let opened_names: Vec<(Kind, String, String)> = opened
.iter()
.map(|(k, sf)| (*k, sf.backend.clone(), sf.version.clone()))
.collect();
let declared = weakest_declared(&opened);
let actual = Provider::new(
spec.id,
opened.into_iter().map(|(_, surface)| surface).collect(),
declared,
p.endpoint().clone(),
);
provider::providers(std::slice::from_ref(&actual), needs, m)
.map_err(|u| OpenError::Unmet(explain_unmet(u, &opened_names, m)))?;
Ok(Handle {
id: spec.id,
kv,
blob,
rel,
})
}
fn open_blob(id: &str, endpoint: &Endpoint) -> Result<AnyBlob, OpenError> {
let open = |e: &dyn fmt::Display| OpenError::Open(e.to_string());
let inner = match (id, endpoint) {
("memory", _) => OpendalBlob::memory().map_err(|e| open(&e))?,
("fs", Endpoint::Path(root)) => {
let mut scratch = root.clone().into_os_string();
scratch.push(".persistant-atomic");
OpendalBlob::fs(root, Some(&PathBuf::from(scratch))).map_err(|e| open(&e))?
}
_ => return Err(OpenError::Open(format!("no blob opener for `{id}`"))),
};
Ok(AnyBlob { inner })
}
#[allow(
deprecated,
reason = "`Endpoint::Url` is deprecated (0.17.0); the registry still accepts it until it is removed"
)]
async fn open_rel(
id: &str,
endpoint: &Endpoint,
bound: Option<Duration>,
) -> Result<AnyRel, OpenError> {
#[cfg(any(
feature = "registry-sqlite",
feature = "registry-postgres",
feature = "registry-mysql"
))]
let open = |e: &dyn fmt::Display| OpenError::Open(e.to_string());
match (id, endpoint) {
#[cfg(feature = "registry-sqlite")]
("sqlite" | "sqlite-full" | "sqlite-secure", Endpoint::Path(file)) => {
let db = if id == "sqlite-full" {
SqliteBackend::open_durable(file).await
} else if id == "sqlite-secure" {
SqliteBackend::open_secure(file).await
} else {
SqliteBackend::open(file).await
}
.map_err(|e| open(&e))?;
Ok(match bound {
None => AnyRel::Sqlite(db),
Some(b) => AnyRel::SqliteBounded(Bounded::new(db, b)),
})
}
#[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))?;
Ok(match bound {
None => AnyRel::Postgres(db),
Some(b) => AnyRel::PostgresBounded(Bounded::new(db, b)),
})
}
#[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))?;
Ok(match bound {
None => AnyRel::Mysql(db),
Some(b) => AnyRel::MysqlBounded(Bounded::new(db, b)),
})
}
_ => {
let _ = (endpoint, bound);
Err(OpenError::Open(format!("no relational opener for `{id}`")))
}
}
}
#[allow(
deprecated,
reason = "`Endpoint::Url` is deprecated (0.17.0); the registry still accepts it until it is removed"
)]
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))?;
std::fs::create_dir_all(&scratch).map_err(|e| open(&e))?;
let kv = KvOnBlob::new(OpendalBlob::fs(root, Some(&scratch)).map_err(|e| open(&e))?);
kv.migrate_raw_layout().await.map_err(|e| open(&e))?;
Ok(AnyKv::Blob(kv))
}
#[cfg(feature = "registry-sqlite")]
("sqlite" | "sqlite-full" | "sqlite-secure", Endpoint::Path(file)) => {
let durable = id == "sqlite-full";
let secure = id == "sqlite-secure";
let connect = || async {
if durable {
SqliteBackend::open_durable(file).await
} else if secure {
SqliteBackend::open_secure(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))?,
))
}
}
}
_ => {
let _ = bound;
Err(OpenError::Open(format!("no opener for `{id}`")))
}
}
}
fn explain_unmet(mut u: Unmet, opened: &[(Kind, String, String)], m: &Matrix) -> Unmet {
for p in &mut u.providers {
let mut reasons: Vec<(CapabilityId, String)> = Vec::new();
for (id, _) in &p.missing {
let Some((_, backend, version)) =
opened.iter().find(|(k, _, _)| *k == kind_of(id.as_str()))
else {
continue;
};
let recorded: Vec<&str> = m
.rows()
.iter()
.filter(|r| r.backend == *backend)
.map(|r| r.version.as_str())
.collect();
if recorded.contains(&version.as_str()) {
continue;
}
let why = match nearest_recorded(&recorded, version) {
Some(near) => format!("no row for {version}; nearest recorded {near}"),
None => format!("no row for {version}; none recorded"),
};
reasons.push((id.clone(), why));
}
for (id, why) in reasons {
match p.unverified.iter_mut().find(|(i, _)| *i == id) {
Some(slot) => slot.1 = why,
None => p.unverified.push((id, why)),
}
}
}
u
}
fn version_key(v: &str) -> Vec<u64> {
v.split(|c: char| !c.is_ascii_digit())
.filter(|s| !s.is_empty())
.map(|s| s.parse().unwrap_or(u64::MAX))
.collect()
}
fn nearest_recorded(recorded: &[&str], opened: &str) -> Option<String> {
let want = version_key(opened);
let mut sorted: Vec<&str> = recorded.to_vec();
sorted.sort_by_key(|v| version_key(v));
sorted.dedup();
sorted
.iter()
.rev()
.find(|v| version_key(v) <= want)
.or_else(|| sorted.first())
.map(|v| (*v).to_string())
}
#[cfg(all(test, feature = "registry-sqlite"))]
mod version_key_tests {
use super::*;
#[test]
fn a_newer_version_than_any_row_is_refused_and_named() {
let m = Matrix::parse(include_str!("../matrix/sqlx-sqlite.tsv")).unwrap();
let backend = "kv-on-relational:sqlite";
let need = ProviderNeeds::new(
vec![CapabilityId::new("kv.get").unwrap()],
Durability::Volatile,
);
let facts = Config::new().with("dialect", "sqlite");
let recorded_version = m
.rows()
.iter()
.find(|r| r.backend == backend)
.unwrap()
.version
.clone();
let try_version = |v: &str| {
let p = Provider::new(
"sqlite",
vec![Surface::new(backend, v, facts.clone())],
None,
EndpointSpec::None,
);
provider::providers(std::slice::from_ref(&p), &need, &m)
.map(|_| ())
.map_err(|u| {
let opened = [(Kind::Kv, backend.to_string(), v.to_string())];
explain_unmet(u, &opened, &m).to_string()
})
};
assert_eq!(try_version(&recorded_version), Ok(()));
let newest = m
.rows()
.iter()
.filter(|r| r.backend == backend)
.map(|r| r.version.as_str())
.max_by_key(|v| version_key(v))
.unwrap()
.to_string();
let text = try_version("0.18+3.999.0").unwrap_err();
assert!(
text.contains(&format!(
"no row for 0.18+3.999.0; nearest recorded {newest}"
)),
"{text}"
);
assert!(text.contains("kv.get unverified("), "{text}");
assert!(text.contains("[sqlite:"), "{text}");
}
#[test]
fn nearest_recorded_picks_the_newest_not_newer_else_the_oldest() {
let r = ["0.18+3.51.3", "0.18+3.54.1", "0.18+3.9.0"];
assert_eq!(
nearest_recorded(&r, "0.18+3.52.0").as_deref(),
Some("0.18+3.51.3")
);
assert_eq!(
nearest_recorded(&r, "0.18+3.60.0").as_deref(),
Some("0.18+3.54.1")
);
assert_eq!(
nearest_recorded(&r, "0.18+3.1.0").as_deref(),
Some("0.18+3.9.0"),
"all newer: the oldest"
);
assert_eq!(nearest_recorded(&[], "1"), None);
}
}