Add a versioned backend catalog and YAML deployment configuration
This commit is contained in:
+101
-159
@@ -1,78 +1,35 @@
|
||||
use std::{collections::BTreeMap, fmt, path::Path};
|
||||
//! Runtime configuration and named backend resources for Bedrock.
|
||||
|
||||
use serde::Deserialize;
|
||||
mod catalog;
|
||||
mod driver;
|
||||
mod format;
|
||||
mod object_storage;
|
||||
mod sql;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
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,
|
||||
}
|
||||
pub use catalog::{Resource, ResourceRef};
|
||||
pub use driver::*;
|
||||
pub use format::{ConfigFormat, FormatError, ImportFormat};
|
||||
pub use object_storage::ObjectStorage;
|
||||
pub use sql::{Address, Cluster, ResolvedSql, SqlDriver, Tls};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Tls {
|
||||
#[default]
|
||||
VerifyFull,
|
||||
Disabled,
|
||||
}
|
||||
pub const DOCUMENTS: &str = "documents";
|
||||
|
||||
/// A database address. Debug output includes the full value, which 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 {
|
||||
fmt::Debug::fmt(&self.0, formatter)
|
||||
}
|
||||
}
|
||||
|
||||
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)]
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct DeploymentConfig {
|
||||
pub deployment: String,
|
||||
pub config_version: String,
|
||||
/// Legacy shorthand for sql.documents.
|
||||
pub cluster: Option<String>,
|
||||
pub clusters: BTreeMap<String, Cluster>,
|
||||
/// SQL role to named cluster.
|
||||
pub sql: BTreeMap<String, String>,
|
||||
pub object_storage: BTreeMap<String, ObjectStorage>,
|
||||
pub read_only: bool,
|
||||
pub sqlite_path: Address,
|
||||
}
|
||||
@@ -81,23 +38,30 @@ impl Default for DeploymentConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
deployment: "default".into(),
|
||||
config_version: "local".into(),
|
||||
cluster: None,
|
||||
clusters: BTreeMap::new(),
|
||||
sql: BTreeMap::new(),
|
||||
object_storage: BTreeMap::new(),
|
||||
read_only: false,
|
||||
sqlite_path: "bedrock.sqlite3".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// A validated startup snapshot. The version identifies the configuration release.
|
||||
#[derive(Clone, 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,
|
||||
pub config_version: String,
|
||||
pub sql: BTreeMap<String, ResolvedSql>,
|
||||
pub object_storage: BTreeMap<String, ObjectStorage>,
|
||||
}
|
||||
|
||||
impl ResolvedDeployment {
|
||||
pub fn documents(&self) -> Option<&ResolvedSql> {
|
||||
self.sql.get(DOCUMENTS)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -108,6 +72,18 @@ pub enum ConfigError {
|
||||
UnknownCluster,
|
||||
#[error("a cluster must be selected when clusters are configured")]
|
||||
ClusterRequired,
|
||||
#[error("legacy cluster and sql.documents refer to different resources")]
|
||||
ConflictingDocuments,
|
||||
#[error("invalid object storage configuration")]
|
||||
ObjectStorage,
|
||||
#[error("resource already exists")]
|
||||
DuplicateResource,
|
||||
#[error("resource does not exist")]
|
||||
MissingResource,
|
||||
#[error("resource is referenced by a SQL binding")]
|
||||
ResourceInUse,
|
||||
#[error("a resource update must preserve its category")]
|
||||
ResourceCategory,
|
||||
#[error("the database pool size must be greater than zero")]
|
||||
PoolSize,
|
||||
#[error("SQLite does not support a replica list")]
|
||||
@@ -121,46 +97,68 @@ pub enum ConfigError {
|
||||
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)?
|
||||
validate_name(&self.config_version, "config version")?;
|
||||
let mut targets = BTreeMap::new();
|
||||
for (name, cluster) in &self.clusters {
|
||||
validate_name(name, "cluster")?;
|
||||
targets.insert(
|
||||
name.as_str(),
|
||||
cluster.resolve(&self.deployment, Some(name), self.read_only)?,
|
||||
);
|
||||
}
|
||||
for (name, store) in &self.object_storage {
|
||||
validate_name(name, "object store")?;
|
||||
if self.clusters.contains_key(name) {
|
||||
return Err(ConfigError::DuplicateResource);
|
||||
}
|
||||
None if self.clusters.is_empty() => &local,
|
||||
None => return Err(ConfigError::ClusterRequired),
|
||||
};
|
||||
if cluster.max_connections == 0 {
|
||||
return Err(ConfigError::PoolSize);
|
||||
store.validate()?;
|
||||
}
|
||||
if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() {
|
||||
return Err(ConfigError::SqliteReplicas);
|
||||
|
||||
let mut sql = BTreeMap::new();
|
||||
for (role, target) in &self.sql {
|
||||
validate_name(role, "SQL role")?;
|
||||
validate_name(target, "cluster")?;
|
||||
let settings = targets
|
||||
.get(target.as_str())
|
||||
.ok_or(ConfigError::UnknownCluster)?;
|
||||
sql.insert(role.clone(), settings.clone());
|
||||
}
|
||||
if let Some(name) = &self.cluster {
|
||||
validate_name(name, "cluster")?;
|
||||
if self.sql.get(DOCUMENTS).is_some_and(|target| target != name) {
|
||||
return Err(ConfigError::ConflictingDocuments);
|
||||
}
|
||||
let settings = targets
|
||||
.get(name.as_str())
|
||||
.ok_or(ConfigError::UnknownCluster)?;
|
||||
sql.insert(DOCUMENTS.into(), settings.clone());
|
||||
}
|
||||
if sql.is_empty() {
|
||||
if !targets.is_empty() {
|
||||
return Err(ConfigError::ClusterRequired);
|
||||
}
|
||||
let local = Cluster {
|
||||
driver: SqlDriver::Sqlite,
|
||||
primary: self.sqlite_path.clone(),
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 1,
|
||||
};
|
||||
sql.insert(
|
||||
DOCUMENTS.into(),
|
||||
local.resolve(&self.deployment, None, self.read_only)?,
|
||||
);
|
||||
}
|
||||
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,
|
||||
config_version: self.config_version.clone(),
|
||||
sql,
|
||||
object_storage: self.object_storage.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
|
||||
pub(crate) fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
|
||||
if value.is_empty()
|
||||
|| value.len() > 128
|
||||
|| !value
|
||||
@@ -171,59 +169,3 @@ fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
|
||||
}
|
||||
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}")))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user