Unify backend resources and role bindings in clusters
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user