Unify backend resources and role bindings in clusters
This commit is contained in:
+20
-16
@@ -2,29 +2,33 @@
|
||||
|
||||
`clusters` 负责读取和校验 Bedrock 的部署配置,并解析出各用途的连接参数。
|
||||
|
||||
`resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。
|
||||
|
||||
## 模块依赖
|
||||
|
||||
箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。
|
||||
|
||||
`driver.rs` 集中定义驱动类型,供 SQL 和对象存储配置模块使用。
|
||||
|
||||
`sql.rs` 定义 `SqlCluster`,描述 SQL 主库和可选读副本。`catalog.rs` 的 `Resource` 统一表示 SQL 和对象存储资源。
|
||||
箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
lib["lib.rs"] -->|解析 SQL 配置| sql["sql.rs"]
|
||||
lib -->|校验对象存储配置| obj["object_storage.rs"]
|
||||
|
||||
sql -->|ConfigError| lib
|
||||
obj -->|ConfigError| lib
|
||||
sql -->|SqlDriver| drv["driver.rs"]
|
||||
obj -->|ObjectStoreDriver| drv
|
||||
|
||||
lib["lib.rs"] -->|解析资源和用途| res["resource.rs"]
|
||||
lib --> err["error.rs"]
|
||||
cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib
|
||||
cat -->|统一表示驱动类别| drv
|
||||
cat -->|编辑 SQL 资源| sql
|
||||
cat -->|编辑对象存储资源| obj
|
||||
cat -->|统一校验资源| res
|
||||
cat --> err
|
||||
|
||||
res -->|SQL 配置和解析| sql["sql.rs"]
|
||||
res -->|对象存储配置和解析| obj["object_storage.rs"]
|
||||
res -->|统一驱动类型| drv["driver.rs"]
|
||||
res --> err
|
||||
sql -->|SqlDriver| drv
|
||||
obj -->|ObjectStoreDriver| drv
|
||||
sql --> err
|
||||
obj --> err
|
||||
|
||||
fmt["format.rs"] -->|读取和输出 DeploymentConfig| lib
|
||||
fmt -->|导入时调用 insert_resource| cat
|
||||
fmt -->|读取资源格式| res
|
||||
fmt -->|读取旧 SQL 配置| sql
|
||||
fmt -->|读取旧对象存储配置| obj
|
||||
fmt --> err
|
||||
```
|
||||
|
||||
@@ -1,88 +1,48 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
//! Named resource lookup and editing.
|
||||
|
||||
use crate::{ConfigError, DeploymentConfig, Driver, ObjectStorage, SqlCluster, validate_name};
|
||||
use std::mem::discriminant;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Resource {
|
||||
Sql(SqlCluster),
|
||||
ObjectStore(ObjectStorage),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ResourceRef<'a> {
|
||||
Sql(&'a SqlCluster),
|
||||
ObjectStore(&'a ObjectStorage),
|
||||
}
|
||||
|
||||
impl ResourceRef<'_> {
|
||||
pub fn driver(self) -> Driver {
|
||||
match self {
|
||||
Self::Sql(cluster) => Driver::Sql(cluster.driver),
|
||||
Self::ObjectStore(store) => Driver::ObjectStore(store.driver),
|
||||
}
|
||||
}
|
||||
}
|
||||
use crate::{ConfigError, DeploymentConfig, Resource, ResourceRef, validate_name};
|
||||
|
||||
impl DeploymentConfig {
|
||||
pub fn resource(&self, name: &str) -> Option<ResourceRef<'_>> {
|
||||
self.clusters
|
||||
.get(name)
|
||||
.map(ResourceRef::Sql)
|
||||
.or_else(|| self.object_storage.get(name).map(ResourceRef::ObjectStore))
|
||||
self.resources.get(name)
|
||||
}
|
||||
|
||||
pub fn resources(&self) -> impl Iterator<Item = (&str, ResourceRef<'_>)> {
|
||||
self.clusters
|
||||
self.resources
|
||||
.iter()
|
||||
.map(|(name, value)| (name.as_str(), ResourceRef::Sql(value)))
|
||||
.chain(
|
||||
self.object_storage
|
||||
.iter()
|
||||
.map(|(name, value)| (name.as_str(), ResourceRef::ObjectStore(value))),
|
||||
)
|
||||
.map(|(name, resource)| (name.as_str(), resource))
|
||||
}
|
||||
|
||||
pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
|
||||
if self.resource(&name).is_some() {
|
||||
if self.resources.contains_key(&name) {
|
||||
return Err(ConfigError::DuplicateResource);
|
||||
}
|
||||
self.store_resource(name, resource)
|
||||
}
|
||||
|
||||
pub fn update_resource(&mut self, name: &str, resource: Resource) -> Result<(), ConfigError> {
|
||||
match (self.resource(name), &resource) {
|
||||
(None, _) => return Err(ConfigError::MissingResource),
|
||||
(Some(ResourceRef::Sql(_)), Resource::Sql(_))
|
||||
| (Some(ResourceRef::ObjectStore(_)), Resource::ObjectStore(_)) => {}
|
||||
_ => return Err(ConfigError::ResourceCategory),
|
||||
let previous = self.resource(name).ok_or(ConfigError::MissingResource)?;
|
||||
if discriminant(previous) != discriminant(&resource) {
|
||||
return Err(ConfigError::ResourceCategory);
|
||||
}
|
||||
self.store_resource(name.to_owned(), resource)
|
||||
}
|
||||
|
||||
pub fn remove_resource(&mut self, name: &str) -> Result<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);
|
||||
}
|
||||
self.clusters
|
||||
self.resources
|
||||
.remove(name)
|
||||
.map(Resource::Sql)
|
||||
.or_else(|| self.object_storage.remove(name).map(Resource::ObjectStore))
|
||||
.ok_or(ConfigError::MissingResource)
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
|
||||
validate_name(&name, "resource")?;
|
||||
match resource {
|
||||
Resource::Sql(cluster) => {
|
||||
cluster.resolve(&self.deployment, Some(&name), self.read_only)?;
|
||||
self.clusters.insert(name, cluster);
|
||||
}
|
||||
Resource::ObjectStore(store) => {
|
||||
store.validate()?;
|
||||
self.object_storage.insert(name, store);
|
||||
}
|
||||
}
|
||||
resource.resolve(&self.deployment, Some(&name), self.read_only)?;
|
||||
self.resources.insert(name, resource);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 thiserror::Error;
|
||||
|
||||
use crate::{ConfigError, DeploymentConfig, Resource};
|
||||
use crate::{
|
||||
Address, ConfigError, DOCUMENTS, DeploymentConfig, ObjectStorage, Resource, SqlCluster,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ConfigFormat {
|
||||
@@ -52,7 +54,10 @@ impl ConfigFormat {
|
||||
|
||||
impl DeploymentConfig {
|
||||
pub fn parse(input: &str, format: ConfigFormat) -> Result<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> {
|
||||
@@ -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)]
|
||||
struct TerraformOutputs {
|
||||
bedrock_resources: Option<TerraformOutput>,
|
||||
|
||||
+48
-98
@@ -2,19 +2,21 @@
|
||||
|
||||
mod catalog;
|
||||
mod driver;
|
||||
mod error;
|
||||
mod format;
|
||||
mod object_storage;
|
||||
mod resource;
|
||||
mod sql;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
pub use catalog::{Resource, ResourceRef};
|
||||
pub use driver::*;
|
||||
pub use error::ConfigError;
|
||||
pub use format::{ConfigFormat, FormatError, ImportFormat};
|
||||
pub use object_storage::ObjectStorage;
|
||||
pub use resource::{ResolvedResource, Resource, ResourceRef};
|
||||
/// Compatibility name for the SQL cluster configuration.
|
||||
pub use sql::SqlCluster as Cluster;
|
||||
pub use sql::{Address, ResolvedSql, SqlCluster, Tls};
|
||||
@@ -22,19 +24,14 @@ pub use sql::{Address, ResolvedSql, SqlCluster, Tls};
|
||||
pub const DOCUMENTS: &str = "documents";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
#[serde(try_from = "format::DeploymentInput")]
|
||||
pub struct DeploymentConfig {
|
||||
pub deployment: String,
|
||||
pub config_version: String,
|
||||
/// Legacy shorthand for sql.documents.
|
||||
pub cluster: Option<String>,
|
||||
/// Named SQL targets that can be bound to entries in `sql`.
|
||||
pub clusters: BTreeMap<String, SqlCluster>,
|
||||
/// SQL role to named cluster.
|
||||
pub sql: BTreeMap<String, String>,
|
||||
pub object_storage: BTreeMap<String, ObjectStorage>,
|
||||
pub resources: BTreeMap<String, Resource>,
|
||||
/// Role to named resource.
|
||||
pub bindings: BTreeMap<String, String>,
|
||||
pub read_only: bool,
|
||||
pub sqlite_path: Address,
|
||||
}
|
||||
|
||||
impl Default for DeploymentConfig {
|
||||
@@ -42,12 +39,9 @@ impl Default for DeploymentConfig {
|
||||
Self {
|
||||
deployment: "default".into(),
|
||||
config_version: "local".into(),
|
||||
cluster: None,
|
||||
clusters: BTreeMap::new(),
|
||||
sql: BTreeMap::new(),
|
||||
object_storage: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
bindings: BTreeMap::new(),
|
||||
read_only: false,
|
||||
sqlite_path: "bedrock.sqlite3".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,106 +51,62 @@ impl Default for DeploymentConfig {
|
||||
pub struct ResolvedDeployment {
|
||||
pub deployment: String,
|
||||
pub config_version: String,
|
||||
pub sql: BTreeMap<String, ResolvedSql>,
|
||||
pub object_storage: BTreeMap<String, ObjectStorage>,
|
||||
resources: BTreeMap<String, ResolvedResource>,
|
||||
bindings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl ResolvedDeployment {
|
||||
pub fn documents(&self) -> Option<&ResolvedSql> {
|
||||
self.sql.get(DOCUMENTS)
|
||||
pub fn resource(&self, name: &str) -> Option<&ResolvedResource> {
|
||||
self.resources.get(name)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("invalid {0} name")]
|
||||
Name(&'static str),
|
||||
#[error("the selected database cluster is not configured")]
|
||||
UnknownCluster,
|
||||
#[error("a cluster must be selected when clusters are configured")]
|
||||
ClusterRequired,
|
||||
#[error("legacy cluster and sql.documents refer to different resources")]
|
||||
ConflictingDocuments,
|
||||
#[error("invalid object storage configuration")]
|
||||
ObjectStorage,
|
||||
#[error("resource already exists")]
|
||||
DuplicateResource,
|
||||
#[error("resource does not exist")]
|
||||
MissingResource,
|
||||
#[error("resource is referenced by a SQL binding")]
|
||||
ResourceInUse,
|
||||
#[error("a resource update must preserve its category")]
|
||||
ResourceCategory,
|
||||
#[error("the database pool size must be greater than zero")]
|
||||
PoolSize,
|
||||
#[error("SQLite does not support a replica list")]
|
||||
SqliteReplicas,
|
||||
#[error("invalid SQLite file path")]
|
||||
SqlitePath,
|
||||
#[error("invalid {0} database URL")]
|
||||
Url(&'static str),
|
||||
pub fn binding(&self, role: &str) -> Option<&ResolvedResource> {
|
||||
self.resource(self.bindings.get(role)?)
|
||||
}
|
||||
|
||||
pub fn bound_resources(&self) -> impl Iterator<Item = (&str, &ResolvedResource)> {
|
||||
self.bindings
|
||||
.iter()
|
||||
.map(|(role, target)| (role.as_str(), &self.resources[target]))
|
||||
}
|
||||
}
|
||||
|
||||
impl DeploymentConfig {
|
||||
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
|
||||
validate_name(&self.deployment, "deployment")?;
|
||||
validate_name(&self.config_version, "config version")?;
|
||||
let mut targets = BTreeMap::new();
|
||||
for (name, cluster) in &self.clusters {
|
||||
validate_name(name, "cluster")?;
|
||||
targets.insert(
|
||||
name.as_str(),
|
||||
cluster.resolve(&self.deployment, Some(name), self.read_only)?,
|
||||
let mut resources = BTreeMap::new();
|
||||
let mut bindings = self.bindings.clone();
|
||||
for (name, resource) in &self.resources {
|
||||
validate_name(name, "resource")?;
|
||||
resources.insert(
|
||||
name.clone(),
|
||||
resource.resolve(&self.deployment, Some(name), self.read_only)?,
|
||||
);
|
||||
}
|
||||
for (name, store) in &self.object_storage {
|
||||
validate_name(name, "object store")?;
|
||||
if self.clusters.contains_key(name) {
|
||||
return Err(ConfigError::DuplicateResource);
|
||||
}
|
||||
store.validate()?;
|
||||
}
|
||||
|
||||
let mut sql = BTreeMap::new();
|
||||
for (role, target) in &self.sql {
|
||||
validate_name(role, "SQL role")?;
|
||||
validate_name(target, "cluster")?;
|
||||
let settings = targets
|
||||
.get(target.as_str())
|
||||
.ok_or(ConfigError::UnknownCluster)?;
|
||||
sql.insert(role.clone(), settings.clone());
|
||||
}
|
||||
if let Some(name) = &self.cluster {
|
||||
validate_name(name, "cluster")?;
|
||||
if self.sql.get(DOCUMENTS).is_some_and(|target| target != name) {
|
||||
return Err(ConfigError::ConflictingDocuments);
|
||||
}
|
||||
let settings = targets
|
||||
.get(name.as_str())
|
||||
.ok_or(ConfigError::UnknownCluster)?;
|
||||
sql.insert(DOCUMENTS.into(), settings.clone());
|
||||
}
|
||||
if sql.is_empty() {
|
||||
if !targets.is_empty() {
|
||||
return Err(ConfigError::ClusterRequired);
|
||||
}
|
||||
let local = SqlCluster {
|
||||
driver: SqlDriver::Sqlite,
|
||||
primary: self.sqlite_path.clone(),
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 1,
|
||||
};
|
||||
sql.insert(
|
||||
DOCUMENTS.into(),
|
||||
local.resolve(&self.deployment, None, self.read_only)?,
|
||||
if resources.is_empty() && bindings.is_empty() {
|
||||
let default = Resource::default_documents();
|
||||
resources.insert(
|
||||
"local".into(),
|
||||
default.resolve(&self.deployment, None, self.read_only)?,
|
||||
);
|
||||
bindings.insert(DOCUMENTS.into(), "local".into());
|
||||
}
|
||||
for (role, target) in &bindings {
|
||||
validate_name(role, "role")?;
|
||||
validate_name(target, "resource")?;
|
||||
if !resources.contains_key(target) {
|
||||
return Err(ConfigError::UnknownBinding {
|
||||
role: role.clone(),
|
||||
target: target.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(ResolvedDeployment {
|
||||
deployment: self.deployment.clone(),
|
||||
config_version: self.config_version.clone(),
|
||||
sql,
|
||||
object_storage: self.object_storage.clone(),
|
||||
resources,
|
||||
bindings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ pub struct 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() {
|
||||
return Err(ConfigError::ObjectStorage);
|
||||
}
|
||||
@@ -29,6 +29,6 @@ impl 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 {
|
||||
pub(crate) fn local(path: Address) -> Self {
|
||||
Self {
|
||||
driver: SqlDriver::Sqlite,
|
||||
primary: path,
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(
|
||||
&self,
|
||||
deployment: &str,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use clusters::{Address, ConfigError, DeploymentConfig, SqlCluster, SqlDriver, Tls};
|
||||
use clusters::{
|
||||
Address, ConfigError, DOCUMENTS, DeploymentConfig, Resource, SqlCluster, SqlDriver, Tls,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn address_debug_formats_the_inner_string() {
|
||||
@@ -11,21 +13,21 @@ fn address_debug_formats_the_inner_string() {
|
||||
#[test]
|
||||
fn named_cluster_requires_matching_addresses() {
|
||||
let mut config = DeploymentConfig {
|
||||
cluster: Some("regional".into()),
|
||||
clusters: BTreeMap::from([(
|
||||
bindings: BTreeMap::from([(DOCUMENTS.into(), "regional".into())]),
|
||||
resources: BTreeMap::from([(
|
||||
"regional".into(),
|
||||
SqlCluster {
|
||||
Resource::Sql(SqlCluster {
|
||||
driver: SqlDriver::Postgres,
|
||||
primary: "postgres://user:secret@primary/bedrock".into(),
|
||||
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
|
||||
tls: Tls::VerifyFull,
|
||||
max_connections: 5,
|
||||
},
|
||||
}),
|
||||
)]),
|
||||
..DeploymentConfig::default()
|
||||
};
|
||||
let resolved = config.resolve().unwrap();
|
||||
let resolved = resolved.documents().unwrap();
|
||||
let resolved = resolved.binding(DOCUMENTS).unwrap().as_sql().unwrap();
|
||||
assert!(
|
||||
resolved
|
||||
.primary
|
||||
@@ -37,8 +39,10 @@ fn named_cluster_requires_matching_addresses() {
|
||||
.connection_string()
|
||||
.ends_with("sslmode=verify-full")
|
||||
);
|
||||
config.clusters.get_mut("regional").unwrap().replicas[0] =
|
||||
"mysql://user:secret@replica/bedrock".into();
|
||||
let Some(Resource::Sql(cluster)) = config.resources.get_mut("regional") else {
|
||||
panic!("expected a SQL resource");
|
||||
};
|
||||
cluster.replicas[0] = "mysql://user:secret@replica/bedrock".into();
|
||||
assert!(matches!(
|
||||
config.resolve(),
|
||||
Err(ConfigError::Url("postgres"))
|
||||
@@ -56,25 +60,57 @@ fn resolves_named_connections_and_round_trips_yaml() {
|
||||
.unwrap();
|
||||
let snapshot = config.resolve().unwrap();
|
||||
assert_eq!(snapshot.config_version, "example-1");
|
||||
assert_eq!(snapshot.documents().unwrap().driver, SqlDriver::Postgres);
|
||||
assert_eq!(snapshot.sql["legacy"].driver, SqlDriver::Mysql);
|
||||
assert_eq!(
|
||||
snapshot.object_storage["attachments"].bucket,
|
||||
snapshot
|
||||
.binding(DOCUMENTS)
|
||||
.unwrap()
|
||||
.as_sql()
|
||||
.unwrap()
|
||||
.driver,
|
||||
SqlDriver::Postgres
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.binding("legacy").unwrap().as_sql().unwrap().driver,
|
||||
SqlDriver::Mysql
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.binding("attachments")
|
||||
.unwrap()
|
||||
.as_object_store()
|
||||
.unwrap()
|
||||
.bucket,
|
||||
"bedrock-attachments"
|
||||
);
|
||||
assert_eq!(snapshot.documents().unwrap().max_connections, 5);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.binding(DOCUMENTS)
|
||||
.unwrap()
|
||||
.as_sql()
|
||||
.unwrap()
|
||||
.max_connections,
|
||||
5
|
||||
);
|
||||
|
||||
let serialized = config.to_yaml().unwrap();
|
||||
let roundtrip = DeploymentConfig::parse(&serialized, ConfigFormat::Yaml)
|
||||
.unwrap()
|
||||
.resolve()
|
||||
.unwrap();
|
||||
assert_eq!(roundtrip.sql["legacy"].driver, SqlDriver::Mysql);
|
||||
assert_eq!(
|
||||
roundtrip
|
||||
.binding("legacy")
|
||||
.unwrap()
|
||||
.as_sql()
|
||||
.unwrap()
|
||||
.driver,
|
||||
SqlDriver::Mysql
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_catalog_atomically_and_preserves_role_references() {
|
||||
use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver, Resource};
|
||||
use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver};
|
||||
|
||||
let mut config =
|
||||
DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap();
|
||||
@@ -84,7 +120,8 @@ fn imports_catalog_atomically_and_preserves_role_references() {
|
||||
ImportFormat::KubernetesConfigMap,
|
||||
)
|
||||
.unwrap();
|
||||
config.sql.insert("documents".into(), "pg-main".into());
|
||||
config.bindings.insert(DOCUMENTS.into(), "pg-main".into());
|
||||
config.bindings.insert("files".into(), "attachments".into());
|
||||
|
||||
let before = config.resource("attachments").unwrap().driver();
|
||||
assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3));
|
||||
@@ -107,6 +144,11 @@ fn imports_catalog_atomically_and_preserves_role_references() {
|
||||
.is_err()
|
||||
);
|
||||
assert!(config.resource("another-bucket").is_none());
|
||||
assert!(matches!(
|
||||
config.remove_resource("attachments"),
|
||||
Err(ConfigError::ResourceInUse)
|
||||
));
|
||||
config.bindings.remove("files");
|
||||
let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else {
|
||||
panic!("expected S3 configuration");
|
||||
};
|
||||
@@ -119,7 +161,71 @@ fn imports_catalog_atomically_and_preserves_role_references() {
|
||||
.update_resource("attachments", Resource::ObjectStore(updated))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
config.resolve().unwrap().object_storage["attachments"].bucket,
|
||||
config
|
||||
.resolve()
|
||||
.unwrap()
|
||||
.resource("attachments")
|
||||
.unwrap()
|
||||
.as_object_store()
|
||||
.unwrap()
|
||||
.bucket,
|
||||
"replaced"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_configuration_is_normalized_at_load() {
|
||||
use clusters::ConfigFormat;
|
||||
|
||||
let config = DeploymentConfig::parse(
|
||||
r#"{
|
||||
"cluster":"east",
|
||||
"clusters":{"east":{"driver":"postgres","primary":"postgres://u@primary/db"}},
|
||||
"object_storage":{"files":{"driver":"s3","bucket":"files","region":"us-east-1"}}
|
||||
}"#,
|
||||
ConfigFormat::Json,
|
||||
)
|
||||
.unwrap();
|
||||
let snapshot = config.resolve().unwrap();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.binding(DOCUMENTS)
|
||||
.unwrap()
|
||||
.as_sql()
|
||||
.unwrap()
|
||||
.driver,
|
||||
SqlDriver::Postgres
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.resource("files")
|
||||
.unwrap()
|
||||
.as_object_store()
|
||||
.unwrap()
|
||||
.bucket,
|
||||
"files"
|
||||
);
|
||||
|
||||
let config =
|
||||
DeploymentConfig::parse("sqlite_path: custom.sqlite3", ConfigFormat::Yaml).unwrap();
|
||||
let snapshot = config.resolve().unwrap();
|
||||
let connection = snapshot.binding(DOCUMENTS).unwrap().as_sql().unwrap();
|
||||
assert!(
|
||||
connection
|
||||
.primary
|
||||
.connection_string()
|
||||
.ends_with("/custom.sqlite3?mode=rwc")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_binding_target_is_rejected_for_any_role() {
|
||||
let mut config = DeploymentConfig::default();
|
||||
config
|
||||
.bindings
|
||||
.insert("attachments".into(), "missing".into());
|
||||
assert!(
|
||||
matches!(config.resolve(), Err(ConfigError::UnknownBinding { role, target })
|
||||
if role == "attachments" && target == "missing")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use clusters::{Address, ConfigError, DeploymentConfig, ResolvedSql, SqlDriver as Driver};
|
||||
use clusters::{
|
||||
Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedSql, SqlDriver as Driver,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
@@ -18,6 +20,8 @@ pub enum ConnectError {
|
||||
Config(#[from] ConfigError),
|
||||
#[error("the documents SQL role is not configured")]
|
||||
MissingDocuments,
|
||||
#[error("the documents role must reference a SQL resource")]
|
||||
InvalidDocuments,
|
||||
#[error(transparent)]
|
||||
Storage(#[from] StorageError),
|
||||
}
|
||||
@@ -102,7 +106,10 @@ pub struct Connection {
|
||||
|
||||
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
|
||||
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> {
|
||||
|
||||
@@ -8,7 +8,7 @@ pub mod sqlite;
|
||||
|
||||
pub use clusters::SqlDriver as Dialect;
|
||||
pub use clusters::{
|
||||
Address, Cluster, ConfigError, DeploymentConfig, SqlCluster, SqlDriver as Driver, Tls,
|
||||
Address, Cluster, ConfigError, DeploymentConfig, Resource, SqlCluster, SqlDriver as Driver, Tls,
|
||||
};
|
||||
pub use common::Error as StorageError;
|
||||
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
|
||||
|
||||
+13
-21
@@ -1,8 +1,8 @@
|
||||
use std::{collections::BTreeMap, env, time::Duration};
|
||||
|
||||
use db::{
|
||||
Connection, DeploymentConfig, Driver, Mutation, ReadPreference, SqlCluster, StorageError, Tls,
|
||||
connect,
|
||||
Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster,
|
||||
StorageError, Tls, connect,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -17,16 +17,16 @@ fn change(id: &str, text: &str) -> Mutation {
|
||||
fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig {
|
||||
DeploymentConfig {
|
||||
deployment: deployment.into(),
|
||||
cluster: Some("test".into()),
|
||||
clusters: BTreeMap::from([(
|
||||
bindings: BTreeMap::from([("documents".into(), "test".into())]),
|
||||
resources: BTreeMap::from([(
|
||||
"test".into(),
|
||||
SqlCluster {
|
||||
Resource::Sql(SqlCluster {
|
||||
driver,
|
||||
primary: url.into(),
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 4,
|
||||
},
|
||||
}),
|
||||
)]),
|
||||
..DeploymentConfig::default()
|
||||
}
|
||||
@@ -118,10 +118,7 @@ async fn check_document_contract(db: &Connection) {
|
||||
async fn sqlite_persists_across_reopening_and_enforces_read_only() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let filename = folder.path().join("bedrock +?#%.sqlite");
|
||||
let mut config = DeploymentConfig {
|
||||
sqlite_path: filename.to_str().unwrap().into(),
|
||||
..DeploymentConfig::default()
|
||||
};
|
||||
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
|
||||
let db = connect(&config).await.unwrap();
|
||||
assert_eq!(db.driver(), Driver::Sqlite);
|
||||
check_document_contract(&db).await;
|
||||
@@ -140,11 +137,8 @@ async fn sqlite_persists_across_reopening_and_enforces_read_only() {
|
||||
async fn sqlite_read_only_startup_does_not_create_a_database() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let filename = folder.path().join("missing.sqlite");
|
||||
let config = DeploymentConfig {
|
||||
read_only: true,
|
||||
sqlite_path: filename.to_str().unwrap().into(),
|
||||
..DeploymentConfig::default()
|
||||
};
|
||||
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
|
||||
config.read_only = true;
|
||||
assert!(connect(&config).await.is_err());
|
||||
assert!(!filename.exists());
|
||||
}
|
||||
@@ -156,12 +150,10 @@ async fn postgres_reads_replicas_and_falls_back_when_behind() {
|
||||
};
|
||||
let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap();
|
||||
let mut config = sql_config(Driver::Postgres, &url, "pg_contract");
|
||||
config
|
||||
.clusters
|
||||
.get_mut("test")
|
||||
.unwrap()
|
||||
.replicas
|
||||
.push(replica_url.clone().into());
|
||||
let Some(Resource::Sql(cluster)) = config.resources.get_mut("test") else {
|
||||
panic!("expected a SQL resource");
|
||||
};
|
||||
cluster.replicas.push(replica_url.clone().into());
|
||||
let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Reference in New Issue
Block a user