khive_runtime/
channel_section.rs1use std::collections::{btree_map::Entry, BTreeMap};
4use std::fmt;
5use std::sync::Arc;
6
7use serde::{Deserialize, Serialize};
8
9use crate::engine_config::ConfigError;
10use crate::RuntimeError;
11
12#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
17#[serde(transparent)]
18pub struct ChannelSectionConfig {
19 values: BTreeMap<String, toml::Value>,
20}
21
22impl ChannelSectionConfig {
23 pub fn get(&self, name: &str) -> Option<&toml::Value> {
24 self.values.get(name)
25 }
26
27 pub fn iter(&self) -> impl Iterator<Item = (&str, &toml::Value)> {
28 self.values
29 .iter()
30 .map(|(name, value)| (name.as_str(), value))
31 }
32
33 pub fn is_empty(&self) -> bool {
34 self.values.is_empty()
35 }
36
37 pub fn insert(&mut self, name: String, value: toml::Value) -> Option<toml::Value> {
38 self.values.insert(name, value)
39 }
40
41 pub fn validate(&self) -> Result<(), ConfigError> {
43 Ok(())
44 }
45}
46
47impl From<BTreeMap<String, toml::Value>> for ChannelSectionConfig {
48 fn from(values: BTreeMap<String, toml::Value>) -> Self {
49 Self { values }
50 }
51}
52
53pub type ChannelConfigValidator =
57 Arc<dyn Fn(Option<&toml::Value>) -> Result<(), RuntimeError> + Send + Sync>;
58
59#[derive(Clone, Default)]
64pub struct ChannelConfigValidators {
65 validators: BTreeMap<String, ChannelConfigValidator>,
66}
67
68impl fmt::Debug for ChannelConfigValidators {
69 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70 formatter
71 .debug_struct("ChannelConfigValidators")
72 .field("names", &self.validators.keys().collect::<Vec<_>>())
73 .finish()
74 }
75}
76
77impl ChannelConfigValidators {
78 pub fn register(
80 &mut self,
81 name: impl Into<String>,
82 validator: ChannelConfigValidator,
83 ) -> Result<(), RuntimeError> {
84 let name = name.into();
85 if name.is_empty() {
86 return Err(RuntimeError::InvalidInput(
87 "channel component name must not be empty".into(),
88 ));
89 }
90 match self.validators.entry(name) {
91 Entry::Vacant(entry) => {
92 entry.insert(validator);
93 Ok(())
94 }
95 Entry::Occupied(entry) => Err(RuntimeError::InvalidInput(format!(
96 "channel component {:?} is already registered",
97 entry.key()
98 ))),
99 }
100 }
101
102 pub fn is_empty(&self) -> bool {
104 self.validators.is_empty()
105 }
106
107 pub fn validate(&self, section: &ChannelSectionConfig) -> Result<(), RuntimeError> {
110 for (name, validator) in &self.validators {
111 validator(section.get(name))?;
112 }
113 Ok(())
114 }
115}