Add a versioned backend catalog and YAML deployment configuration

This commit is contained in:
2026-11-30 17:11:03 +08:00
parent c270adbab4
commit 7982fffcda
22 changed files with 924 additions and 223 deletions
Generated
+167 -1
View File
@@ -36,6 +36,29 @@ version = "0.2.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" 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]] [[package]]
name = "async-trait" name = "async-trait"
version = "0.1.92" version = "0.1.92"
@@ -69,8 +92,8 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
name = "bedrock" name = "bedrock"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"clusters",
"db", "db",
"serde_json",
"tokio", "tokio",
] ]
@@ -157,7 +180,10 @@ name = "clusters"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"serde", "serde",
"serde-saphyr",
"serde_json",
"thiserror", "thiserror",
"toml",
"url", "url",
] ]
@@ -179,6 +205,12 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.17" version = "0.2.17"
@@ -368,6 +400,29 @@ dependencies = [
"syn 3.0.10", "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]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.3" version = "1.0.3"
@@ -545,6 +600,16 @@ dependencies = [
"wasm-bindgen", "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]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.14.5" version = "0.14.5"
@@ -837,6 +902,12 @@ dependencies = [
"windows-sys 0.61.2", "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]] [[package]]
name = "mysql_async" name = "mysql_async"
version = "0.36.2" version = "0.36.2"
@@ -895,6 +966,12 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "nohash-hasher"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]] [[package]]
name = "num-bigint" name = "num-bigint"
version = "0.4.8" version = "0.4.8"
@@ -1290,6 +1367,23 @@ dependencies = [
"serde_derive", "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]] [[package]]
name = "serde_core" name = "serde_core"
version = "1.0.229" version = "1.0.229"
@@ -1323,6 +1417,15 @@ dependencies = [
"zmij", "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]] [[package]]
name = "sha1" name = "sha1"
version = "0.10.7" version = "0.10.7"
@@ -1368,6 +1471,12 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.4" version = "1.0.4"
@@ -1644,6 +1753,45 @@ dependencies = [
"tokio", "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]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.44" version = "0.1.44"
@@ -1714,6 +1862,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
[[package]]
name = "unicode-width"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
[[package]] [[package]]
name = "untrusted" name = "untrusted"
version = "0.9.0" version = "0.9.0"
@@ -1975,6 +2129,18 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 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]] [[package]]
name = "wit-bindgen" name = "wit-bindgen"
version = "0.57.1" version = "0.57.1"
+3 -1
View File
@@ -16,6 +16,8 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std"
rustls-pemfile = "2" rustls-pemfile = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
serde-saphyr = { version = "2.2", default-features = false, features = ["deserialize", "serialize"] }
toml = "0.9"
tempfile = "3" tempfile = "3"
thiserror = "2" thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
@@ -32,6 +34,6 @@ edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
[dependencies] [dependencies]
clusters.workspace = true
db.workspace = true db.workspace = true
serde_json.workspace = true
tokio.workspace = true tokio.workspace = true
+5 -18
View File
@@ -4,32 +4,19 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i
## Storage boundaries ## 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 ## 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 `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.
{
"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
}
}
}
```
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 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. 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.
+3
View File
@@ -6,5 +6,8 @@ rust-version.workspace = true
[dependencies] [dependencies]
serde.workspace = true serde.workspace = true
serde_json.workspace = true
serde-saphyr.workspace = true
toml.workspace = true
thiserror.workspace = true thiserror.workspace = true
url.workspace = true url.workspace = true
+88
View File
@@ -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(())
}
}
+49
View File
@@ -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,
}
+127
View File
@@ -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>,
}
+97 -155
View File
@@ -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 thiserror::Error;
use url::Url;
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)] pub use catalog::{Resource, ResourceRef};
#[serde(rename_all = "snake_case")] pub use driver::*;
pub enum Driver { pub use format::{ConfigFormat, FormatError, ImportFormat};
#[default] pub use object_storage::ObjectStorage;
Sqlite, pub use sql::{Address, Cluster, ResolvedSql, SqlDriver, Tls};
Postgres,
Mysql,
}
#[derive(Clone, Copy, Debug, Default, Deserialize)] pub const DOCUMENTS: &str = "documents";
#[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, Debug, Deserialize, Serialize)]
#[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)]
#[serde(default, deny_unknown_fields)] #[serde(default, deny_unknown_fields)]
pub struct DeploymentConfig { pub struct DeploymentConfig {
pub deployment: String, pub deployment: String,
pub config_version: String,
/// Legacy shorthand for sql.documents.
pub cluster: Option<String>, pub cluster: Option<String>,
pub clusters: BTreeMap<String, Cluster>, 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 read_only: bool,
pub sqlite_path: Address, pub sqlite_path: Address,
} }
@@ -81,23 +38,30 @@ impl Default for DeploymentConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
deployment: "default".into(), deployment: "default".into(),
config_version: "local".into(),
cluster: None, cluster: None,
clusters: BTreeMap::new(), clusters: BTreeMap::new(),
sql: BTreeMap::new(),
object_storage: BTreeMap::new(),
read_only: false, read_only: false,
sqlite_path: "bedrock.sqlite3".into(), sqlite_path: "bedrock.sqlite3".into(),
} }
} }
} }
#[derive(Debug)] /// A validated startup snapshot. The version identifies the configuration release.
#[derive(Clone, Debug)]
pub struct ResolvedDeployment { pub struct ResolvedDeployment {
pub deployment: String, pub deployment: String,
pub cluster: Option<String>, pub config_version: String,
pub driver: Driver, pub sql: BTreeMap<String, ResolvedSql>,
pub primary: Address, pub object_storage: BTreeMap<String, ObjectStorage>,
pub replicas: Vec<Address>, }
pub read_only: bool,
pub max_connections: u32, impl ResolvedDeployment {
pub fn documents(&self) -> Option<&ResolvedSql> {
self.sql.get(DOCUMENTS)
}
} }
#[derive(Debug, Error)] #[derive(Debug, Error)]
@@ -108,6 +72,18 @@ pub enum ConfigError {
UnknownCluster, UnknownCluster,
#[error("a cluster must be selected when clusters are configured")] #[error("a cluster must be selected when clusters are configured")]
ClusterRequired, 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")] #[error("the database pool size must be greater than zero")]
PoolSize, PoolSize,
#[error("SQLite does not support a replica list")] #[error("SQLite does not support a replica list")]
@@ -121,46 +97,68 @@ pub enum ConfigError {
impl DeploymentConfig { impl DeploymentConfig {
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> { pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
validate_name(&self.deployment, "deployment")?; 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)?,
);
}
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 = Cluster { let local = Cluster {
driver: Driver::Sqlite, driver: SqlDriver::Sqlite,
primary: self.sqlite_path.clone(), primary: self.sqlite_path.clone(),
replicas: vec![], replicas: vec![],
tls: Tls::Disabled, tls: Tls::Disabled,
max_connections: 1, max_connections: 1,
}; };
let cluster = match &self.cluster { sql.insert(
Some(name) => { DOCUMENTS.into(),
validate_name(name, "cluster")?; local.resolve(&self.deployment, None, self.read_only)?,
self.clusters.get(name).ok_or(ConfigError::UnknownCluster)? );
} }
None if self.clusters.is_empty() => &local,
None => return Err(ConfigError::ClusterRequired),
};
if cluster.max_connections == 0 {
return Err(ConfigError::PoolSize);
}
if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
}
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 { Ok(ResolvedDeployment {
deployment: self.deployment.clone(), deployment: self.deployment.clone(),
cluster: self.cluster.clone(), config_version: self.config_version.clone(),
driver: cluster.driver, sql,
primary, object_storage: self.object_storage.clone(),
replicas,
read_only: self.read_only,
max_connections: cluster.max_connections,
}) })
} }
} }
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() if value.is_empty()
|| value.len() > 128 || value.len() > 128
|| !value || !value
@@ -171,59 +169,3 @@ fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
} }
Ok(()) 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}")))
}
+34
View File
@@ -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(())
}
}
+169
View File
@@ -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}")))
}
+82 -2
View File
@@ -1,6 +1,6 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver, Tls};
#[test] #[test]
fn address_debug_formats_the_inner_string() { fn address_debug_formats_the_inner_string() {
@@ -15,7 +15,7 @@ fn named_cluster_requires_matching_addresses() {
clusters: BTreeMap::from([( clusters: BTreeMap::from([(
"regional".into(), "regional".into(),
Cluster { Cluster {
driver: Driver::Postgres, driver: SqlDriver::Postgres,
primary: "postgres://user:secret@primary/bedrock".into(), primary: "postgres://user:secret@primary/bedrock".into(),
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()], replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
tls: Tls::VerifyFull, tls: Tls::VerifyFull,
@@ -25,6 +25,7 @@ fn named_cluster_requires_matching_addresses() {
..DeploymentConfig::default() ..DeploymentConfig::default()
}; };
let resolved = config.resolve().unwrap(); let resolved = config.resolve().unwrap();
let resolved = resolved.documents().unwrap();
assert!( assert!(
resolved resolved
.primary .primary
@@ -43,3 +44,82 @@ fn named_cluster_requires_matching_addresses() {
Err(ConfigError::Url("postgres")) 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"
);
}
+10 -4
View File
@@ -2,7 +2,7 @@
use std::sync::atomic::{AtomicUsize, Ordering}; 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 thiserror::Error;
use crate::{ use crate::{
@@ -16,6 +16,8 @@ use crate::{
pub enum ConnectError { pub enum ConnectError {
#[error(transparent)] #[error(transparent)]
Config(#[from] ConfigError), Config(#[from] ConfigError),
#[error("the documents SQL role is not configured")]
MissingDocuments,
#[error(transparent)] #[error(transparent)]
Storage(#[from] StorageError), Storage(#[from] StorageError),
} }
@@ -100,6 +102,10 @@ pub struct Connection {
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> { pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
let config = config.resolve()?; 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 { let writer = if config.read_only {
None None
} else { } else {
@@ -115,7 +121,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
let primary = match &writer { let primary = match &writer {
Some(store) => store.reader(), Some(store) => store.reader(),
None => { None => {
let reader = reader(&config, &config.primary)?; let reader = reader(config, &config.primary)?;
reader.revision().await?; reader.revision().await?;
reader reader
} }
@@ -123,7 +129,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
let replicas = config let replicas = config
.replicas .replicas
.iter() .iter()
.map(|address| reader(&config, address)) .map(|address| reader(config, address))
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
Ok(Connection { Ok(Connection {
driver: config.driver, 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 url = address.connection_string();
let name = &config.deployment; let name = &config.deployment;
match config.driver { match config.driver {
+5 -3
View File
@@ -6,9 +6,11 @@ pub mod mysql;
pub mod postgres; pub mod postgres;
pub mod sqlite; pub mod sqlite;
pub use clusters::Driver as Dialect; pub use clusters::SqlDriver as Dialect;
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, SqlDriver as Driver, Tls};
pub use common::Error as StorageError; pub use common::Error as StorageError;
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot}; 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}; pub use mysql::{Lease, MySql};
+8 -5
View File
@@ -1,12 +1,15 @@
# Deployment configuration # 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. - **SQLite** uses a persistent, writable path for `sqlite_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. - **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.
- **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` 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. 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.
+1 -1
View File
@@ -65,7 +65,7 @@
<text x="584" y="481" class="detail">和密码 Secret</text> <text x="584" y="481" class="detail">和密码 Secret</text>
<rect x="84" y="497" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/> <rect x="84" y="497" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="526" class="code">render-postgres.py</text> <text x="104" y="526" class="code">render-postgres.py</text>
<text x="104" y="547" class="detail">由 release.sh 调用,生成权限为 0600 的 bedrock.json。</text> <text x="104" y="547" class="detail">由 release.sh 调用,生成权限为 0600 的 bedrock.yaml。</text>
<rect x="84" y="580" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/> <rect x="84" y="580" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
<text x="104" y="609" class="headline">release.sh 启动临时容器</text> <text x="104" y="609" class="headline">release.sh 启动临时容器</text>
<text x="104" y="630" class="detail">挂载二进制和配置,运行 Rust bedrock。</text> <text x="104" y="630" class="detail">挂载二进制和配置,运行 Rust bedrock。</text>

Before

Width:  |  Height:  |  Size: 7.4 KiB

After

Width:  |  Height:  |  Size: 7.4 KiB

+16
View File
@@ -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
+18
View File
@@ -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
+4 -3
View File
@@ -21,16 +21,17 @@ stage=$(mktemp -d "$root/releases/.staging.XXXXXXXX")
cleanup() { rm -rf -- "$stage"; } cleanup() { rm -rf -- "$stage"; }
trap cleanup EXIT trap cleanup EXIT
install -m 755 "$binary" "$stage/bedrock" 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. # The current binary is a one-shot storage initializer. It publishes no ports.
docker run --rm --network "$network" \ docker run --rm --network "$network" \
--user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \ --user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \
--mount "type=bind,source=$stage,target=/release,readonly" \ --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 debian:bookworm-slim /release/bedrock
release="$revision.${stage##*.}"
# Keep the final release private; only switch current after initialization succeeds. # Keep the final release private; only switch current after initialization succeeds.
python3 - "$stage" "$root" "$release" <<'PY' python3 - "$stage" "$root" "$release" <<'PY'
import os import os
+15 -12
View File
@@ -45,26 +45,29 @@ def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path) parser.add_argument("output", type=Path)
parser.add_argument("--deployment", default="default") parser.add_argument("--deployment", default="default")
parser.add_argument("--config-version", default="local")
options = parser.parse_args() options = parser.parse_args()
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment): if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment):
parser.error("invalid deployment name") parser.error("invalid deployment name")
config = { if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.config_version):
"deployment": options.deployment, parser.error("invalid config version")
"cluster": "postgres", # JSON quoting is valid for scalars in YAML and handles special characters.
"clusters": { config = (
"postgres": { f"deployment: {json.dumps(options.deployment)}\n"
"driver": "postgres", f"config_version: {json.dumps(options.config_version)}\n"
"primary": database_url(), "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. # Write with owner-only permissions, then replace the destination atomically.
file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False) file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False)
try: try:
with file: with file:
json.dump(config, file, indent=2) file.write(config)
file.write("\n")
os.replace(file.name, options.output) os.replace(file.name, options.output)
finally: finally:
Path(file.name).unlink(missing_ok=True) Path(file.name).unlink(missing_ok=True)
-4
View File
@@ -1,4 +0,0 @@
{
"deployment": "default",
"sqlite_path": "bedrock.sqlite3"
}
+3
View File
@@ -0,0 +1,3 @@
deployment: default
config_version: local
sqlite_path: bedrock.sqlite3
+14 -8
View File
@@ -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] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
let config = match env::var_os("BEDROCK_DB_CONFIG") { let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?, Some(path) => DeploymentConfig::load(path)?,
None => DeploymentConfig::default(), None => DeploymentConfig::default(),
}; };
let db = connect(&config).await?; let resolved = config.resolve()?;
for (role, settings) in &resolved.sql {
let connection = connect_sql(settings).await?;
println!( println!(
"Bedrock storage ready ({:?}, revision {}, read-only: {})", "Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})",
db.driver(), resolved.config_version,
db.revision().await?, role,
db.is_read_only() connection.driver(),
connection.revision().await?,
connection.is_read_only(),
); );
}
Ok(()) Ok(())
} }