Add a versioned backend catalog and YAML deployment configuration
This commit is contained in:
@@ -6,5 +6,8 @@ rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde-saphyr.workspace = true
|
||||
toml.workspace = true
|
||||
thiserror.workspace = true
|
||||
url.workspace = true
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Cluster, ConfigError, DeploymentConfig, Driver, ObjectStorage, validate_name};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Resource {
|
||||
Sql(Cluster),
|
||||
ObjectStore(ObjectStorage),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ResourceRef<'a> {
|
||||
Sql(&'a Cluster),
|
||||
ObjectStore(&'a ObjectStorage),
|
||||
}
|
||||
|
||||
impl ResourceRef<'_> {
|
||||
pub fn driver(self) -> Driver {
|
||||
match self {
|
||||
Self::Sql(cluster) => Driver::Sql(cluster.driver),
|
||||
Self::ObjectStore(store) => Driver::ObjectStore(store.driver),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DeploymentConfig {
|
||||
pub fn resource(&self, name: &str) -> Option<ResourceRef<'_>> {
|
||||
self.clusters
|
||||
.get(name)
|
||||
.map(ResourceRef::Sql)
|
||||
.or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore))
|
||||
}
|
||||
|
||||
pub fn resources(&self) -> impl Iterator<Item = (&str, ResourceRef<'_>)> {
|
||||
self.clusters
|
||||
.iter()
|
||||
.map(|(name, value)| (name.as_str(), ResourceRef::Sql(value)))
|
||||
.chain(
|
||||
self.object_storage
|
||||
.iter()
|
||||
.map(|(name, value)| (name.as_str(), ResourceRef::ObjectStore(value))),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
|
||||
if self.resource(&name).is_some() {
|
||||
return Err(ConfigError::DuplicateResource);
|
||||
}
|
||||
self.store_resource(name, resource)
|
||||
}
|
||||
|
||||
pub fn update_resource(&mut self, name: &str, resource: Resource) -> Result<(), ConfigError> {
|
||||
match (self.resource(name), &resource) {
|
||||
(None, _) => return Err(ConfigError::MissingResource),
|
||||
(Some(ResourceRef::Sql(_)), Resource::Sql(_))
|
||||
| (Some(ResourceRef::ObjectStore(_)), Resource::ObjectStore(_)) => {}
|
||||
_ => return Err(ConfigError::ResourceCategory),
|
||||
}
|
||||
self.store_resource(name.to_owned(), resource)
|
||||
}
|
||||
|
||||
pub fn remove_resource(&mut self, name: &str) -> Result<Resource, ConfigError> {
|
||||
if self.cluster.as_deref() == Some(name) || self.sql.values().any(|target| target == name) {
|
||||
return Err(ConfigError::ResourceInUse);
|
||||
}
|
||||
self.clusters
|
||||
.remove(name)
|
||||
.map(Resource::Sql)
|
||||
.or_else(|| self.object_storage.remove(name).map(Resource::ObjectStore))
|
||||
.ok_or(ConfigError::MissingResource)
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
|
||||
validate_name(&name, "resource")?;
|
||||
match resource {
|
||||
Resource::Sql(cluster) => {
|
||||
cluster.resolve(&self.deployment, Some(&name), self.read_only)?;
|
||||
self.clusters.insert(name, cluster);
|
||||
}
|
||||
Resource::ObjectStore(store) => {
|
||||
store.validate()?;
|
||||
self.object_storage.insert(name, store);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::SqlDriver;
|
||||
|
||||
/// Backend taxonomy. Configuration currently enables SQL and object storage.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Driver {
|
||||
Sql(SqlDriver),
|
||||
ObjectStore(ObjectStoreDriver),
|
||||
// Reserved for future adapters.
|
||||
Cache(CacheDriver),
|
||||
Search(SearchDriver),
|
||||
EventStream(EventStreamDriver),
|
||||
BatchCompute(BatchComputeDriver),
|
||||
OnlineService(OnlineServiceKind),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ObjectStoreDriver {
|
||||
S3,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CacheDriver {
|
||||
Redis,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SearchDriver {
|
||||
OpenSearch,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum EventStreamDriver {
|
||||
Kafka,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum BatchComputeDriver {
|
||||
Spark,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum OnlineServiceKind {
|
||||
Recommendation,
|
||||
Retrieval,
|
||||
Ranking,
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{ConfigError, DeploymentConfig, Resource};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ConfigFormat {
|
||||
Yaml,
|
||||
Toml,
|
||||
/// Compatibility with previously published deployment files.
|
||||
Json,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ImportFormat {
|
||||
Catalog(ConfigFormat),
|
||||
/// The bedrock_resources output of terraform output -json.
|
||||
TerraformOutputs,
|
||||
/// A ConfigMap carrying a catalog in data["bedrock-resources.yaml"].
|
||||
KubernetesConfigMap,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum FormatError {
|
||||
#[error("configuration filename must end in .yaml, .yml, .toml or .json")]
|
||||
FileExtension,
|
||||
#[error("could not read the deployment configuration: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
// Parser errors may quote connection strings or credentials.
|
||||
#[error("invalid {0} configuration document")]
|
||||
Parse(&'static str),
|
||||
#[error("could not serialize the deployment configuration as YAML")]
|
||||
Serialize,
|
||||
#[error("import does not contain a Bedrock resource catalog")]
|
||||
MissingCatalog,
|
||||
#[error("publishable deployment configuration requires a valid catalog: {0}")]
|
||||
Config(#[from] ConfigError),
|
||||
}
|
||||
|
||||
impl ConfigFormat {
|
||||
fn parse<T: DeserializeOwned>(self, input: &str) -> Result<T, FormatError> {
|
||||
match self {
|
||||
Self::Yaml => serde_saphyr::from_str(input).map_err(|_| FormatError::Parse("YAML")),
|
||||
Self::Toml => toml::from_str(input).map_err(|_| FormatError::Parse("TOML")),
|
||||
Self::Json => serde_json::from_str(input).map_err(|_| FormatError::Parse("JSON")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DeploymentConfig {
|
||||
pub fn parse(input: &str, format: ConfigFormat) -> Result<Self, FormatError> {
|
||||
format.parse(input)
|
||||
}
|
||||
|
||||
pub fn load(path: impl AsRef<Path>) -> Result<Self, FormatError> {
|
||||
let path = path.as_ref();
|
||||
let format = match path.extension().and_then(|value| value.to_str()) {
|
||||
Some("yaml" | "yml") => ConfigFormat::Yaml,
|
||||
Some("toml") => ConfigFormat::Toml,
|
||||
Some("json") => ConfigFormat::Json,
|
||||
_ => return Err(FormatError::FileExtension),
|
||||
};
|
||||
Self::parse(&std::fs::read_to_string(path)?, format)
|
||||
}
|
||||
|
||||
/// Serializes the configuration, including any credentials in connection strings.
|
||||
pub fn to_yaml(&self) -> Result<String, FormatError> {
|
||||
self.resolve()?;
|
||||
serde_saphyr::to_string(self).map_err(|_| FormatError::Serialize)
|
||||
}
|
||||
|
||||
/// Imports an inventory atomically. Deployment roles are assigned separately.
|
||||
pub fn import_resources(
|
||||
&mut self,
|
||||
input: &str,
|
||||
format: ImportFormat,
|
||||
) -> Result<(), FormatError> {
|
||||
let resources: BTreeMap<String, Resource> = match format {
|
||||
ImportFormat::Catalog(format) => format.parse(input)?,
|
||||
ImportFormat::TerraformOutputs => {
|
||||
let exports: TerraformOutputs = ConfigFormat::Json.parse(input)?;
|
||||
exports
|
||||
.bedrock_resources
|
||||
.ok_or(FormatError::MissingCatalog)?
|
||||
.value
|
||||
}
|
||||
ImportFormat::KubernetesConfigMap => {
|
||||
let manifest: ConfigMap = ConfigFormat::Yaml.parse(input)?;
|
||||
if manifest.kind != "ConfigMap" || manifest.api_version != "v1" {
|
||||
return Err(FormatError::MissingCatalog);
|
||||
}
|
||||
let catalog = manifest
|
||||
.data
|
||||
.get("bedrock-resources.yaml")
|
||||
.ok_or(FormatError::MissingCatalog)?;
|
||||
ConfigFormat::Yaml.parse(catalog)?
|
||||
}
|
||||
};
|
||||
let mut candidate = self.clone();
|
||||
for (name, resource) in resources {
|
||||
candidate.insert_resource(name, resource)?;
|
||||
}
|
||||
*self = candidate;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TerraformOutputs {
|
||||
bedrock_resources: Option<TerraformOutput>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TerraformOutput {
|
||||
value: BTreeMap<String, Resource>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ConfigMap {
|
||||
api_version: String,
|
||||
kind: String,
|
||||
data: BTreeMap<String, String>,
|
||||
}
|
||||
+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}")))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::{ConfigError, ObjectStoreDriver};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ObjectStorage {
|
||||
pub driver: ObjectStoreDriver,
|
||||
pub bucket: String,
|
||||
pub region: String,
|
||||
pub endpoint: Option<String>,
|
||||
}
|
||||
|
||||
impl ObjectStorage {
|
||||
pub(crate) fn validate(&self) -> Result<(), ConfigError> {
|
||||
if self.bucket.trim().is_empty() || self.region.trim().is_empty() {
|
||||
return Err(ConfigError::ObjectStorage);
|
||||
}
|
||||
if let Some(endpoint) = &self.endpoint {
|
||||
let url = Url::parse(endpoint).map_err(|_| ConfigError::ObjectStorage)?;
|
||||
if !matches!(url.scheme(), "http" | "https")
|
||||
|| url.host_str().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.query().is_some()
|
||||
|| url.fragment().is_some()
|
||||
{
|
||||
return Err(ConfigError::ObjectStorage);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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}")))
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver, Tls};
|
||||
|
||||
#[test]
|
||||
fn address_debug_formats_the_inner_string() {
|
||||
@@ -15,7 +15,7 @@ fn named_cluster_requires_matching_addresses() {
|
||||
clusters: BTreeMap::from([(
|
||||
"regional".into(),
|
||||
Cluster {
|
||||
driver: Driver::Postgres,
|
||||
driver: SqlDriver::Postgres,
|
||||
primary: "postgres://user:secret@primary/bedrock".into(),
|
||||
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
|
||||
tls: Tls::VerifyFull,
|
||||
@@ -25,6 +25,7 @@ fn named_cluster_requires_matching_addresses() {
|
||||
..DeploymentConfig::default()
|
||||
};
|
||||
let resolved = config.resolve().unwrap();
|
||||
let resolved = resolved.documents().unwrap();
|
||||
assert!(
|
||||
resolved
|
||||
.primary
|
||||
@@ -43,3 +44,82 @@ fn named_cluster_requires_matching_addresses() {
|
||||
Err(ConfigError::Url("postgres"))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_named_connections_and_round_trips_yaml() {
|
||||
use clusters::ConfigFormat;
|
||||
|
||||
let config = DeploymentConfig::parse(
|
||||
include_str!("../../../deploy/multi-storage.yaml"),
|
||||
ConfigFormat::Yaml,
|
||||
)
|
||||
.unwrap();
|
||||
let snapshot = config.resolve().unwrap();
|
||||
assert_eq!(snapshot.config_version, "example-1");
|
||||
assert_eq!(snapshot.documents().unwrap().driver, SqlDriver::Postgres);
|
||||
assert_eq!(snapshot.sql["legacy"].driver, SqlDriver::Mysql);
|
||||
assert_eq!(
|
||||
snapshot.object_storage["attachments"].bucket,
|
||||
"bedrock-attachments"
|
||||
);
|
||||
assert_eq!(snapshot.documents().unwrap().max_connections, 5);
|
||||
|
||||
let serialized = config.to_yaml().unwrap();
|
||||
let roundtrip = DeploymentConfig::parse(&serialized, ConfigFormat::Yaml)
|
||||
.unwrap()
|
||||
.resolve()
|
||||
.unwrap();
|
||||
assert_eq!(roundtrip.sql["legacy"].driver, SqlDriver::Mysql);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_catalog_atomically_and_preserves_role_references() {
|
||||
use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver, Resource};
|
||||
|
||||
let mut config =
|
||||
DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap();
|
||||
config
|
||||
.import_resources(
|
||||
include_str!("../../../deploy/kubernetes-catalog.yaml"),
|
||||
ImportFormat::KubernetesConfigMap,
|
||||
)
|
||||
.unwrap();
|
||||
config.sql.insert("documents".into(), "pg-main".into());
|
||||
|
||||
let before = config.resource("attachments").unwrap().driver();
|
||||
assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3));
|
||||
assert!(matches!(
|
||||
config.remove_resource("pg-main"),
|
||||
Err(ConfigError::ResourceInUse)
|
||||
));
|
||||
|
||||
let inventory = r#"{
|
||||
"bedrock_resources": {
|
||||
"value": {
|
||||
"another-bucket": {"kind":"object_store","driver":"s3","bucket":"other","region":"us-east-1"},
|
||||
"attachments": {"kind":"object_store","driver":"s3","bucket":"duplicate","region":"us-east-1"}
|
||||
}
|
||||
}
|
||||
}"#;
|
||||
assert!(
|
||||
config
|
||||
.import_resources(inventory, ImportFormat::TerraformOutputs)
|
||||
.is_err()
|
||||
);
|
||||
assert!(config.resource("another-bucket").is_none());
|
||||
let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else {
|
||||
panic!("expected S3 configuration");
|
||||
};
|
||||
updated.bucket = "updated".into();
|
||||
config
|
||||
.insert_resource("attachments".into(), Resource::ObjectStore(updated.clone()))
|
||||
.unwrap();
|
||||
updated.bucket = "replaced".into();
|
||||
config
|
||||
.update_resource("attachments", Resource::ObjectStore(updated))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
config.resolve().unwrap().object_storage["attachments"].bucket,
|
||||
"replaced"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment};
|
||||
use clusters::{Address, ConfigError, DeploymentConfig, ResolvedSql, SqlDriver as Driver};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
@@ -16,6 +16,8 @@ use crate::{
|
||||
pub enum ConnectError {
|
||||
#[error(transparent)]
|
||||
Config(#[from] ConfigError),
|
||||
#[error("the documents SQL role is not configured")]
|
||||
MissingDocuments,
|
||||
#[error(transparent)]
|
||||
Storage(#[from] StorageError),
|
||||
}
|
||||
@@ -100,6 +102,10 @@ pub struct Connection {
|
||||
|
||||
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
|
||||
let config = config.resolve()?;
|
||||
connect_sql(config.documents().ok_or(ConnectError::MissingDocuments)?).await
|
||||
}
|
||||
|
||||
pub async fn connect_sql(config: &ResolvedSql) -> Result<Connection, ConnectError> {
|
||||
let writer = if config.read_only {
|
||||
None
|
||||
} else {
|
||||
@@ -115,7 +121,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
||||
let primary = match &writer {
|
||||
Some(store) => store.reader(),
|
||||
None => {
|
||||
let reader = reader(&config, &config.primary)?;
|
||||
let reader = reader(config, &config.primary)?;
|
||||
reader.revision().await?;
|
||||
reader
|
||||
}
|
||||
@@ -123,7 +129,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
||||
let replicas = config
|
||||
.replicas
|
||||
.iter()
|
||||
.map(|address| reader(&config, address))
|
||||
.map(|address| reader(config, address))
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Connection {
|
||||
driver: config.driver,
|
||||
@@ -134,7 +140,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
||||
})
|
||||
}
|
||||
|
||||
fn reader(config: &ResolvedDeployment, address: &Address) -> Result<Reader, StorageError> {
|
||||
fn reader(config: &ResolvedSql, address: &Address) -> Result<Reader, StorageError> {
|
||||
let url = address.connection_string();
|
||||
let name = &config.deployment;
|
||||
match config.driver {
|
||||
|
||||
@@ -6,9 +6,11 @@ pub mod mysql;
|
||||
pub mod postgres;
|
||||
pub mod sqlite;
|
||||
|
||||
pub use clusters::Driver as Dialect;
|
||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
pub use clusters::SqlDriver as Dialect;
|
||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver as Driver, Tls};
|
||||
pub use common::Error as StorageError;
|
||||
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
|
||||
pub use connection::{ConnectError, Connection, ReadPreference, Reader, Store, connect};
|
||||
pub use connection::{
|
||||
ConnectError, Connection, ReadPreference, Reader, Store, connect, connect_sql,
|
||||
};
|
||||
pub use mysql::{Lease, MySql};
|
||||
|
||||
Reference in New Issue
Block a user