Skip to main content

khive_runtime/
channel_section.rs

1//! Opaque channel configuration and instance-bound component validation.
2
3use 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/// Values under `[channel]`, keyed by the component's exact registered name.
13///
14/// Unknown names are retained without effect. Only a registered component
15/// interprets its value; a value alone never starts a component or installs a route.
16///
17/// `Debug` prints component names only: a value is the component's own
18/// configuration and may hold credentials.
19#[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    /// Loading preserves every value; component validation happens at activation.
54    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
65/// A component validates its own exact value, or its absence, before activation.
66/// Checks must be pure and idempotent: host preparation and pack activation may
67/// both invoke them. They must not start work or depend on exactly one invocation.
68pub type ChannelConfigValidator =
69    Arc<dyn Fn(Option<&toml::Value>) -> Result<(), RuntimeError> + Send + Sync>;
70
71/// Validators supplied by the host before constructing its pack registry.
72///
73/// Clones retain the same callbacks. Independent registries share no mutable
74/// registration state; callbacks must not start resident work during validation.
75#[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    /// Register one component name without replacing an existing callback.
91    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    /// Whether no component validator is registered.
115    pub fn is_empty(&self) -> bool {
116        self.validators.is_empty()
117    }
118
119    /// Validate registered components in name order, preserving their typed errors.
120    /// Unregistered configuration remains retained and inert.
121    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}