camel_api/component_metrics.rs
1//! `ComponentMetrics` — lever-gated facade for the uniform
2//! component-operations family (dashboard-observability Task 4.1).
3//!
4//! Components call [`ComponentMetrics::observe`] at their principal
5//! operation boundary. The facade owns two concerns so individual
6//! components do not:
7//!
8//! - **Lever gating:** the `[observability.metrics].components` lever
9//! (default off, metrics-configuration Req 3) suppresses only the
10//! `camel_component_operations_total` family.
11//! - **Unconditional error forwarding:** failures always increment the
12//! non-disableable error family (`camel_errors_total`) as
13//! `increment_errors(component, "e:{component}:{operation}")` — never
14//! lever-gated (metrics-configuration Req 2).
15//!
16//! The lever arrives as a plain `bool` because `camel-api` cannot depend
17//! on `camel-core`, where `MetricsLeversConfig` lives: the construction
18//! site (camel-core, via the `RuntimeObservability` blanket impl)
19//! snapshots the current levers into the facade at build time.
20
21use std::sync::Arc;
22
23use crate::metrics::MetricsCollector;
24
25/// Facade over a [`MetricsCollector`] for uniform component-operation
26/// emission. Construct via `RuntimeObservability::component_metrics()`
27/// or directly in tests.
28pub struct ComponentMetrics {
29 collector: Arc<dyn MetricsCollector>,
30 components_enabled: bool,
31}
32
33impl ComponentMetrics {
34 /// Builds a facade over `collector`; `components_enabled` is the
35 /// snapshot of the `[observability.metrics].components` lever taken
36 /// at construction time.
37 pub fn new(collector: Arc<dyn MetricsCollector>, components_enabled: bool) -> Self {
38 Self {
39 collector,
40 components_enabled,
41 }
42 }
43
44 /// Observes one component operation. `failed` selects the closed-set
45 /// outcome label ("failure"/"success") and, when true, unconditionally
46 /// forwards to the error family with the `e:{component}:{operation}`
47 /// label — error-family emission is never lever-gated.
48 pub fn observe(&self, component: &str, operation: &str, failed: bool) {
49 if failed {
50 // allow-open-label rc-otxh (facade builds the e:{component}:{operation} label per ADR-0012; names bounded at observe() call sites)
51 self.collector
52 .increment_errors(component, &format!("e:{component}:{operation}"));
53 }
54 if self.components_enabled {
55 // allow-open-label rc-gm6s (component/operation: caller-bounded literals through the facade; outcome is a two-literal if/else)
56 self.collector.record_component_operation(
57 component,
58 operation,
59 if failed { "failure" } else { "success" },
60 );
61 }
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68 use crate::metrics::MetricsCollector;
69 use std::sync::{Arc, Mutex};
70 use std::time::Duration;
71
72 /// Recording double capturing error-family and component-op emissions.
73 struct RecordingComponentMetrics {
74 errors: Mutex<Vec<(String, String)>>,
75 ops: Mutex<Vec<(String, String, String)>>,
76 }
77
78 impl RecordingComponentMetrics {
79 fn new() -> Self {
80 Self {
81 errors: Mutex::new(Vec::new()),
82 ops: Mutex::new(Vec::new()),
83 }
84 }
85 }
86
87 impl MetricsCollector for RecordingComponentMetrics {
88 fn record_exchange_duration(&self, _route_id: &str, _duration: Duration) {}
89 fn increment_errors(&self, route_id: &str, error_type: &str) {
90 self.errors
91 .lock()
92 .expect("errors lock")
93 .push((route_id.to_string(), error_type.to_string()));
94 }
95 fn increment_exchanges(&self, _route_id: &str) {}
96 fn set_queue_depth(&self, _queue: &str, _depth: usize) {}
97 fn record_circuit_breaker_change(&self, _route_id: &str, _from: &str, _to: &str) {}
98 fn record_component_operation(&self, component: &str, operation: &str, outcome: &str) {
99 self.ops.lock().expect("ops lock").push((
100 component.to_string(),
101 operation.to_string(),
102 outcome.to_string(),
103 ));
104 }
105 }
106
107 /// Task 4.1: the components lever gates ONLY the component-operations
108 /// family; error-family forwarding is unconditional.
109 #[test]
110 fn facade_gates_components_not_errors() {
111 // Lever OFF: a failed observe forwards to the error family and
112 // records no component-op.
113 let off_collector = Arc::new(RecordingComponentMetrics::new());
114 let off = ComponentMetrics::new(
115 Arc::clone(&off_collector) as Arc<dyn MetricsCollector>,
116 false,
117 );
118 off.observe("redis", "command", true);
119 assert_eq!(
120 off_collector.errors.lock().expect("errors lock").clone(),
121 vec![("redis".to_string(), "e:redis:command".to_string())],
122 "failure must hit the error family with the lever off"
123 );
124 assert!(
125 off_collector.ops.lock().expect("ops lock").is_empty(),
126 "component ops must be suppressed with the lever off"
127 );
128
129 // Lever ON: both outcomes recorded; the failure ALSO increments
130 // errors (error family is never lever-gated).
131 let on_collector = Arc::new(RecordingComponentMetrics::new());
132 let on =
133 ComponentMetrics::new(Arc::clone(&on_collector) as Arc<dyn MetricsCollector>, true);
134 on.observe("redis", "command", false);
135 on.observe("redis", "command", true);
136 assert_eq!(
137 on_collector.ops.lock().expect("ops lock").clone(),
138 vec![
139 (
140 "redis".to_string(),
141 "command".to_string(),
142 "success".to_string()
143 ),
144 (
145 "redis".to_string(),
146 "command".to_string(),
147 "failure".to_string()
148 ),
149 ],
150 "lever on must record both outcomes"
151 );
152 assert_eq!(
153 on_collector.errors.lock().expect("errors lock").clone(),
154 vec![("redis".to_string(), "e:redis:command".to_string())],
155 "failure must still increment errors with the lever on"
156 );
157 }
158}