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