219 lines
7.5 KiB
Rust
219 lines
7.5 KiB
Rust
use std::{collections::BTreeMap, path::Path};
|
|
|
|
use serde::Deserialize;
|
|
use serde::de::DeserializeOwned;
|
|
use thiserror::Error;
|
|
|
|
use crate::{
|
|
Address, ConfigError, DOCUMENTS, DeploymentConfig, ObjectStorage, Resource, SqlCluster,
|
|
};
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub enum ConfigFormat {
|
|
Yaml,
|
|
Toml,
|
|
/// Compatibility with previously published deployment files.
|
|
Json,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub enum ImportFormat {
|
|
Catalog(ConfigFormat),
|
|
/// The bedrock_resources output of terraform output -json.
|
|
TerraformOutputs,
|
|
/// A ConfigMap carrying a catalog in data["bedrock-resources.yaml"].
|
|
KubernetesConfigMap,
|
|
}
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum FormatError {
|
|
#[error("configuration filename must end in .yaml, .yml, .toml or .json")]
|
|
FileExtension,
|
|
#[error("could not read the deployment configuration: {0}")]
|
|
Io(#[from] std::io::Error),
|
|
// Parser errors may quote connection strings or credentials.
|
|
#[error("invalid {0} configuration document")]
|
|
Parse(&'static str),
|
|
#[error("could not serialize the deployment configuration as YAML")]
|
|
Serialize,
|
|
#[error("import does not contain a Bedrock resource catalog")]
|
|
MissingCatalog,
|
|
#[error("publishable deployment configuration requires a valid catalog: {0}")]
|
|
Config(#[from] ConfigError),
|
|
}
|
|
|
|
impl ConfigFormat {
|
|
fn parse<T: DeserializeOwned>(self, input: &str) -> Result<T, FormatError> {
|
|
match self {
|
|
Self::Yaml => serde_saphyr::from_str(input).map_err(|_| FormatError::Parse("YAML")),
|
|
Self::Toml => toml::from_str(input).map_err(|_| FormatError::Parse("TOML")),
|
|
Self::Json => serde_json::from_str(input).map_err(|_| FormatError::Parse("JSON")),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl DeploymentConfig {
|
|
pub fn parse(input: &str, format: ConfigFormat) -> Result<Self, FormatError> {
|
|
format
|
|
.parse::<DeploymentInput>(input)?
|
|
.try_into()
|
|
.map_err(Into::into)
|
|
}
|
|
|
|
pub fn load(path: impl AsRef<Path>) -> Result<Self, FormatError> {
|
|
let path = path.as_ref();
|
|
let format = match path.extension().and_then(|value| value.to_str()) {
|
|
Some("yaml" | "yml") => ConfigFormat::Yaml,
|
|
Some("toml") => ConfigFormat::Toml,
|
|
Some("json") => ConfigFormat::Json,
|
|
_ => return Err(FormatError::FileExtension),
|
|
};
|
|
Self::parse(&std::fs::read_to_string(path)?, format)
|
|
}
|
|
|
|
/// Serializes the configuration, including any credentials in connection strings.
|
|
pub fn to_yaml(&self) -> Result<String, FormatError> {
|
|
self.resolve()?;
|
|
serde_saphyr::to_string(self).map_err(|_| FormatError::Serialize)
|
|
}
|
|
|
|
/// Imports an inventory atomically. Deployment roles are assigned separately.
|
|
pub fn import_resources(
|
|
&mut self,
|
|
input: &str,
|
|
format: ImportFormat,
|
|
) -> Result<(), FormatError> {
|
|
let resources: BTreeMap<String, Resource> = match format {
|
|
ImportFormat::Catalog(format) => format.parse(input)?,
|
|
ImportFormat::TerraformOutputs => {
|
|
let exports: TerraformOutputs = ConfigFormat::Json.parse(input)?;
|
|
exports
|
|
.bedrock_resources
|
|
.ok_or(FormatError::MissingCatalog)?
|
|
.value
|
|
}
|
|
ImportFormat::KubernetesConfigMap => {
|
|
let manifest: ConfigMap = ConfigFormat::Yaml.parse(input)?;
|
|
if manifest.kind != "ConfigMap" || manifest.api_version != "v1" {
|
|
return Err(FormatError::MissingCatalog);
|
|
}
|
|
let catalog = manifest
|
|
.data
|
|
.get("bedrock-resources.yaml")
|
|
.ok_or(FormatError::MissingCatalog)?;
|
|
ConfigFormat::Yaml.parse(catalog)?
|
|
}
|
|
};
|
|
let mut candidate = self.clone();
|
|
for (name, resource) in resources {
|
|
candidate.insert_resource(name, resource)?;
|
|
}
|
|
*self = candidate;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
// 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>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct TerraformOutput {
|
|
value: BTreeMap<String, Resource>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct ConfigMap {
|
|
api_version: String,
|
|
kind: String,
|
|
data: BTreeMap<String, String>,
|
|
}
|