Skip to main content

camel_component_ws/
bundle.rs

1use std::sync::Arc;
2
3use camel_component_api::{CamelError, ComponentBundle, ComponentRegistrar};
4
5use crate::{WsComponent, WssComponent, config::WsConfig};
6
7pub struct WsBundle {
8    config: WsConfig,
9}
10
11impl ComponentBundle for WsBundle {
12    fn config_key() -> &'static str {
13        "ws"
14    }
15
16    fn from_toml(value: toml::Value) -> Result<Self, CamelError> {
17        let config: WsConfig = value
18            .try_into()
19            .map_err(|e: toml::de::Error| CamelError::Config(e.to_string()))?;
20        Ok(Self { config })
21    }
22
23    fn register_all(self, ctx: &mut dyn ComponentRegistrar) {
24        ctx.register_component_dyn(Arc::new(WsComponent::with_config(self.config.clone())));
25        ctx.register_component_dyn(Arc::new(WssComponent::with_config(self.config)));
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    struct TestRegistrar {
34        schemes: Vec<String>,
35    }
36
37    impl camel_component_api::ComponentRegistrar for TestRegistrar {
38        fn register_component_dyn(
39            &mut self,
40            component: std::sync::Arc<dyn camel_component_api::Component>,
41        ) {
42            self.schemes.push(component.scheme().to_string());
43        }
44    }
45
46    #[test]
47    fn ws_bundle_from_toml_empty_uses_defaults() {
48        let value: toml::Value = toml::from_str("").unwrap();
49        assert!(WsBundle::from_toml(value).is_ok());
50    }
51
52    #[test]
53    fn ws_bundle_registers_expected_schemes() {
54        let bundle = WsBundle::from_toml(toml::Value::Table(toml::map::Map::new())).unwrap();
55        let mut registrar = TestRegistrar { schemes: vec![] };
56
57        bundle.register_all(&mut registrar);
58
59        assert_eq!(registrar.schemes, vec!["ws", "wss"]);
60    }
61
62    #[test]
63    fn ws_bundle_from_toml_returns_error_on_invalid_config() {
64        let mut table = toml::map::Map::new();
65        table.insert(
66            "max_message_size".to_string(),
67            toml::Value::String("not-a-number".to_string()),
68        );
69
70        let result = WsBundle::from_toml(toml::Value::Table(table));
71        assert!(result.is_err(), "expected Err on malformed config");
72        let err_msg = match result {
73            Err(err) => err.to_string(),
74            Ok(_) => panic!("expected Err on malformed config"),
75        };
76        assert!(
77            err_msg.contains("Configuration error"),
78            "expected CamelError::Config, got: {err_msg}"
79        );
80    }
81}