Skip to main content

torvyn_observability/
config.rs

1//! Observability configuration types.
2//!
3//! Controls observability level, tracing sample rates, export targets,
4//! histogram bucket boundaries, and inspection API settings.
5
6use serde::{Deserialize, Serialize};
7use std::path::PathBuf;
8use std::time::Duration;
9use torvyn_types::ObservabilityLevel;
10
11/// Top-level observability configuration.
12///
13/// # Invariants
14/// - `tracing.sample_rate` must be in `[0.0, 1.0]`.
15/// - `tracing.ring_buffer_capacity` must be a power of two and >= 8.
16/// - `metrics.histogram_buckets` must be non-empty and sorted ascending.
17/// - `export.batch_size` must be >= 1.
18///
19/// # Examples
20/// ```
21/// use torvyn_observability::config::ObservabilityConfig;
22///
23/// let config = ObservabilityConfig::default();
24/// assert_eq!(config.level, torvyn_types::ObservabilityLevel::Production);
25/// ```
26#[derive(Clone, Debug, Serialize, Deserialize)]
27pub struct ObservabilityConfig {
28    /// Active observability level.
29    pub level: ObservabilityLevel,
30    /// Tracing configuration.
31    pub tracing: TracingConfig,
32    /// Metrics configuration.
33    pub metrics: MetricsConfig,
34    /// Export configuration.
35    pub export: ExportConfig,
36    /// Inspection API configuration.
37    pub inspection: InspectionConfig,
38    /// Event channel capacity for diagnostic events.
39    /// Default: 8192.
40    pub event_channel_capacity: usize,
41}
42
43/// Tracing subsystem configuration.
44///
45/// Controls sampling rates, ring buffer sizes, and latency thresholds
46/// that trigger trace promotion.
47#[derive(Clone, Debug, Serialize, Deserialize)]
48pub struct TracingConfig {
49    /// Fraction of flows that are fully traced (head-based sampling).
50    /// Range: `[0.0, 1.0]`. Default: 0.01 (1%).
51    pub sample_rate: f64,
52    /// Whether to promote errored flows to full trace.
53    /// Default: true.
54    pub error_promote: bool,
55    /// Latency threshold (ms) above which a flow is promoted to full trace.
56    /// Default: 10 ms.
57    pub latency_promote_threshold_ms: u64,
58    /// Per-flow span ring buffer capacity. Must be power of two.
59    /// Default: 64.
60    pub ring_buffer_capacity: usize,
61}
62
63/// Metrics subsystem configuration.
64#[derive(Clone, Debug, Serialize, Deserialize)]
65pub struct MetricsConfig {
66    /// Whether metrics collection is enabled.
67    /// Default: true.
68    pub enabled: bool,
69    /// Whether to serve Prometheus exposition format on the inspection API.
70    /// Default: true.
71    pub prometheus_enabled: bool,
72    /// Custom histogram bucket boundaries (nanoseconds). If empty, uses defaults.
73    pub histogram_buckets: Vec<u64>,
74}
75
76/// Export configuration for traces and metrics.
77#[derive(Clone, Debug, Serialize, Deserialize)]
78pub struct ExportConfig {
79    /// Export target type.
80    pub target: ExportTarget,
81    /// OTLP endpoint URL (for OTLP targets).
82    pub endpoint: Option<String>,
83    /// Batch size for export.
84    /// Default: 512.
85    pub batch_size: usize,
86    /// Export interval.
87    /// Default: 5 seconds.
88    #[serde(with = "humantime_serde_compat")]
89    pub interval: Duration,
90}
91
92/// Supported export targets.
93#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "kebab-case")]
95pub enum ExportTarget {
96    /// No export. Events stay in memory only.
97    None,
98    /// Structured JSON to stderr.
99    Stdout,
100    /// Append structured JSON to file.
101    File(PathBuf),
102    /// OTLP over HTTP/JSON.
103    OtlpHttp,
104    /// In-process channel (for `torvyn bench`).
105    Channel,
106}
107
108/// Inspection API configuration.
109#[derive(Clone, Debug, Serialize, Deserialize)]
110pub struct InspectionConfig {
111    /// Whether the inspection API is enabled.
112    /// Default: true.
113    pub enabled: bool,
114    /// Bind address. Default: Unix socket.
115    pub bind: InspectionBind,
116    /// Optional bearer token for authentication.
117    pub auth_token: Option<String>,
118}
119
120/// Inspection API binding address.
121#[derive(Clone, Debug, Serialize, Deserialize)]
122#[serde(rename_all = "kebab-case")]
123pub enum InspectionBind {
124    /// Unix domain socket at the given path.
125    Unix(PathBuf),
126    /// TCP socket on localhost at the given port.
127    Tcp(u16),
128}
129
130// ---------------------------------------------------------------------------
131// Defaults
132// ---------------------------------------------------------------------------
133
134impl Default for ObservabilityConfig {
135    fn default() -> Self {
136        Self {
137            level: ObservabilityLevel::Production,
138            tracing: TracingConfig::default(),
139            metrics: MetricsConfig::default(),
140            export: ExportConfig::default(),
141            inspection: InspectionConfig::default(),
142            event_channel_capacity: 8192,
143        }
144    }
145}
146
147impl Default for TracingConfig {
148    fn default() -> Self {
149        Self {
150            sample_rate: 0.01,
151            error_promote: true,
152            latency_promote_threshold_ms: 10,
153            ring_buffer_capacity: 64,
154        }
155    }
156}
157
158impl Default for MetricsConfig {
159    fn default() -> Self {
160        Self {
161            enabled: true,
162            prometheus_enabled: true,
163            histogram_buckets: Vec::new(), // empty => use LATENCY_BUCKETS_NS
164        }
165    }
166}
167
168impl Default for ExportConfig {
169    fn default() -> Self {
170        Self {
171            target: ExportTarget::None,
172            endpoint: None,
173            batch_size: 512,
174            interval: Duration::from_secs(5),
175        }
176    }
177}
178
179impl Default for InspectionConfig {
180    fn default() -> Self {
181        Self {
182            enabled: true,
183            bind: InspectionBind::Tcp(9091),
184            auth_token: None,
185        }
186    }
187}
188
189// ---------------------------------------------------------------------------
190// Validation
191// ---------------------------------------------------------------------------
192
193/// Errors encountered when validating an [`ObservabilityConfig`].
194#[derive(Clone, Debug, PartialEq)]
195pub enum ConfigValidationError {
196    /// Sample rate is outside [0.0, 1.0].
197    InvalidSampleRate(f64),
198    /// Ring buffer capacity is not a power of two or is less than 8.
199    InvalidRingBufferCapacity(usize),
200    /// Histogram buckets are not sorted ascending or are empty when custom.
201    InvalidHistogramBuckets,
202    /// Batch size is zero.
203    ZeroBatchSize,
204    /// Export interval is zero.
205    ZeroExportInterval,
206    /// OTLP target specified but no endpoint provided.
207    MissingOtlpEndpoint,
208}
209
210impl std::fmt::Display for ConfigValidationError {
211    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        match self {
213            Self::InvalidSampleRate(r) => {
214                write!(f, "sample_rate {r} is outside valid range [0.0, 1.0]")
215            }
216            Self::InvalidRingBufferCapacity(c) => {
217                write!(
218                    f,
219                    "ring_buffer_capacity {c} must be a power of two and >= 8"
220                )
221            }
222            Self::InvalidHistogramBuckets => {
223                write!(
224                    f,
225                    "histogram_buckets must be non-empty and sorted ascending"
226                )
227            }
228            Self::ZeroBatchSize => write!(f, "export batch_size must be >= 1"),
229            Self::ZeroExportInterval => write!(f, "export interval must be > 0"),
230            Self::MissingOtlpEndpoint => {
231                write!(f, "OTLP export target requires an endpoint URL")
232            }
233        }
234    }
235}
236
237impl std::error::Error for ConfigValidationError {}
238
239impl ObservabilityConfig {
240    /// Validate the configuration, returning all errors found.
241    ///
242    /// # COLD PATH — called once at startup.
243    pub fn validate(&self) -> Result<(), Vec<ConfigValidationError>> {
244        let mut errors = Vec::new();
245
246        if !(0.0..=1.0).contains(&self.tracing.sample_rate) {
247            errors.push(ConfigValidationError::InvalidSampleRate(
248                self.tracing.sample_rate,
249            ));
250        }
251
252        let cap = self.tracing.ring_buffer_capacity;
253        if cap < 8 || !cap.is_power_of_two() {
254            errors.push(ConfigValidationError::InvalidRingBufferCapacity(cap));
255        }
256
257        if !self.metrics.histogram_buckets.is_empty() {
258            let sorted = self
259                .metrics
260                .histogram_buckets
261                .windows(2)
262                .all(|w| w[0] < w[1]);
263            if !sorted {
264                errors.push(ConfigValidationError::InvalidHistogramBuckets);
265            }
266        }
267
268        if self.export.batch_size == 0 {
269            errors.push(ConfigValidationError::ZeroBatchSize);
270        }
271
272        if self.export.interval.is_zero() {
273            errors.push(ConfigValidationError::ZeroExportInterval);
274        }
275
276        if self.export.target == ExportTarget::OtlpHttp && self.export.endpoint.is_none() {
277            errors.push(ConfigValidationError::MissingOtlpEndpoint);
278        }
279
280        if errors.is_empty() {
281            Ok(())
282        } else {
283            Err(errors)
284        }
285    }
286}
287
288/// Serde helper for Duration as milliseconds.
289mod humantime_serde_compat {
290    use serde::{self, Deserialize, Deserializer, Serializer};
291    use std::time::Duration;
292
293    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
294    where
295        S: Serializer,
296    {
297        serializer.serialize_u64(duration.as_millis() as u64)
298    }
299
300    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
301    where
302        D: Deserializer<'de>,
303    {
304        let ms = u64::deserialize(deserializer)?;
305        Ok(Duration::from_millis(ms))
306    }
307}
308
309// ---------------------------------------------------------------------------
310// Tests
311// ---------------------------------------------------------------------------
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn test_default_config_is_valid() {
319        let config = ObservabilityConfig::default();
320        assert!(config.validate().is_ok());
321    }
322
323    #[test]
324    fn test_invalid_sample_rate_above_one() {
325        let mut config = ObservabilityConfig::default();
326        config.tracing.sample_rate = 1.5;
327        let errs = config.validate().unwrap_err();
328        assert!(errs
329            .iter()
330            .any(|e| matches!(e, ConfigValidationError::InvalidSampleRate(_))));
331    }
332
333    #[test]
334    fn test_invalid_sample_rate_negative() {
335        let mut config = ObservabilityConfig::default();
336        config.tracing.sample_rate = -0.1;
337        let errs = config.validate().unwrap_err();
338        assert!(errs
339            .iter()
340            .any(|e| matches!(e, ConfigValidationError::InvalidSampleRate(_))));
341    }
342
343    #[test]
344    fn test_invalid_ring_buffer_not_power_of_two() {
345        let mut config = ObservabilityConfig::default();
346        config.tracing.ring_buffer_capacity = 100;
347        let errs = config.validate().unwrap_err();
348        assert!(errs
349            .iter()
350            .any(|e| matches!(e, ConfigValidationError::InvalidRingBufferCapacity(_))));
351    }
352
353    #[test]
354    fn test_invalid_ring_buffer_too_small() {
355        let mut config = ObservabilityConfig::default();
356        config.tracing.ring_buffer_capacity = 4;
357        let errs = config.validate().unwrap_err();
358        assert!(errs
359            .iter()
360            .any(|e| matches!(e, ConfigValidationError::InvalidRingBufferCapacity(_))));
361    }
362
363    #[test]
364    fn test_invalid_histogram_buckets_unsorted() {
365        let mut config = ObservabilityConfig::default();
366        config.metrics.histogram_buckets = vec![100, 50, 200];
367        let errs = config.validate().unwrap_err();
368        assert!(errs
369            .iter()
370            .any(|e| matches!(e, ConfigValidationError::InvalidHistogramBuckets)));
371    }
372
373    #[test]
374    fn test_zero_batch_size() {
375        let mut config = ObservabilityConfig::default();
376        config.export.batch_size = 0;
377        let errs = config.validate().unwrap_err();
378        assert!(errs
379            .iter()
380            .any(|e| matches!(e, ConfigValidationError::ZeroBatchSize)));
381    }
382
383    #[test]
384    fn test_missing_otlp_endpoint() {
385        let mut config = ObservabilityConfig::default();
386        config.export.target = ExportTarget::OtlpHttp;
387        config.export.endpoint = None;
388        let errs = config.validate().unwrap_err();
389        assert!(errs
390            .iter()
391            .any(|e| matches!(e, ConfigValidationError::MissingOtlpEndpoint)));
392    }
393
394    #[test]
395    fn test_valid_custom_histogram_buckets() {
396        let mut config = ObservabilityConfig::default();
397        config.metrics.histogram_buckets = vec![100, 500, 1000, 5000];
398        assert!(config.validate().is_ok());
399    }
400
401    #[test]
402    fn test_export_target_serde_roundtrip() {
403        let target = ExportTarget::OtlpHttp;
404        let json = serde_json::to_string(&target).unwrap();
405        let parsed: ExportTarget = serde_json::from_str(&json).unwrap();
406        assert_eq!(parsed, target);
407    }
408
409    #[test]
410    fn test_config_validation_error_display() {
411        let err = ConfigValidationError::InvalidSampleRate(2.0);
412        let msg = format!("{err}");
413        assert!(msg.contains("2"));
414        assert!(msg.contains("sample_rate"));
415    }
416
417    #[test]
418    fn test_multiple_validation_errors() {
419        let mut config = ObservabilityConfig::default();
420        config.tracing.sample_rate = 5.0;
421        config.export.batch_size = 0;
422        let errs = config.validate().unwrap_err();
423        assert!(errs.len() >= 2);
424    }
425}