Add a versioned backend catalog and YAML deployment configuration

This commit is contained in:
2026-11-30 17:11:03 +08:00
parent c270adbab4
commit 7982fffcda
22 changed files with 924 additions and 223 deletions
+169
View File
@@ -0,0 +1,169 @@
use std::{fmt, path::Path};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::ConfigError;
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SqlDriver {
#[default]
Sqlite,
Postgres,
Mysql,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
/// A database address. Debug output includes the full value, which may contain credentials.
#[derive(Clone, Deserialize, Serialize)]
#[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 {
fmt::Debug::fmt(&self.0, formatter)
}
}
impl Address {
pub fn connection_string(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Cluster {
pub driver: SqlDriver,
pub primary: Address,
#[serde(default)]
pub replicas: Vec<Address>,
#[serde(default)]
pub tls: Tls,
#[serde(default = "default_pool_size")]
pub max_connections: u32,
}
const DEFAULT_POOL_SIZE: u32 = 5;
fn default_pool_size() -> u32 {
DEFAULT_POOL_SIZE
}
#[derive(Clone, Debug)]
pub struct ResolvedSql {
pub deployment: String,
pub cluster: Option<String>,
pub driver: SqlDriver,
pub primary: Address,
pub replicas: Vec<Address>,
pub read_only: bool,
pub max_connections: u32,
}
impl Cluster {
pub(crate) fn resolve(
&self,
deployment: &str,
name: Option<&str>,
read_only: bool,
) -> Result<ResolvedSql, ConfigError> {
if self.max_connections == 0 {
return Err(ConfigError::PoolSize);
}
if self.driver == SqlDriver::Sqlite && !self.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
}
let primary = resolve_address(self, &self.primary, read_only)?;
let replicas = self
.replicas
.iter()
.map(|address| resolve_address(self, address, true))
.collect::<Result<_, _>>()?;
Ok(ResolvedSql {
deployment: deployment.into(),
cluster: name.map(str::to_owned),
driver: self.driver,
primary,
replicas,
read_only,
max_connections: self.max_connections,
})
}
}
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 {
SqlDriver::Sqlite => return sqlite_url(address, read_only),
SqlDriver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
SqlDriver::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}")))
}