From 7982fffcda0ca8fc05c02309906c9b5e1e8cd33e Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Mon, 30 Nov 2026 17:11:03 +0800 Subject: [PATCH] Add a versioned backend catalog and YAML deployment configuration --- Cargo.lock | 168 ++++++++++++- Cargo.toml | 4 +- README.md | 23 +- crates/clusters/Cargo.toml | 3 + crates/clusters/src/catalog.rs | 88 +++++++ crates/clusters/src/driver.rs | 49 ++++ crates/clusters/src/format.rs | 127 ++++++++++ crates/clusters/src/lib.rs | 260 ++++++++------------- crates/clusters/src/object_storage.rs | 34 +++ crates/clusters/src/sql.rs | 169 ++++++++++++++ crates/clusters/tests/deployment_config.rs | 84 ++++++- crates/db/src/connection.rs | 14 +- crates/db/src/lib.rs | 8 +- deploy/README.md | 13 +- deploy/bedrock-deployment.svg | 2 +- deploy/kubernetes-catalog.yaml | 16 ++ deploy/multi-storage.yaml | 18 ++ deploy/release.sh | 7 +- deploy/render-postgres.py | 27 ++- deploy/sqlite.json | 4 - deploy/sqlite.yaml | 3 + src/main.rs | 26 ++- 22 files changed, 924 insertions(+), 223 deletions(-) create mode 100644 crates/clusters/src/catalog.rs create mode 100644 crates/clusters/src/driver.rs create mode 100644 crates/clusters/src/format.rs create mode 100644 crates/clusters/src/object_storage.rs create mode 100644 crates/clusters/src/sql.rs create mode 100644 deploy/kubernetes-catalog.yaml create mode 100644 deploy/multi-storage.yaml delete mode 100644 deploy/sqlite.json create mode 100644 deploy/sqlite.yaml diff --git a/Cargo.lock b/Cargo.lock index 2f38097..42ecca8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,6 +36,29 @@ version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" +[[package]] +name = "annotate-snippets" +version = "0.12.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" +dependencies = [ + "anstyle", + "memchr", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "arraydeque" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" + [[package]] name = "async-trait" version = "0.1.92" @@ -69,8 +92,8 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" name = "bedrock" version = "0.1.0" dependencies = [ + "clusters", "db", - "serde_json", "tokio", ] @@ -157,7 +180,10 @@ name = "clusters" version = "0.1.0" dependencies = [ "serde", + "serde-saphyr", + "serde_json", "thiserror", + "toml", "url", ] @@ -179,6 +205,12 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -368,6 +400,29 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "encoding_rs_io" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" +dependencies = [ + "encoding_rs", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -545,6 +600,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "granit-parser" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd04d0d9c7079b416b458d2317aea4aa964c81938cb7c20f559758c4f422dc8" +dependencies = [ + "arraydeque", + "smallvec", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -837,6 +902,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "mysql_async" version = "0.36.2" @@ -895,6 +966,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + [[package]] name = "num-bigint" version = "0.4.8" @@ -1290,6 +1367,23 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-saphyr" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" +dependencies = [ + "annotate-snippets", + "base64", + "encoding_rs_io", + "granit-parser", + "nohash-hasher", + "num-traits", + "serde_core", + "smallvec", + "zmij", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -1323,6 +1417,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "sha1" version = "0.10.7" @@ -1368,6 +1471,12 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "siphasher" version = "1.0.4" @@ -1644,6 +1753,45 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tracing" version = "0.1.44" @@ -1714,6 +1862,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "untrusted" version = "0.9.0" @@ -1975,6 +2129,18 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index 106fe02..1e29d5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,8 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std" rustls-pemfile = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" +serde-saphyr = { version = "2.2", default-features = false, features = ["deserialize", "serialize"] } +toml = "0.9" tempfile = "3" thiserror = "2" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } @@ -32,6 +34,6 @@ edition.workspace = true rust-version.workspace = true [dependencies] +clusters.workspace = true db.workspace = true -serde_json.workspace = true tokio.workspace = true diff --git a/README.md b/README.md index 37bbfcd..ed26a55 100644 --- a/README.md +++ b/README.md @@ -4,32 +4,19 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i ## Storage boundaries -`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `common.rs`. +`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share document types, validation, and encoding in `common.rs`. -Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) +Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock supports named SQL roles and read replicas. The catalog can describe S3 buckets. Object I/O, workspace routing, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) ## Database configuration -Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example: +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. -```json -{ - "deployment": "production", - "cluster": "east", - "clusters": { - "east": { - "driver": "postgres", - "primary": "postgres://bedrock@primary.example.net/bedrock", - "replicas": ["postgres://bedrock_reader@replica.example.net/bedrock"], - "max_connections": 5 - } - } -} -``` +`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. 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. -Applications connect with `db::connect`. 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. +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. For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database. diff --git a/crates/clusters/Cargo.toml b/crates/clusters/Cargo.toml index 5fdebbe..459c6b0 100644 --- a/crates/clusters/Cargo.toml +++ b/crates/clusters/Cargo.toml @@ -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 diff --git a/crates/clusters/src/catalog.rs b/crates/clusters/src/catalog.rs new file mode 100644 index 0000000..09f1327 --- /dev/null +++ b/crates/clusters/src/catalog.rs @@ -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> { + self.clusters + .get(name) + .map(ResourceRef::Sql) + .or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore)) + } + + pub fn resources(&self) -> impl Iterator)> { + 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 { + 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(()) + } +} diff --git a/crates/clusters/src/driver.rs b/crates/clusters/src/driver.rs new file mode 100644 index 0000000..3e40b4e --- /dev/null +++ b/crates/clusters/src/driver.rs @@ -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, +} diff --git a/crates/clusters/src/format.rs b/crates/clusters/src/format.rs new file mode 100644 index 0000000..f4adec0 --- /dev/null +++ b/crates/clusters/src/format.rs @@ -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(self, input: &str) -> Result { + 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 { + format.parse(input) + } + + pub fn load(path: impl AsRef) -> Result { + 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 { + 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 = 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, +} + +#[derive(Deserialize)] +struct TerraformOutput { + value: BTreeMap, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct ConfigMap { + api_version: String, + kind: String, + data: BTreeMap, +} diff --git a/crates/clusters/src/lib.rs b/crates/clusters/src/lib.rs index eb8bb2d..feb7c3a 100644 --- a/crates/clusters/src/lib.rs +++ b/crates/clusters/src/lib.rs @@ -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 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
, - #[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, pub clusters: BTreeMap, + /// SQL role to named cluster. + pub sql: BTreeMap, + pub object_storage: BTreeMap, 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, - pub driver: Driver, - pub primary: Address, - pub replicas: Vec
, - pub read_only: bool, - pub max_connections: u32, + pub config_version: String, + pub sql: BTreeMap, + pub object_storage: BTreeMap, +} + +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 { 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::>()?; 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 { - 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 { - 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}"))) -} diff --git a/crates/clusters/src/object_storage.rs b/crates/clusters/src/object_storage.rs new file mode 100644 index 0000000..1aeb33e --- /dev/null +++ b/crates/clusters/src/object_storage.rs @@ -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, +} + +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(()) + } +} diff --git a/crates/clusters/src/sql.rs b/crates/clusters/src/sql.rs new file mode 100644 index 0000000..02fc1d0 --- /dev/null +++ b/crates/clusters/src/sql.rs @@ -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 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
, + #[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 Cluster { + 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: &Cluster, + 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}"))) +} diff --git a/crates/clusters/tests/deployment_config.rs b/crates/clusters/tests/deployment_config.rs index 796997e..6702806 100644 --- a/crates/clusters/tests/deployment_config.rs +++ b/crates/clusters/tests/deployment_config.rs @@ -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" + ); +} diff --git a/crates/db/src/connection.rs b/crates/db/src/connection.rs index e50d51b..9d5d974 100644 --- a/crates/db/src/connection.rs +++ b/crates/db/src/connection.rs @@ -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 { let config = config.resolve()?; + connect_sql(config.documents().ok_or(ConnectError::MissingDocuments)?).await +} + +pub async fn connect_sql(config: &ResolvedSql) -> Result { let writer = if config.read_only { None } else { @@ -115,7 +121,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result 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>()?; Ok(Connection { driver: config.driver, @@ -134,7 +140,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result Result { +fn reader(config: &ResolvedSql, address: &Address) -> Result { let url = address.connection_string(); let name = &config.deployment; match config.driver { diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index b928ef8..a4efbfd 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -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}; diff --git a/deploy/README.md b/deploy/README.md index 45d8eaa..5b79e8f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,12 +1,15 @@ # Deployment configuration -Deployments pass the path of a JSON configuration file to the Bedrock executable using `BEDROCK_DB_CONFIG`. The Rust libraries accept structured configuration. +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 `deploy/sqlite.json` as a template. Set `sqlite_path` to a persistent, writable volume path. -- **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address. -- **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint. +- **SQLite** uses a persistent, writable path for `sqlite_path`. +- **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. -Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `db` use only SQL configuration. +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. + +S3 entries describe endpoints and buckets. Keep access credentials in the deployment's secret store for the eventual object storage client. Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner. diff --git a/deploy/bedrock-deployment.svg b/deploy/bedrock-deployment.svg index c07065e..67b1a6d 100644 --- a/deploy/bedrock-deployment.svg +++ b/deploy/bedrock-deployment.svg @@ -65,7 +65,7 @@ 和密码 Secret render-postgres.py -由 release.sh 调用,生成权限为 0600 的 bedrock.json。 +由 release.sh 调用,生成权限为 0600 的 bedrock.yaml。 release.sh 启动临时容器 挂载二进制和配置,运行 Rust bedrock。 diff --git a/deploy/kubernetes-catalog.yaml b/deploy/kubernetes-catalog.yaml new file mode 100644 index 0000000..9da516c --- /dev/null +++ b/deploy/kubernetes-catalog.yaml @@ -0,0 +1,16 @@ +# Resource catalog for ImportFormat::KubernetesConfigMap. +apiVersion: v1 +kind: ConfigMap +metadata: + name: bedrock-resources +data: + bedrock-resources.yaml: | + pg-main: + kind: sql + driver: postgres + primary: postgres://bedrock@pg-main:5432/bedrock + attachments: + kind: object_store + driver: s3 + bucket: bedrock-attachments + region: us-east-1 diff --git a/deploy/multi-storage.yaml b/deploy/multi-storage.yaml new file mode 100644 index 0000000..e2b3f15 --- /dev/null +++ b/deploy/multi-storage.yaml @@ -0,0 +1,18 @@ +# Illustrative service names. Inject deployment credentials before publishing. +deployment: production +config_version: example-1 +clusters: + pg-main: + driver: postgres + primary: postgres://bedrock@pg-main:5432/bedrock + mysql-legacy: + driver: mysql + primary: mysql://bedrock@mysql-legacy:3306/legacy +sql: + documents: pg-main + legacy: mysql-legacy +object_storage: + attachments: + driver: s3 + bucket: bedrock-attachments + region: us-east-1 diff --git a/deploy/release.sh b/deploy/release.sh index 57fb953..e88606a 100644 --- a/deploy/release.sh +++ b/deploy/release.sh @@ -21,16 +21,17 @@ stage=$(mktemp -d "$root/releases/.staging.XXXXXXXX") cleanup() { rm -rf -- "$stage"; } trap cleanup EXIT install -m 755 "$binary" "$stage/bedrock" -python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.json" --deployment production +release="$revision.${stage##*.}" +python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \ + --deployment production --config-version "$release" # The current binary is a one-shot storage initializer. It publishes no ports. docker run --rm --network "$network" \ --user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \ --mount "type=bind,source=$stage,target=/release,readonly" \ - -e BEDROCK_DB_CONFIG=/release/bedrock.json \ + -e BEDROCK_DB_CONFIG=/release/bedrock.yaml \ debian:bookworm-slim /release/bedrock -release="$revision.${stage##*.}" # Keep the final release private; only switch current after initialization succeeds. python3 - "$stage" "$root" "$release" <<'PY' import os diff --git a/deploy/render-postgres.py b/deploy/render-postgres.py index a3d00e2..01d8aa4 100644 --- a/deploy/render-postgres.py +++ b/deploy/render-postgres.py @@ -45,26 +45,29 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output", type=Path) parser.add_argument("--deployment", default="default") + parser.add_argument("--config-version", default="local") options = parser.parse_args() if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment): parser.error("invalid deployment name") - config = { - "deployment": options.deployment, - "cluster": "postgres", - "clusters": { - "postgres": { - "driver": "postgres", - "primary": database_url(), - } - }, - } + if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.config_version): + parser.error("invalid config version") + # JSON quoting is valid for scalars in YAML and handles special characters. + config = ( + f"deployment: {json.dumps(options.deployment)}\n" + f"config_version: {json.dumps(options.config_version)}\n" + "sql:\n" + " documents: postgres\n" + "clusters:\n" + " postgres:\n" + " driver: postgres\n" + f" primary: {json.dumps(database_url())}\n" + ) # Write with owner-only permissions, then replace the destination atomically. file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False) try: with file: - json.dump(config, file, indent=2) - file.write("\n") + file.write(config) os.replace(file.name, options.output) finally: Path(file.name).unlink(missing_ok=True) diff --git a/deploy/sqlite.json b/deploy/sqlite.json deleted file mode 100644 index 6e61a4d..0000000 --- a/deploy/sqlite.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "deployment": "default", - "sqlite_path": "bedrock.sqlite3" -} diff --git a/deploy/sqlite.yaml b/deploy/sqlite.yaml new file mode 100644 index 0000000..b3e7294 --- /dev/null +++ b/deploy/sqlite.yaml @@ -0,0 +1,3 @@ +deployment: default +config_version: local +sqlite_path: bedrock.sqlite3 diff --git a/src/main.rs b/src/main.rs index 5036bf6..3be0f3e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,19 +1,25 @@ -use std::{env, error::Error, fs}; +use std::{env, error::Error}; -use db::{DeploymentConfig, connect}; +use clusters::DeploymentConfig; +use db::connect_sql; #[tokio::main] async fn main() -> Result<(), Box> { let config = match env::var_os("BEDROCK_DB_CONFIG") { - Some(path) => serde_json::from_slice::(&fs::read(path)?)?, + Some(path) => DeploymentConfig::load(path)?, None => DeploymentConfig::default(), }; - let db = connect(&config).await?; - println!( - "Bedrock storage ready ({:?}, revision {}, read-only: {})", - db.driver(), - db.revision().await?, - db.is_read_only() - ); + let resolved = config.resolve()?; + for (role, settings) in &resolved.sql { + let connection = connect_sql(settings).await?; + println!( + "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})", + resolved.config_version, + role, + connection.driver(), + connection.revision().await?, + connection.is_read_only(), + ); + } Ok(()) }