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, Default, PartialEq, Deserialize, Serialize)]
20#[serde(transparent)]
21pub struct ChannelSectionConfig {
22 values: BTreeMap<String, toml::Value>,
23}
24
25impl fmt::Debug for ChannelSectionConfig {
26 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27 formatter
28 .debug_struct("ChannelSectionConfig")
29 .field("names", &self.values.keys().collect::<Vec<_>>())
30 .finish()
31 }
32}
33
34impl ChannelSectionConfig {
35 pub fn get(&self, name: &str) -> Option<&toml::Value> {
36 self.values.get(name)
37 }
38
39 pub fn iter(&self) -> impl Iterator<Item = (&str, &toml::Value)> {
40 self.values
41 .iter()
42 .map(|(name, value)| (name.as_str(), value))
43 }
44
45 pub fn is_empty(&self) -> bool {
46 self.values.is_empty()
47 }
48
49 pub fn insert(&mut self, name: String, value: toml::Value) -> Option<toml::Value> {
50 self.values.insert(name, value)
51 }
52
53 pub fn validate(&self) -> Result<(), ConfigError> {
55 Ok(())
56 }
57}
58
59impl From<BTreeMap<String, toml::Value>> for ChannelSectionConfig {
60 fn from(values: BTreeMap<String, toml::Value>) -> Self {
61 Self { values }
62 }
63}
64
65pub type ChannelConfigValidator =
69 Arc<dyn Fn(Option<&toml::Value>) -> Result<(), RuntimeError> + Send + Sync>;
70
71#[derive(Clone, Default)]
76pub struct ChannelConfigValidators {
77 validators: BTreeMap<String, ChannelConfigValidator>,
78}
79
80impl fmt::Debug for ChannelConfigValidators {
81 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82 formatter
83 .debug_struct("ChannelConfigValidators")
84 .field("names", &self.validators.keys().collect::<Vec<_>>())
85 .finish()
86 }
87}
88
89impl ChannelConfigValidators {
90 pub fn register(
92 &mut self,
93 name: impl Into<String>,
94 validator: ChannelConfigValidator,
95 ) -> Result<(), RuntimeError> {
96 let name = name.into();
97 if name.is_empty() {
98 return Err(RuntimeError::InvalidInput(
99 "channel component name must not be empty".into(),
100 ));
101 }
102 match self.validators.entry(name) {
103 Entry::Vacant(entry) => {
104 entry.insert(validator);
105 Ok(())
106 }
107 Entry::Occupied(entry) => Err(RuntimeError::InvalidInput(format!(
108 "channel component {:?} is already registered",
109 entry.key()
110 ))),
111 }
112 }
113
114 pub fn is_empty(&self) -> bool {
116 self.validators.is_empty()
117 }
118
119 pub fn validate(&self, section: &ChannelSectionConfig) -> Result<(), RuntimeError> {
122 for (name, validator) in &self.validators {
123 validator(section.get(name))?;
124 }
125 Ok(())
126 }
127}