Skip to main content

camel_core/shared/observability/domain/
config.rs

1use camel_api::ComponentMetricsLevers;
2use serde::{Deserialize, Deserializer};
3
4/// Configuration for the Tracer EIP (Enterprise Integration Pattern).
5///
6/// This struct defines how message tracing should be performed throughout
7/// Camel routes. Use `CamelContext::set_tracer_config` to apply configuration
8/// programmatically, or configure via `Camel.toml` as shown in the module documentation.
9#[derive(Clone, Debug, Default)]
10pub struct TracerConfig {
11    /// SPAN enablement (metrics-configuration Req 1: `tracer.enabled` gates
12    /// spans ONLY). Explicit values win over the "otel/prometheus imply
13    /// tracing" rule in `effective_tracer_config` (camel-config), in both
14    /// directions.
15    pub enabled: bool,
16
17    /// Whether `enabled` was explicitly present at the serde boundary.
18    ///
19    /// Not read from input keys: the custom `Deserialize` impl below sets it
20    /// from the presence/absence of the `enabled` key, so it is skipped by
21    /// every serde path. Explicit values win over the "otel/prometheus imply
22    /// tracing" rule in `effective_tracer_config` (camel-config), in both
23    /// directions.
24    pub tracing_enabled_explicit: bool,
25
26    /// PIPELINE enablement: whether routes are wrapped with the observability
27    /// adapters at all. Unlike `enabled`, this is not a TOML key — the
28    /// effective-config assembly (camel-config) raises it whenever an
29    /// exporter (otel/prometheus) or tracing itself is active, because the
30    /// pipeline carries the metric families incl. the non-disableable error
31    /// family (metrics-collection-wiring MODIFIED requirement). Programmatic
32    /// users leave it `false` and pipeline wrapping follows `enabled`.
33    pub pipeline_enabled: bool,
34
35    pub detail_level: DetailLevel,
36
37    pub outputs: TracerOutputs,
38
39    /// Metric-family levers (`[observability.metrics]`). Not a
40    /// `[observability.tracer]` key: the levers deserialize at their own
41    /// table and camel-config attaches them here during effective-config
42    /// assembly, so the tracer serde boundary below never reads them.
43    pub metrics_levers: MetricsLeversConfig,
44}
45
46/// Deserializes `TracerConfig` with serde-boundary detection for `enabled`:
47/// an absent key means "not explicitly set" (`enabled = false`,
48/// `tracing_enabled_explicit = false`), while any explicit `enabled` value
49/// keeps the flag set so callers can honor it over implied enabling.
50///
51/// The intermediate `Raw` struct mirrors the public field set and its serde
52/// attributes (`#[serde(default)]` behavior on other fields is unchanged).
53impl<'de> Deserialize<'de> for TracerConfig {
54    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
55    where
56        D: Deserializer<'de>,
57    {
58        #[derive(Deserialize)]
59        struct Raw {
60            #[serde(default)]
61            enabled: Option<bool>,
62            #[serde(default = "default_detail_level")]
63            detail_level: DetailLevel,
64            #[serde(default)]
65            outputs: TracerOutputs,
66        }
67
68        let raw = Raw::deserialize(deserializer)?;
69        Ok(Self {
70            enabled: raw.enabled.unwrap_or(false),
71            tracing_enabled_explicit: raw.enabled.is_some(),
72            pipeline_enabled: false,
73            detail_level: raw.detail_level,
74            outputs: raw.outputs,
75            metrics_levers: MetricsLeversConfig::default(),
76        })
77    }
78}
79
80#[derive(Debug, Clone, Deserialize, Default)]
81pub struct TracerOutputs {
82    #[serde(default)]
83    pub stdout: StdoutOutput,
84
85    #[serde(default)]
86    pub file: Option<FileOutput>,
87}
88
89#[derive(Debug, Clone, Deserialize)]
90pub struct StdoutOutput {
91    #[serde(default = "default_true")]
92    pub enabled: bool,
93
94    #[serde(default = "default_format")]
95    pub format: OutputFormat,
96}
97
98impl Default for StdoutOutput {
99    fn default() -> Self {
100        Self {
101            enabled: true,
102            format: OutputFormat::Json,
103        }
104    }
105}
106
107#[derive(Debug, Clone, Deserialize)]
108pub struct FileOutput {
109    pub enabled: bool,
110    pub path: String,
111    #[serde(default = "default_format")]
112    pub format: OutputFormat,
113}
114
115/// Controls the level of detail captured in trace spans.
116///
117/// Each variant progressively adds more fields to the trace output:
118///
119/// - `Minimal`: Includes the core span attributes (correlation_id, route_id,
120///   and step_index). `duration_ms` is a `camel_tracer` log field at
121///   every detail level, not a span attribute.
122/// - `Medium`: Includes Minimal fields plus headers_count, body_type, has_error,
123///   and output_body_type
124/// - `Full`: Includes all fields from Minimal and Medium plus up to 3 message headers
125#[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq, PartialOrd, Ord)]
126#[serde(rename_all = "lowercase")]
127pub enum DetailLevel {
128    #[default]
129    Minimal,
130    Medium,
131    Full,
132}
133
134#[derive(Debug, Clone, Deserialize, Default)]
135#[serde(rename_all = "lowercase")]
136pub enum OutputFormat {
137    #[default]
138    Json,
139    Plain,
140}
141
142/// Metric-family levers for `[observability.metrics]` in Camel.toml
143/// (dashboard-observability D3).
144///
145/// A non-error family flows only when `enabled && <family>`, where
146/// `<family>` is `exchange`, `duration`, or `components`.
147/// `component_overrides` narrows the component-operations family per
148/// component: a component without an override inherits `components`, and
149/// the master `enabled` switch is applied last, so it always wins. No lever
150/// exists for the error family — `camel_errors_total` is structurally
151/// non-disableable (metrics-configuration Req 2).
152#[derive(Clone, Debug, PartialEq)]
153pub struct MetricsLeversConfig {
154    pub enabled: bool,
155    pub exchange: bool,
156    pub duration: bool,
157    pub components: bool,
158    /// Per-component enablement for the component-operations family,
159    /// keyed by component name. An absent key inherits `components`.
160    pub component_overrides: std::collections::BTreeMap<String, bool>,
161}
162
163impl MetricsLeversConfig {
164    /// Whether the exchanges counter family may flow.
165    pub fn exchanges_enabled(&self) -> bool {
166        self.enabled && self.exchange
167    }
168
169    /// Whether the duration histogram family may flow.
170    pub fn durations_enabled(&self) -> bool {
171        self.enabled && self.duration
172    }
173
174    /// Whether the uniform component-operations counter family may flow
175    /// (`camel_component_operations_total`; the error family is never
176    /// gated by any lever).
177    pub fn components_enabled(&self) -> bool {
178        self.enabled && self.components
179    }
180
181    /// Whether the component-operations family may flow for `component`.
182    ///
183    /// Precedence: a per-component override wins over `components`; an
184    /// absent override inherits `components`; the master `enabled` switch
185    /// applies last and can veto every component.
186    pub fn component_enabled(&self, component: &str) -> bool {
187        self.enabled
188            && self
189                .component_overrides
190                .get(component)
191                .copied()
192                .unwrap_or(self.components)
193    }
194
195    /// Snapshots the component-operations levers into the scoped identity
196    /// handed to components through
197    /// [`ComponentContext::component_metric_levers`](camel_component_api::ComponentContext::component_metric_levers).
198    pub fn component_metrics_levers(&self) -> ComponentMetricsLevers {
199        ComponentMetricsLevers::new(
200            self.enabled,
201            self.components,
202            self.component_overrides.clone(),
203        )
204    }
205}
206
207impl Default for MetricsLeversConfig {
208    fn default() -> Self {
209        Self {
210            enabled: true,
211            exchange: true,
212            duration: true,
213            components: false,
214            component_overrides: std::collections::BTreeMap::new(),
215        }
216    }
217}
218
219/// Deserializes `MetricsLeversConfig` via a `Raw` intermediate with
220/// `Option<bool>` fields so an absent table and an absent key both mean
221/// "default" (same serde-boundary technique as `TracerConfig`). Unknown
222/// keys are denied, consistent with the sibling observability tables.
223impl<'de> Deserialize<'de> for MetricsLeversConfig {
224    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225    where
226        D: Deserializer<'de>,
227    {
228        #[derive(Deserialize)]
229        #[serde(deny_unknown_fields)]
230        struct Raw {
231            #[serde(default)]
232            enabled: Option<bool>,
233            #[serde(default)]
234            exchange: Option<bool>,
235            #[serde(default)]
236            duration: Option<bool>,
237            #[serde(default)]
238            components: Option<bool>,
239            #[serde(default)]
240            component_overrides: Option<std::collections::BTreeMap<String, bool>>,
241        }
242
243        let raw = Raw::deserialize(deserializer)?;
244        Ok(Self {
245            enabled: raw.enabled.unwrap_or(true),
246            exchange: raw.exchange.unwrap_or(true),
247            duration: raw.duration.unwrap_or(true),
248            components: raw.components.unwrap_or(false),
249            component_overrides: raw.component_overrides.unwrap_or_default(),
250        })
251    }
252}
253
254fn default_detail_level() -> DetailLevel {
255    DetailLevel::Minimal
256}
257fn default_format() -> OutputFormat {
258    OutputFormat::Json
259}
260fn default_true() -> bool {
261    true
262}
263
264#[cfg(test)]
265mod tests {
266    use std::collections::BTreeMap;
267
268    use super::*;
269
270    #[test]
271    fn metrics_levers_precedence_matrix() {
272        let cases = [
273            (false, None, false),
274            (false, Some(false), false),
275            (false, Some(true), true),
276            (true, None, true),
277            (true, Some(false), false),
278            (true, Some(true), true),
279        ];
280
281        for (components, override_value, expected) in cases {
282            let mut overrides = BTreeMap::new();
283            if let Some(value) = override_value {
284                overrides.insert("http".to_string(), value);
285            }
286            let levers = MetricsLeversConfig {
287                enabled: true,
288                exchange: true,
289                duration: true,
290                components,
291                component_overrides: overrides,
292            };
293            assert_eq!(
294                levers.component_enabled("http"),
295                expected,
296                "components={components}, override={override_value:?}"
297            );
298        }
299    }
300
301    #[test]
302    fn metrics_levers_master_switch_beats_override() {
303        let mut overrides = BTreeMap::new();
304        overrides.insert("http".to_string(), true);
305        let levers = MetricsLeversConfig {
306            enabled: false,
307            exchange: true,
308            duration: true,
309            components: false,
310            component_overrides: overrides,
311        };
312        assert!(!levers.component_enabled("http"));
313    }
314
315    #[test]
316    fn metrics_levers_defaults_have_no_overrides() {
317        let levers = MetricsLeversConfig::default();
318        assert!(levers.component_overrides.is_empty());
319        assert!(!levers.component_enabled("http"));
320    }
321
322    #[test]
323    fn metrics_levers_deserializes_component_overrides() {
324        let levers: MetricsLeversConfig = serde_json::from_str(
325            r#"{"enabled":true,"components":false,"component_overrides":{"http":true,"kafka":false}}"#,
326        )
327        .unwrap();
328
329        assert_eq!(levers.component_overrides.len(), 2);
330        assert!(levers.component_enabled("http"));
331        assert!(!levers.component_enabled("kafka"));
332    }
333
334    #[test]
335    fn metrics_levers_absent_override_inherits_components() {
336        let levers: MetricsLeversConfig = serde_json::from_str(r#"{"components":true}"#).unwrap();
337        assert!(levers.component_enabled("http"));
338    }
339
340    #[test]
341    fn metrics_levers_rejects_unknown_keys() {
342        let result: Result<MetricsLeversConfig, _> =
343            serde_json::from_str(r#"{"component_override":{"http":true}}"#);
344        assert!(result.is_err());
345    }
346
347    #[test]
348    fn tracer_config_defaults_are_stable() {
349        let cfg = TracerConfig::default();
350        assert!(!cfg.enabled);
351        assert_eq!(cfg.detail_level, DetailLevel::Minimal);
352        assert!(cfg.outputs.stdout.enabled);
353        assert!(matches!(cfg.outputs.stdout.format, OutputFormat::Json));
354        assert!(cfg.outputs.file.is_none());
355    }
356
357    #[test]
358    fn tracer_config_deserializes_lowercase_enums() {
359        let cfg: TracerConfig = serde_json::from_str(
360            r#"{
361  "enabled": true,
362  "detail_level": "full",
363  "outputs": {
364    "stdout": { "enabled": false, "format": "plain" },
365    "file": { "enabled": true, "path": "/tmp/trace.log", "format": "json" }
366  }
367}"#,
368        )
369        .unwrap();
370
371        assert!(cfg.enabled);
372        assert_eq!(cfg.detail_level, DetailLevel::Full);
373        assert!(!cfg.outputs.stdout.enabled);
374        assert!(matches!(cfg.outputs.stdout.format, OutputFormat::Plain));
375        assert_eq!(cfg.outputs.file.as_ref().unwrap().path, "/tmp/trace.log");
376    }
377}