use std::{fmt, path::Path}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ConfigError, driver::SqlDriver}; #[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 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 } } /// A SQL target with a primary connection and optional read replicas. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct SqlCluster { pub driver: SqlDriver, pub primary: Address, #[serde(default)] pub replicas: Vec
, #[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, pub driver: SqlDriver, pub primary: Address, pub replicas: Vec
, pub read_only: bool, pub max_connections: u32, } impl SqlCluster { pub(crate) fn local(path: Address) -> Self { Self { driver: SqlDriver::Sqlite, primary: path, replicas: vec![], tls: Tls::Disabled, max_connections: 1, } } pub(crate) fn resolve( &self, deployment: &str, name: Option<&str>, read_only: bool, ) -> Result { 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::>()?; 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: &SqlCluster, address: &Address, read_only: bool, ) -> Result { 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 { 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}"))) }