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#[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    /// Loading preserves every value; component validation happens at activation.
42    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
53/// A component validates its own exact value, or its absence, before activation.
54/// Checks must be pure and idempotent: host preparation and pack activation may
55/// both invoke them. They must not start work or depend on exactly one invocation.
56pub type ChannelConfigValidator =
57    Arc<dyn Fn(Option<&toml::Value>) -> Result<(), RuntimeError> + Send + Sync>;
58
59/// Validators supplied by the host before constructing its pack registry.
60///
61/// Clones retain the same callbacks. Independent registries share no mutable
62/// registration state; callbacks must not start resident work during validation.
63#[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    /// Register one component name without replacing an existing callback.
79    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    /// Whether no component validator is registered.
103    pub fn is_empty(&self) -> bool {
104        self.validators.is_empty()
105    }
106
107    /// Validate registered components in name order, preserving their typed errors.
108    /// Unregistered configuration remains retained and inert.
109    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}