diff --git a/README.md b/README.md index ed26a55..05d2767 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,9 @@ Notion describes sharding online PostgreSQL block data by workspace and feeding Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model. -`clusters` lists SQL connection targets, and `sql` binds roles such as `documents` to those targets. The legacy `cluster` field selects the `documents` role. `object_storage` describes named object stores. The executable logs the configuration version and initializes every configured SQL role at startup. +`resources` lists named backends, each with a `kind` and its own settings. `bindings` maps roles such as `documents` or `attachments` to those resources. The executable logs the configuration version and initializes bound SQL resources at startup. Existing `cluster`, `clusters`, `sql`, `object_storage`, and `sqlite_path` inputs are migrated to this shape when loaded. -The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file. +The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the SQL resource's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. For SQLite, set the resource's `primary` to the file path. Applications use `db::connect` for the documents role or `db::connect_sql` for an explicitly resolved SQL role. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value. diff --git a/crates/clusters/README.md b/crates/clusters/README.md index 1d98bed..48f5a8e 100644 --- a/crates/clusters/README.md +++ b/crates/clusters/README.md @@ -2,29 +2,33 @@ `clusters` 负责读取和校验 Bedrock 的部署配置,并解析出各用途的连接参数。 +`resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。 + ## 模块依赖 -箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。 - -`driver.rs` 集中定义驱动类型,供 SQL 和对象存储配置模块使用。 - -`sql.rs` 定义 `SqlCluster`,描述 SQL 主库和可选读副本。`catalog.rs` 的 `Resource` 统一表示 SQL 和对象存储资源。 +箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。 ```mermaid flowchart LR - lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"] - lib -->|校验对象存储配置| obj["object_storage.rs"] - - sql -->|ConfigError| lib - obj -->|ConfigError| lib - sql -->|SqlDriver| drv["driver.rs"] - obj -->|ObjectStoreDriver| drv - + lib["lib.rs"] -->|解析资源和用途| res["resource.rs"] + lib --> err["error.rs"] cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib - cat -->|统一表示驱动类别| drv - cat -->|编辑 SQL 资源| sql - cat -->|编辑对象存储资源| obj + cat -->|统一校验资源| res + cat --> err + + res -->|SQL 配置和解析| sql["sql.rs"] + res -->|对象存储配置和解析| obj["object_storage.rs"] + res -->|统一驱动类型| drv["driver.rs"] + res --> err + sql -->|SqlDriver| drv + obj -->|ObjectStoreDriver| drv + sql --> err + obj --> err fmt["format.rs"] -->|读取和输出 DeploymentConfig| lib fmt -->|导入时调用 insert_resource| cat + fmt -->|读取资源格式| res + fmt -->|读取旧 SQL 配置| sql + fmt -->|读取旧对象存储配置| obj + fmt --> err ``` diff --git a/crates/clusters/src/catalog.rs b/crates/clusters/src/catalog.rs index 60d9ae4..9528a01 100644 --- a/crates/clusters/src/catalog.rs +++ b/crates/clusters/src/catalog.rs @@ -1,88 +1,48 @@ -use serde::{Deserialize, Serialize}; +//! Named resource lookup and editing. -use crate::{ConfigError, DeploymentConfig, Driver, ObjectStorage, SqlCluster, validate_name}; +use std::mem::discriminant; -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum Resource { - Sql(SqlCluster), - ObjectStore(ObjectStorage), -} - -#[derive(Clone, Copy, Debug)] -pub enum ResourceRef<'a> { - Sql(&'a SqlCluster), - 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), - } - } -} +use crate::{ConfigError, DeploymentConfig, Resource, ResourceRef, validate_name}; impl DeploymentConfig { pub fn resource(&self, name: &str) -> Option> { - self.clusters - .get(name) - .map(ResourceRef::Sql) - .or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore)) + self.resources.get(name) } pub fn resources(&self) -> impl Iterator)> { - self.clusters + self.resources .iter() - .map(|(name, value)| (name.as_str(), ResourceRef::Sql(value))) - .chain( - self.object_storage - .iter() - .map(|(name, value)| (name.as_str(), ResourceRef::ObjectStore(value))), - ) + .map(|(name, resource)| (name.as_str(), resource)) } pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> { - if self.resource(&name).is_some() { + if self.resources.contains_key(&name) { 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), + let previous = self.resource(name).ok_or(ConfigError::MissingResource)?; + if discriminant(previous) != discriminant(&resource) { + return Err(ConfigError::ResourceCategory); } self.store_resource(name.to_owned(), resource) } pub fn remove_resource(&mut self, name: &str) -> Result { - if self.cluster.as_deref() == Some(name) || self.sql.values().any(|target| target == name) { + if self.bindings.values().any(|target| target == name) { return Err(ConfigError::ResourceInUse); } - self.clusters + self.resources .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); - } - } + resource.resolve(&self.deployment, Some(&name), self.read_only)?; + self.resources.insert(name, resource); Ok(()) } } diff --git a/crates/clusters/src/error.rs b/crates/clusters/src/error.rs new file mode 100644 index 0000000..40ab20f --- /dev/null +++ b/crates/clusters/src/error.rs @@ -0,0 +1,35 @@ +use thiserror::Error; + +#[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("legacy cluster and sql.documents refer to different resources")] + ConflictingDocuments, + #[error("binding {role} references unknown resource {target}")] + UnknownBinding { role: String, target: String }, + #[error("conflicting bindings for role {0}")] + ConflictingBinding(String), + #[error("invalid object storage configuration")] + ObjectStorage, + #[error("resource already exists")] + DuplicateResource, + #[error("resource does not exist")] + MissingResource, + #[error("resource is referenced by a deployment 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")] + SqliteReplicas, + #[error("invalid SQLite file path")] + SqlitePath, + #[error("invalid {0} database URL")] + Url(&'static str), +} diff --git a/crates/clusters/src/format.rs b/crates/clusters/src/format.rs index f4adec0..532d158 100644 --- a/crates/clusters/src/format.rs +++ b/crates/clusters/src/format.rs @@ -4,7 +4,9 @@ use serde::Deserialize; use serde::de::DeserializeOwned; use thiserror::Error; -use crate::{ConfigError, DeploymentConfig, Resource}; +use crate::{ + Address, ConfigError, DOCUMENTS, DeploymentConfig, ObjectStorage, Resource, SqlCluster, +}; #[derive(Clone, Copy, Debug)] pub enum ConfigFormat { @@ -52,7 +54,10 @@ impl ConfigFormat { impl DeploymentConfig { pub fn parse(input: &str, format: ConfigFormat) -> Result { - format.parse(input) + format + .parse::(input)? + .try_into() + .map_err(Into::into) } pub fn load(path: impl AsRef) -> Result { @@ -108,6 +113,92 @@ impl DeploymentConfig { } } +// Compatibility for the older, category-specific on-disk layout. Normalize once on load. +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct DeploymentInput { + deployment: Option, + config_version: Option, + resources: BTreeMap, + bindings: BTreeMap, + read_only: bool, + cluster: Option, + clusters: BTreeMap, + sql: BTreeMap, + object_storage: BTreeMap, + sqlite_path: Option
, +} + +impl TryFrom for DeploymentConfig { + type Error = ConfigError; + + fn try_from(input: DeploymentInput) -> Result { + let defaults = Self::default(); + let mut config = Self { + deployment: input.deployment.unwrap_or(defaults.deployment), + config_version: input.config_version.unwrap_or(defaults.config_version), + resources: input.resources, + bindings: input.bindings, + read_only: input.read_only, + }; + let has_canonical_config = !config.resources.is_empty() || !config.bindings.is_empty(); + let has_legacy_sql_targets = !input.clusters.is_empty(); + for (name, resource) in input + .clusters + .into_iter() + .map(|(name, cluster)| (name, Resource::Sql(cluster))) + .chain( + input + .object_storage + .into_iter() + .map(|(name, store)| (name, Resource::ObjectStore(store))), + ) + { + if config.resources.insert(name, resource).is_some() { + return Err(ConfigError::DuplicateResource); + } + } + let mut sql = input.sql; + if let Some(name) = input.cluster { + if sql.get(DOCUMENTS).is_some_and(|target| target != &name) { + return Err(ConfigError::ConflictingDocuments); + } + sql.insert(DOCUMENTS.into(), name); + } + if !has_canonical_config && has_legacy_sql_targets && sql.is_empty() { + return Err(ConfigError::ClusterRequired); + } + for (role, target) in sql { + if !matches!(config.resources.get(&target), Some(Resource::Sql(_))) { + return Err(ConfigError::UnknownCluster); + } + if config + .bindings + .get(&role) + .is_some_and(|existing| existing != &target) + { + return Err(ConfigError::ConflictingBinding(role)); + } + config.bindings.insert(role, target); + } + if !has_canonical_config + && config.bindings.is_empty() + && (input.sqlite_path.is_some() || !config.resources.is_empty()) + { + let mut name = String::from("local"); + while config.resources.contains_key(&name) { + name.push('-'); + } + let local = input + .sqlite_path + .map_or_else(Resource::default_documents, Resource::local_documents); + config.resources.insert(name.clone(), local); + config.bindings.insert(DOCUMENTS.into(), name); + } + Ok(config) + } +} + #[derive(Deserialize)] struct TerraformOutputs { bedrock_resources: Option, diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index f663554..96786cd 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -2,19 +2,21 @@ mod catalog; mod driver; +mod error; mod format; mod object_storage; +mod resource; mod sql; use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use thiserror::Error; -pub use catalog::{Resource, ResourceRef}; pub use driver::*; +pub use error::ConfigError; pub use format::{ConfigFormat, FormatError, ImportFormat}; pub use object_storage::ObjectStorage; +pub use resource::{ResolvedResource, Resource, ResourceRef}; /// Compatibility name for the SQL cluster configuration. pub use sql::SqlCluster as Cluster; pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; @@ -22,19 +24,14 @@ pub use sql::{Address, ResolvedSql, SqlCluster, Tls}; pub const DOCUMENTS: &str = "documents"; #[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(default, deny_unknown_fields)] +#[serde(try_from = "format::DeploymentInput")] pub struct DeploymentConfig { pub deployment: String, pub config_version: String, - /// Legacy shorthand for sql.documents. - pub cluster: Option, - /// Named SQL targets that can be bound to entries in `sql`. - pub clusters: BTreeMap, - /// SQL role to named cluster. - pub sql: BTreeMap, - pub object_storage: BTreeMap, + pub resources: BTreeMap, + /// Role to named resource. + pub bindings: BTreeMap, pub read_only: bool, - pub sqlite_path: Address, } impl Default for DeploymentConfig { @@ -42,12 +39,9 @@ impl Default for DeploymentConfig { Self { deployment: "default".into(), config_version: "local".into(), - cluster: None, - clusters: BTreeMap::new(), - sql: BTreeMap::new(), - object_storage: BTreeMap::new(), + resources: BTreeMap::new(), + bindings: BTreeMap::new(), read_only: false, - sqlite_path: "bedrock.sqlite3".into(), } } } @@ -57,106 +51,62 @@ impl Default for DeploymentConfig { pub struct ResolvedDeployment { pub deployment: String, pub config_version: String, - pub sql: BTreeMap, - pub object_storage: BTreeMap, + resources: BTreeMap, + bindings: BTreeMap, } impl ResolvedDeployment { - pub fn documents(&self) -> Option<&ResolvedSql> { - self.sql.get(DOCUMENTS) + pub fn resource(&self, name: &str) -> Option<&ResolvedResource> { + self.resources.get(name) } -} -#[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("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")] - SqliteReplicas, - #[error("invalid SQLite file path")] - SqlitePath, - #[error("invalid {0} database URL")] - Url(&'static str), + pub fn binding(&self, role: &str) -> Option<&ResolvedResource> { + self.resource(self.bindings.get(role)?) + } + + pub fn bound_resources(&self) -> impl Iterator { + self.bindings + .iter() + .map(|(role, target)| (role.as_str(), &self.resources[target])) + } } impl DeploymentConfig { pub fn resolve(&self) -> Result { validate_name(&self.deployment, "deployment")?; 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)?, + let mut resources = BTreeMap::new(); + let mut bindings = self.bindings.clone(); + for (name, resource) in &self.resources { + validate_name(name, "resource")?; + resources.insert( + name.clone(), + resource.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); - } - store.validate()?; - } - - 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 = SqlCluster { - 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)?, + if resources.is_empty() && bindings.is_empty() { + let default = Resource::default_documents(); + resources.insert( + "local".into(), + default.resolve(&self.deployment, None, self.read_only)?, ); + bindings.insert(DOCUMENTS.into(), "local".into()); + } + for (role, target) in &bindings { + validate_name(role, "role")?; + validate_name(target, "resource")?; + if !resources.contains_key(target) { + return Err(ConfigError::UnknownBinding { + role: role.clone(), + target: target.clone(), + }); + } } Ok(ResolvedDeployment { deployment: self.deployment.clone(), config_version: self.config_version.clone(), - sql, - object_storage: self.object_storage.clone(), + resources, + bindings, }) } } diff --git a/crates/clusters/src/object_storage.rs b/crates/clusters/src/object_storage.rs index 1fc48eb..52d11ca 100644 --- a/crates/clusters/src/object_storage.rs +++ b/crates/clusters/src/object_storage.rs @@ -13,7 +13,7 @@ pub struct ObjectStorage { } impl ObjectStorage { - pub(crate) fn validate(&self) -> Result<(), ConfigError> { + pub(crate) fn resolve(&self) -> Result { if self.bucket.trim().is_empty() || self.region.trim().is_empty() { return Err(ConfigError::ObjectStorage); } @@ -29,6 +29,6 @@ impl ObjectStorage { return Err(ConfigError::ObjectStorage); } } - Ok(()) + Ok(self.clone()) } } diff --git a/crates/clusters/src/resource.rs b/crates/clusters/src/resource.rs new file mode 100644 index 0000000..7ff7d53 --- /dev/null +++ b/crates/clusters/src/resource.rs @@ -0,0 +1,67 @@ +//! Configurations and resolved settings dispatched by resource category. + +use serde::{Deserialize, Serialize}; + +use crate::{Address, ConfigError, Driver, ObjectStorage, ResolvedSql, SqlCluster}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Resource { + Sql(SqlCluster), + ObjectStore(ObjectStorage), +} + +pub type ResourceRef<'a> = &'a Resource; + +impl Resource { + pub fn driver(&self) -> Driver { + match self { + Self::Sql(cluster) => Driver::Sql(cluster.driver), + Self::ObjectStore(store) => Driver::ObjectStore(store.driver), + } + } + + pub(crate) fn default_documents() -> Self { + Self::local_documents("bedrock.sqlite3".into()) + } + + pub(crate) fn local_documents(path: Address) -> Self { + Self::Sql(SqlCluster::local(path)) + } + + pub(crate) fn resolve( + &self, + deployment: &str, + name: Option<&str>, + read_only: bool, + ) -> Result { + match self { + Self::Sql(cluster) => cluster + .resolve(deployment, name, read_only) + .map(ResolvedResource::Sql), + Self::ObjectStore(store) => store.resolve().map(ResolvedResource::ObjectStore), + } + } +} + +#[derive(Clone, Debug)] +pub enum ResolvedResource { + Sql(ResolvedSql), + ObjectStore(ObjectStorage), +} + +impl ResolvedResource { + pub fn as_sql(&self) -> Option<&ResolvedSql> { + match self { + Self::Sql(sql) => Some(sql), + _ => None, + } + } + + pub fn as_object_store(&self) -> Option<&ObjectStorage> { + match self { + Self::ObjectStore(store) => Some(store), + _ => None, + } + } +} diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs index 21e43da..275cecd 100644 --- a/crates/clusters/src/sql.rs +++ b/crates/clusters/src/sql.rs @@ -74,6 +74,16 @@ pub struct ResolvedSql { } 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, diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 45e56ba..9dc2783 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -1,6 +1,8 @@ use std::collections::BTreeMap; -use clusters::{Address, ConfigError, DeploymentConfig, SqlCluster, SqlDriver, Tls}; +use clusters::{ + Address, ConfigError, DOCUMENTS, DeploymentConfig, Resource, SqlCluster, SqlDriver, Tls, +}; #[test] fn address_debug_formats_the_inner_string() { @@ -11,21 +13,21 @@ fn address_debug_formats_the_inner_string() { #[test] fn named_cluster_requires_matching_addresses() { let mut config = DeploymentConfig { - cluster: Some("regional".into()), - clusters: BTreeMap::from([( + bindings: BTreeMap::from([(DOCUMENTS.into(), "regional".into())]), + resources: BTreeMap::from([( "regional".into(), - SqlCluster { + Resource::Sql(SqlCluster { driver: SqlDriver::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(); - let resolved = resolved.documents().unwrap(); + let resolved = resolved.binding(DOCUMENTS).unwrap().as_sql().unwrap(); assert!( resolved .primary @@ -37,8 +39,10 @@ fn named_cluster_requires_matching_addresses() { .connection_string() .ends_with("sslmode=verify-full") ); - config.clusters.get_mut("regional").unwrap().replicas[0] = - "mysql://user:secret@replica/bedrock".into(); + let Some(Resource::Sql(cluster)) = config.resources.get_mut("regional") else { + panic!("expected a SQL resource"); + }; + cluster.replicas[0] = "mysql://user:secret@replica/bedrock".into(); assert!(matches!( config.resolve(), Err(ConfigError::Url("postgres")) @@ -56,25 +60,57 @@ fn resolves_named_connections_and_round_trips_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, + snapshot + .binding(DOCUMENTS) + .unwrap() + .as_sql() + .unwrap() + .driver, + SqlDriver::Postgres + ); + assert_eq!( + snapshot.binding("legacy").unwrap().as_sql().unwrap().driver, + SqlDriver::Mysql + ); + assert_eq!( + snapshot + .binding("attachments") + .unwrap() + .as_object_store() + .unwrap() + .bucket, "bedrock-attachments" ); - assert_eq!(snapshot.documents().unwrap().max_connections, 5); + assert_eq!( + snapshot + .binding(DOCUMENTS) + .unwrap() + .as_sql() + .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); + assert_eq!( + roundtrip + .binding("legacy") + .unwrap() + .as_sql() + .unwrap() + .driver, + SqlDriver::Mysql + ); } #[test] fn imports_catalog_atomically_and_preserves_role_references() { - use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver, Resource}; + use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver}; let mut config = DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap(); @@ -84,7 +120,8 @@ fn imports_catalog_atomically_and_preserves_role_references() { ImportFormat::KubernetesConfigMap, ) .unwrap(); - config.sql.insert("documents".into(), "pg-main".into()); + config.bindings.insert(DOCUMENTS.into(), "pg-main".into()); + config.bindings.insert("files".into(), "attachments".into()); let before = config.resource("attachments").unwrap().driver(); assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3)); @@ -107,6 +144,11 @@ fn imports_catalog_atomically_and_preserves_role_references() { .is_err() ); assert!(config.resource("another-bucket").is_none()); + assert!(matches!( + config.remove_resource("attachments"), + Err(ConfigError::ResourceInUse) + )); + config.bindings.remove("files"); let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else { panic!("expected S3 configuration"); }; @@ -119,7 +161,71 @@ fn imports_catalog_atomically_and_preserves_role_references() { .update_resource("attachments", Resource::ObjectStore(updated)) .unwrap(); assert_eq!( - config.resolve().unwrap().object_storage["attachments"].bucket, + config + .resolve() + .unwrap() + .resource("attachments") + .unwrap() + .as_object_store() + .unwrap() + .bucket, "replaced" ); } + +#[test] +fn legacy_configuration_is_normalized_at_load() { + use clusters::ConfigFormat; + + let config = DeploymentConfig::parse( + r#"{ + "cluster":"east", + "clusters":{"east":{"driver":"postgres","primary":"postgres://u@primary/db"}}, + "object_storage":{"files":{"driver":"s3","bucket":"files","region":"us-east-1"}} + }"#, + ConfigFormat::Json, + ) + .unwrap(); + let snapshot = config.resolve().unwrap(); + assert_eq!( + snapshot + .binding(DOCUMENTS) + .unwrap() + .as_sql() + .unwrap() + .driver, + SqlDriver::Postgres + ); + assert_eq!( + snapshot + .resource("files") + .unwrap() + .as_object_store() + .unwrap() + .bucket, + "files" + ); + + let config = + DeploymentConfig::parse("sqlite_path: custom.sqlite3", ConfigFormat::Yaml).unwrap(); + let snapshot = config.resolve().unwrap(); + let connection = snapshot.binding(DOCUMENTS).unwrap().as_sql().unwrap(); + assert!( + connection + .primary + .connection_string() + .ends_with("/custom.sqlite3?mode=rwc") + ); +} + +#[test] +fn missing_binding_target_is_rejected_for_any_role() { + let mut config = DeploymentConfig::default(); + config + .bindings + .insert("attachments".into(), "missing".into()); + assert!( + matches!(config.resolve(), Err(ConfigError::UnknownBinding { role, target }) + if role == "attachments" && target == "missing") + ); +} diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index 9d5d974..675676d 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -2,7 +2,9 @@ use std::sync::atomic::{AtomicUsize, Ordering}; -use clusters::{Address, ConfigError, DeploymentConfig, ResolvedSql, SqlDriver as Driver}; +use clusters::{ + Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedSql, SqlDriver as Driver, +}; use thiserror::Error; use crate::{ @@ -18,6 +20,8 @@ pub enum ConnectError { Config(#[from] ConfigError), #[error("the documents SQL role is not configured")] MissingDocuments, + #[error("the documents role must reference a SQL resource")] + InvalidDocuments, #[error(transparent)] Storage(#[from] StorageError), } @@ -102,7 +106,10 @@ pub struct Connection { pub async fn connect(config: &DeploymentConfig) -> Result { let config = config.resolve()?; - connect_sql(config.documents().ok_or(ConnectError::MissingDocuments)?).await + let resource = config + .binding(DOCUMENTS) + .ok_or(ConnectError::MissingDocuments)?; + connect_sql(resource.as_sql().ok_or(ConnectError::InvalidDocuments)?).await } pub async fn connect_sql(config: &ResolvedSql) -> Result { diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 5b95c83..11ea074 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -8,7 +8,7 @@ pub mod sqlite; pub use clusters::SqlDriver as Dialect; pub use clusters::{ - Address, Cluster, ConfigError, DeploymentConfig, SqlCluster, SqlDriver as Driver, Tls, + Address, Cluster, ConfigError, DeploymentConfig, Resource, SqlCluster, SqlDriver as Driver, Tls, }; pub use common::Error as StorageError; pub use common::{Document, Error, Mutation, Result, Revision, Snapshot}; diff --git a/crates/db/tests/storage.rs b/crates/db/tests/storage.rs index f485de0..8c138ae 100644 --- a/crates/db/tests/storage.rs +++ b/crates/db/tests/storage.rs @@ -1,8 +1,8 @@ use std::{collections::BTreeMap, env, time::Duration}; use db::{ - Connection, DeploymentConfig, Driver, Mutation, ReadPreference, SqlCluster, StorageError, Tls, - connect, + Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster, + StorageError, Tls, connect, }; use serde_json::json; @@ -17,16 +17,16 @@ fn change(id: &str, text: &str) -> Mutation { fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig { DeploymentConfig { deployment: deployment.into(), - cluster: Some("test".into()), - clusters: BTreeMap::from([( + bindings: BTreeMap::from([("documents".into(), "test".into())]), + resources: BTreeMap::from([( "test".into(), - SqlCluster { + Resource::Sql(SqlCluster { driver, primary: url.into(), replicas: vec![], tls: Tls::Disabled, max_connections: 4, - }, + }), )]), ..DeploymentConfig::default() } @@ -118,10 +118,7 @@ async fn check_document_contract(db: &Connection) { async fn sqlite_persists_across_reopening_and_enforces_read_only() { let folder = tempfile::tempdir().unwrap(); let filename = folder.path().join("bedrock +?#%.sqlite"); - let mut config = DeploymentConfig { - sqlite_path: filename.to_str().unwrap().into(), - ..DeploymentConfig::default() - }; + let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default"); let db = connect(&config).await.unwrap(); assert_eq!(db.driver(), Driver::Sqlite); check_document_contract(&db).await; @@ -140,11 +137,8 @@ async fn sqlite_persists_across_reopening_and_enforces_read_only() { async fn sqlite_read_only_startup_does_not_create_a_database() { let folder = tempfile::tempdir().unwrap(); let filename = folder.path().join("missing.sqlite"); - let config = DeploymentConfig { - read_only: true, - sqlite_path: filename.to_str().unwrap().into(), - ..DeploymentConfig::default() - }; + let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default"); + config.read_only = true; assert!(connect(&config).await.is_err()); assert!(!filename.exists()); } @@ -156,12 +150,10 @@ async fn postgres_reads_replicas_and_falls_back_when_behind() { }; let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap(); let mut config = sql_config(Driver::Postgres, &url, "pg_contract"); - config - .clusters - .get_mut("test") - .unwrap() - .replicas - .push(replica_url.clone().into()); + let Some(Resource::Sql(cluster)) = config.resources.get_mut("test") else { + panic!("expected a SQL resource"); + }; + cluster.replicas.push(replica_url.clone().into()); let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract")) .await .unwrap(); diff --git a/deploy/README.md b/deploy/README.md index 8da61dc..e8f110d 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -2,10 +2,10 @@ Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. See [local SQLite](sqlite.yaml) and [multiple SQL roles with S3 settings](multi-storage.yaml). The loader also accepts TOML and existing JSON files. -- **SQLite** uses a persistent, writable path for `sqlite_path`. +- **SQLite** uses a persistent, writable path in the SQL resource's `primary` field. - **PostgreSQL on the existing host** uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. - **Kubernetes** deploys each database and its Service separately. An in-cluster address can use the Service DNS name, such as `pg-main:5432` in the same namespace. Render the final YAML with deployment credentials, store it in a Secret, mount it into the Bedrock workload and set `BEDROCK_DB_CONFIG` to the mounted file. The [catalog ConfigMap example](kubernetes-catalog.yaml) shows how to package a catalog for the library import API without credentials. Declare the resource kind and driver in the catalog and bind its role in the deployment file. A Service name, port, or Kubernetes object kind alone does not describe the backend or its purpose. -- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration. +- **Terraform or cloud inventory** can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration under `bindings`. Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances. diff --git a/deploy/multi-storage.yaml b/deploy/multi-storage.yaml index e2b3f15..3432043 100644 --- a/deploy/multi-storage.yaml +++ b/deploy/multi-storage.yaml @@ -1,18 +1,21 @@ # Illustrative service names. Inject deployment credentials before publishing. deployment: production config_version: example-1 -clusters: +resources: pg-main: + kind: sql driver: postgres primary: postgres://bedrock@pg-main:5432/bedrock mysql-legacy: + kind: sql driver: mysql primary: mysql://bedrock@mysql-legacy:3306/legacy -sql: - documents: pg-main - legacy: mysql-legacy -object_storage: - attachments: + attachment-store: + kind: object_store driver: s3 bucket: bedrock-attachments region: us-east-1 +bindings: + documents: pg-main + legacy: mysql-legacy + attachments: attachment-store diff --git a/deploy/render-postgres.py b/deploy/render-postgres.py index 01d8aa4..9944389 100644 --- a/deploy/render-postgres.py +++ b/deploy/render-postgres.py @@ -55,10 +55,11 @@ def main(): config = ( f"deployment: {json.dumps(options.deployment)}\n" f"config_version: {json.dumps(options.config_version)}\n" - "sql:\n" + "bindings:\n" " documents: postgres\n" - "clusters:\n" + "resources:\n" " postgres:\n" + " kind: sql\n" " driver: postgres\n" f" primary: {json.dumps(database_url())}\n" ) diff --git a/deploy/sqlite.yaml b/deploy/sqlite.yaml index b3e7294..9243e79 100644 --- a/deploy/sqlite.yaml +++ b/deploy/sqlite.yaml @@ -1,3 +1,10 @@ deployment: default config_version: local -sqlite_path: bedrock.sqlite3 +resources: + local: + kind: sql + driver: sqlite + primary: bedrock.sqlite3 + max_connections: 1 +bindings: + documents: local diff --git a/src/main.rs b/src/main.rs index 3be0f3e..d8f4cce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::{env, error::Error}; -use clusters::DeploymentConfig; +use clusters::{DOCUMENTS, DeploymentConfig}; use db::connect_sql; #[tokio::main] @@ -10,7 +10,16 @@ async fn main() -> Result<(), Box> { None => DeploymentConfig::default(), }; let resolved = config.resolve()?; - for (role, settings) in &resolved.sql { + if resolved + .binding(DOCUMENTS) + .is_some_and(|resource| resource.as_sql().is_none()) + { + return Err(db::ConnectError::InvalidDocuments.into()); + } + for (role, resource) in resolved.bound_resources() { + let Some(settings) = resource.as_sql() else { + continue; + }; let connection = connect_sql(settings).await?; println!( "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})",