use std::collections::{btree_map::Entry, BTreeMap};
use std::fmt;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::engine_config::ConfigError;
use crate::RuntimeError;
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(transparent)]
pub struct ChannelSectionConfig {
values: BTreeMap<String, toml::Value>,
}
impl ChannelSectionConfig {
pub fn get(&self, name: &str) -> Option<&toml::Value> {
self.values.get(name)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &toml::Value)> {
self.values
.iter()
.map(|(name, value)| (name.as_str(), value))
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn insert(&mut self, name: String, value: toml::Value) -> Option<toml::Value> {
self.values.insert(name, value)
}
pub fn validate(&self) -> Result<(), ConfigError> {
Ok(())
}
}
impl From<BTreeMap<String, toml::Value>> for ChannelSectionConfig {
fn from(values: BTreeMap<String, toml::Value>) -> Self {
Self { values }
}
}
pub type ChannelConfigValidator =
Arc<dyn Fn(Option<&toml::Value>) -> Result<(), RuntimeError> + Send + Sync>;
#[derive(Clone, Default)]
pub struct ChannelConfigValidators {
validators: BTreeMap<String, ChannelConfigValidator>,
}
impl fmt::Debug for ChannelConfigValidators {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ChannelConfigValidators")
.field("names", &self.validators.keys().collect::<Vec<_>>())
.finish()
}
}
impl ChannelConfigValidators {
pub fn register(
&mut self,
name: impl Into<String>,
validator: ChannelConfigValidator,
) -> Result<(), RuntimeError> {
let name = name.into();
if name.is_empty() {
return Err(RuntimeError::InvalidInput(
"channel component name must not be empty".into(),
));
}
match self.validators.entry(name) {
Entry::Vacant(entry) => {
entry.insert(validator);
Ok(())
}
Entry::Occupied(entry) => Err(RuntimeError::InvalidInput(format!(
"channel component {:?} is already registered",
entry.key()
))),
}
}
pub fn is_empty(&self) -> bool {
self.validators.is_empty()
}
pub fn validate(&self, section: &ChannelSectionConfig) -> Result<(), RuntimeError> {
for (name, validator) in &self.validators {
validator(section.get(name))?;
}
Ok(())
}
}