Implement Bedrock SQL persistence backends
Bedrock SQL storage / sql (push) Successful in 23m11s

This commit is contained in:
2026-11-30 00:23:48 +08:00
parent 0c34703ec7
commit 807a02e081
20 changed files with 3480 additions and 3 deletions
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "clusters"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
serde.workspace = true
thiserror.workspace = true
url.workspace = true
+272
View File
@@ -0,0 +1,272 @@
use std::{collections::BTreeMap, fmt, path::Path};
use serde::Deserialize;
use thiserror::Error;
use url::Url;
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Driver {
#[default]
Sqlite,
Postgres,
Mysql,
}
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
/// A database address may contain credentials.
#[derive(Clone, Deserialize)]
#[serde(transparent)]
pub struct Address(String);
impl From<&str> for Address {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for Address {
fn from(value: String) -> Self {
Self(value)
}
}
impl fmt::Debug for Address {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Address([redacted])")
}
}
impl Address {
pub fn connection_string(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Cluster {
pub driver: Driver,
pub primary: Address,
#[serde(default)]
pub replicas: Vec<Address>,
#[serde(default)]
pub tls: Tls,
#[serde(default = "default_pool_size")]
pub max_connections: u32,
}
const fn default_pool_size() -> u32 {
5
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DeploymentConfig {
pub deployment: String,
pub cluster: Option<String>,
pub clusters: BTreeMap<String, Cluster>,
pub read_only: bool,
pub sqlite_path: Address,
}
impl Default for DeploymentConfig {
fn default() -> Self {
Self {
deployment: "default".into(),
cluster: None,
clusters: BTreeMap::new(),
read_only: false,
sqlite_path: "bedrock.sqlite3".into(),
}
}
}
#[derive(Debug)]
pub struct ResolvedDeployment {
pub deployment: String,
pub cluster: Option<String>,
pub driver: Driver,
pub primary: Address,
pub replicas: Vec<Address>,
pub read_only: bool,
pub max_connections: u32,
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("invalid {0} name")]
Name(&'static str),
#[error("the selected database cluster is not configured")]
UnknownCluster,
#[error("a cluster must be selected when clusters are configured")]
ClusterRequired,
#[error("the database pool size must be greater than zero")]
PoolSize,
#[error("SQLite does not support a replica list")]
SqliteReplicas,
#[error("invalid SQLite file path")]
SqlitePath,
#[error("invalid {0} database URL")]
Url(&'static str),
}
impl DeploymentConfig {
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
validate_name(&self.deployment, "deployment")?;
let local = Cluster {
driver: Driver::Sqlite,
primary: self.sqlite_path.clone(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
};
let cluster = match &self.cluster {
Some(name) => {
validate_name(name, "cluster")?;
self.clusters.get(name).ok_or(ConfigError::UnknownCluster)?
}
None if self.clusters.is_empty() => &local,
None => return Err(ConfigError::ClusterRequired),
};
if cluster.max_connections == 0 {
return Err(ConfigError::PoolSize);
}
if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
}
let primary = resolve_address(cluster, &cluster.primary, self.read_only)?;
let replicas = cluster
.replicas
.iter()
.map(|address| resolve_address(cluster, address, true))
.collect::<Result<_, _>>()?;
Ok(ResolvedDeployment {
deployment: self.deployment.clone(),
cluster: self.cluster.clone(),
driver: cluster.driver,
primary,
replicas,
read_only: self.read_only,
max_connections: cluster.max_connections,
})
}
}
fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
if value.is_empty()
|| value.len() > 128
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
{
return Err(ConfigError::Name(kind));
}
Ok(())
}
fn resolve_address(
cluster: &Cluster,
address: &Address,
read_only: bool,
) -> Result<Address, ConfigError> {
let address = address.connection_string();
let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver {
Driver::Sqlite => return sqlite_url(address, read_only),
Driver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
Driver::Mysql => ("mysql", "ssl-mode", "VERIFY_IDENTITY", "DISABLED"),
};
let mut url = Url::parse(address).map_err(|_| ConfigError::Url(driver))?;
let compatible = url.scheme() == driver || driver == "postgres" && url.scheme() == "postgresql";
if !compatible
|| url.host_str().is_none()
|| url.username().is_empty()
|| url.path().trim_matches('/').is_empty()
|| url.fragment().is_some()
|| url.query_pairs().any(|(key, _)| {
matches!(
key.as_ref(),
"sslmode"
| "ssl-mode"
| "host"
| "hostaddr"
| "port"
| "socket"
| "dbname"
| "options"
)
})
{
return Err(ConfigError::Url(driver));
}
let tls_mode = match cluster.tls {
Tls::VerifyFull => tls_enabled,
Tls::Disabled => tls_disabled,
};
url.query_pairs_mut().append_pair(tls_key, tls_mode);
Ok(Address(url.into()))
}
fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
if path.is_empty() || path == ":memory:" || path.contains('\0') {
return Err(ConfigError::SqlitePath);
}
let absolute = std::path::absolute(Path::new(path)).map_err(|_| ConfigError::SqlitePath)?;
let file = Url::from_file_path(absolute).map_err(|_| ConfigError::SqlitePath)?;
let file = file
.as_str()
.strip_prefix("file:")
.ok_or(ConfigError::SqlitePath)?;
let mode = if read_only { "ro" } else { "rwc" };
Ok(Address(format!("sqlite:{file}?mode={mode}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn named_cluster_requires_matching_addresses_and_redacts_credentials() {
let mut config = DeploymentConfig {
cluster: Some("regional".into()),
clusters: BTreeMap::from([(
"regional".into(),
Cluster {
driver: Driver::Postgres,
primary: "postgres://user:secret@primary/bedrock".into(),
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
tls: Tls::VerifyFull,
max_connections: 5,
},
)]),
..DeploymentConfig::default()
};
let resolved = config.resolve().unwrap();
assert!(
resolved
.primary
.connection_string()
.ends_with("sslmode=verify-full")
);
assert!(
resolved.replicas[0]
.connection_string()
.ends_with("sslmode=verify-full")
);
assert!(!format!("{resolved:?}").contains("secret"));
config.clusters.get_mut("regional").unwrap().replicas[0] =
"mysql://user:secret@replica/bedrock".into();
assert!(matches!(
config.resolve(),
Err(ConfigError::Url("postgres"))
));
}
}