juncture-tracing 0.2.0

OpenTelemetry integration and tracing for Juncture applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Test utilities for metrics and tracing
//!
//! This module provides test helpers for collecting and asserting on metrics
//! in integration tests.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Test metrics collector for use in integration tests
///
/// A simple in-memory metrics collector that records counter increments,
/// histogram values, and gauge settings for test assertions.
///
/// # Examples
///
/// ```
/// use juncture_tracing::test_utils::TestMetricsCollector;
///
/// let metrics = TestMetricsCollector::new();
/// metrics.increment_counter("test.counter", 1);
/// metrics.record_histogram("test.histogram", 42.0);
/// metrics.set_gauge("test.gauge", 100.0);
///
/// assert_eq!(metrics.get_counter("test.counter"), 1);
/// assert_eq!(metrics.get_histogram_values("test.histogram"), vec![42.0]);
/// assert_eq!(metrics.get_gauge("test.gauge"), Some(100.0));
/// ```
#[derive(Clone, Debug)]
pub struct TestMetricsCollector {
    counters: Arc<Mutex<HashMap<String, u64>>>,
    histogram_values: Arc<Mutex<HashMap<String, Vec<f64>>>>,
    gauge_values: Arc<Mutex<HashMap<String, f64>>>,
    /// Labeled counters: `metric_name` -> (sorted labels -> value)
    #[allow(
        clippy::type_complexity,
        reason = "labeled metric storage requires nested HashMap"
    )]
    labeled_counters: Arc<Mutex<HashMap<String, HashMap<Vec<(String, String)>, u64>>>>,
}

impl Default for TestMetricsCollector {
    fn default() -> Self {
        Self::new()
    }
}

impl juncture_core::observability::MetricsCollector for TestMetricsCollector {
    fn inc_counter(&self, name: &str, value: u64) {
        self.increment_counter(name, value);
    }

    fn record_histogram(&self, name: &str, value: f64) {
        self.record_histogram(name, value);
    }

    fn set_gauge(&self, name: &str, value: u64) {
        #[allow(
            clippy::cast_precision_loss,
            reason = "gauge values from OTel are u64, stored as f64 in test utility"
        )]
        let fval = value as f64;
        self.set_gauge(name, fval);
    }
}

impl TestMetricsCollector {
    /// Create a new test metrics collector
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let collector = TestMetricsCollector::new();
    /// assert_eq!(collector.get_counter("any"), 0);
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            counters: Arc::new(Mutex::new(HashMap::new())),
            histogram_values: Arc::new(Mutex::new(HashMap::new())),
            gauge_values: Arc::new(Mutex::new(HashMap::new())),
            labeled_counters: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Increment a counter metric
    ///
    /// Adds the given value to the counter, creating it if it doesn't exist.
    ///
    /// # Parameters
    ///
    /// * `name` - Counter metric name
    /// * `value` - Value to add (default is 1)
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.increment_counter("my.counter", 1);
    /// metrics.increment_counter("my.counter", 2);
    /// assert_eq!(metrics.get_counter("my.counter"), 3);
    /// ```
    pub fn increment_counter(&self, name: &str, value: u64) {
        let mut counters = self.counters.lock().unwrap();
        *counters.entry(name.to_string()).or_insert(0) += value;
    }

    /// Record a value in a histogram metric
    ///
    /// Adds the value to the histogram's recorded values.
    ///
    /// # Parameters
    ///
    /// * `name` - Histogram metric name
    /// * `value` - Value to record
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.record_histogram("latency_ms", 100.0);
    /// metrics.record_histogram("latency_ms", 200.0);
    ///
    /// let values = metrics.get_histogram_values("latency_ms");
    /// assert_eq!(values.len(), 2);
    /// assert_eq!(values[0], 100.0);
    /// assert_eq!(values[1], 200.0);
    /// ```
    pub fn record_histogram(&self, name: &str, value: f64) {
        let mut histograms = self.histogram_values.lock().unwrap();
        histograms.entry(name.to_string()).or_default().push(value);
    }

    /// Set a gauge metric to a specific value
    ///
    /// # Parameters
    ///
    /// * `name` - Gauge metric name
    /// * `value` - Value to set
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.set_gauge("temperature", 98.6);
    /// metrics.set_gauge("temperature", 99.1);
    ///
    /// assert_eq!(metrics.get_gauge("temperature"), Some(99.1));
    /// ```
    pub fn set_gauge(&self, name: &str, value: f64) {
        let mut gauges = self.gauge_values.lock().unwrap();
        gauges.insert(name.to_string(), value);
    }

    /// Get the current value of a counter metric
    ///
    /// Returns 0 if the counter has never been incremented.
    ///
    /// # Parameters
    ///
    /// * `name` - Counter metric name
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// assert_eq!(metrics.get_counter("test"), 0);
    ///
    /// metrics.increment_counter("test", 5);
    /// assert_eq!(metrics.get_counter("test"), 5);
    /// ```
    #[must_use]
    pub fn get_counter(&self, name: &str) -> u64 {
        let counters = self.counters.lock().unwrap();
        counters.get(name).copied().unwrap_or(0)
    }

    /// Get all recorded values for a histogram metric
    ///
    /// Returns an empty vector if the histogram has no values.
    ///
    /// # Parameters
    ///
    /// * `name` - Histogram metric name
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// assert!(metrics.get_histogram_values("test").is_empty());
    ///
    /// metrics.record_histogram("test", 1.0);
    /// assert_eq!(metrics.get_histogram_values("test"), vec![1.0]);
    /// ```
    #[must_use]
    pub fn get_histogram_values(&self, name: &str) -> Vec<f64> {
        let histograms = self.histogram_values.lock().unwrap();
        histograms.get(name).cloned().unwrap_or_default()
    }

    /// Get the current value of a gauge metric
    ///
    /// Returns `None` if the gauge has never been set.
    ///
    /// # Parameters
    ///
    /// * `name` - Gauge metric name
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// assert_eq!(metrics.get_gauge("test"), None);
    ///
    /// metrics.set_gauge("test", 42.0);
    /// assert_eq!(metrics.get_gauge("test"), Some(42.0));
    /// ```
    #[must_use]
    pub fn get_gauge(&self, name: &str) -> Option<f64> {
        let gauges = self.gauge_values.lock().unwrap();
        gauges.get(name).copied()
    }

    /// Clear all recorded metrics
    ///
    /// Useful for resetting state between test cases.
    ///
    /// # Panics
    ///
    /// Panics if any internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.increment_counter("test", 5);
    /// metrics.clear();
    /// assert_eq!(metrics.get_counter("test"), 0);
    /// ```
    #[expect(
        clippy::significant_drop_tightening,
        reason = "Locks are held only briefly for clearing"
    )]
    pub fn clear(&self) {
        let mut counters = self.counters.lock().unwrap();
        let mut histograms = self.histogram_values.lock().unwrap();
        let mut gauges = self.gauge_values.lock().unwrap();
        let mut labeled = self.labeled_counters.lock().unwrap();

        counters.clear();
        histograms.clear();
        gauges.clear();
        labeled.clear();
    }

    /// Get all counter names that have been recorded
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.increment_counter("counter1", 1);
    /// metrics.increment_counter("counter2", 1);
    ///
    /// let names = metrics.counter_names();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"counter1".to_string()));
    /// ```
    #[must_use]
    pub fn counter_names(&self) -> Vec<String> {
        let counters = self.counters.lock().unwrap();
        counters.keys().cloned().collect()
    }

    /// Get all histogram names that have been recorded
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.record_histogram("hist1", 1.0);
    /// metrics.record_histogram("hist2", 2.0);
    ///
    /// let names = metrics.histogram_names();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"hist1".to_string()));
    /// ```
    #[must_use]
    pub fn histogram_names(&self) -> Vec<String> {
        let histograms = self.histogram_values.lock().unwrap();
        histograms.keys().cloned().collect()
    }

    /// Get all gauge names that have been recorded
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    ///
    /// # Examples
    ///
    /// ```
    /// use juncture_tracing::test_utils::TestMetricsCollector;
    ///
    /// let metrics = TestMetricsCollector::new();
    /// metrics.set_gauge("gauge1", 1.0);
    /// metrics.set_gauge("gauge2", 2.0);
    ///
    /// let names = metrics.gauge_names();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"gauge1".to_string()));
    /// ```
    #[must_use]
    pub fn gauge_names(&self) -> Vec<String> {
        let gauges = self.gauge_values.lock().unwrap();
        gauges.keys().cloned().collect()
    }

    /// Increment a counter metric with labels
    ///
    /// Labels are sorted internally for consistent key matching.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    #[allow(
        clippy::significant_drop_tightening,
        reason = "MutexGuard is needed for entry API; tightening would complicate the code"
    )]
    pub fn increment_counter_with_labels(
        &self,
        name: &str,
        value: u64,
        labels: &[(impl ToString, impl ToString)],
    ) {
        let key = labels_to_key(labels);
        let mut labeled = self.labeled_counters.lock().unwrap();
        let entry = labeled
            .entry(name.to_string())
            .or_default()
            .entry(key)
            .or_insert(0);
        *entry = entry.saturating_add(value);
    }

    /// Get counter value for a specific label set
    ///
    /// Returns 0 if no counter with those labels has been recorded.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned (should not happen in normal usage).
    #[must_use]
    pub fn get_counter_with_labels(
        &self,
        name: &str,
        labels: &[(impl ToString, impl ToString)],
    ) -> u64 {
        let key = labels_to_key(labels);
        let labeled = self.labeled_counters.lock().unwrap();
        labeled
            .get(name)
            .and_then(|m| m.get(&key))
            .copied()
            .unwrap_or(0)
    }
}

/// Convert labels to a sorted Vec key for consistent matching
fn labels_to_key(labels: &[(impl ToString, impl ToString)]) -> Vec<(String, String)> {
    let mut key: Vec<(String, String)> = labels
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
    key.sort_by(|a, b| a.0.cmp(&b.0));
    key
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default() {
        let collector = TestMetricsCollector::default();
        assert_eq!(collector.get_counter("test"), 0);
        assert!(collector.get_histogram_values("test").is_empty());
        assert_eq!(collector.get_gauge("test"), None);
    }

    #[test]
    fn test_increment_counter() {
        let metrics = TestMetricsCollector::new();

        metrics.increment_counter("test.counter", 1);
        assert_eq!(metrics.get_counter("test.counter"), 1);

        metrics.increment_counter("test.counter", 2);
        assert_eq!(metrics.get_counter("test.counter"), 3);

        // Different counter
        metrics.increment_counter("other.counter", 10);
        assert_eq!(metrics.get_counter("other.counter"), 10);
        assert_eq!(metrics.get_counter("test.counter"), 3);
    }

    #[test]
    fn test_record_histogram() {
        let metrics = TestMetricsCollector::new();

        metrics.record_histogram("test.histogram", 1.0);
        assert_eq!(metrics.get_histogram_values("test.histogram"), vec![1.0]);

        metrics.record_histogram("test.histogram", 2.0);
        metrics.record_histogram("test.histogram", 3.0);

        let values = metrics.get_histogram_values("test.histogram");
        assert_eq!(values.len(), 3);
        assert_eq!(values, vec![1.0, 2.0, 3.0]);

        // Different histogram
        metrics.record_histogram("other.histogram", 100.0);
        assert_eq!(metrics.get_histogram_values("other.histogram"), vec![100.0]);
    }

    #[test]
    fn test_set_gauge() {
        let metrics = TestMetricsCollector::new();

        metrics.set_gauge("test.gauge", 50.0);
        assert_eq!(metrics.get_gauge("test.gauge"), Some(50.0));

        metrics.set_gauge("test.gauge", 75.0);
        assert_eq!(metrics.get_gauge("test.gauge"), Some(75.0));

        // Different gauge
        metrics.set_gauge("other.gauge", 100.0);
        assert_eq!(metrics.get_gauge("other.gauge"), Some(100.0));
        assert_eq!(metrics.get_gauge("test.gauge"), Some(75.0));
    }

    #[test]
    fn test_clear() {
        let metrics = TestMetricsCollector::new();

        metrics.increment_counter("counter", 5);
        metrics.record_histogram("histogram", 1.0);
        metrics.set_gauge("gauge", 10.0);

        metrics.clear();

        assert_eq!(metrics.get_counter("counter"), 0);
        assert!(metrics.get_histogram_values("histogram").is_empty());
        assert_eq!(metrics.get_gauge("gauge"), None);
    }

    #[test]
    fn test_metric_names() {
        let metrics = TestMetricsCollector::new();

        metrics.increment_counter("counter1", 1);
        metrics.increment_counter("counter2", 1);

        let counter_names = metrics.counter_names();
        assert_eq!(counter_names.len(), 2);
        assert!(counter_names.contains(&"counter1".to_string()));
        assert!(counter_names.contains(&"counter2".to_string()));

        metrics.record_histogram("hist1", 1.0);
        metrics.record_histogram("hist2", 1.0);

        let histogram_names = metrics.histogram_names();
        assert_eq!(histogram_names.len(), 2);
        assert!(histogram_names.contains(&"hist1".to_string()));

        metrics.set_gauge("gauge1", 1.0);
        metrics.set_gauge("gauge2", 1.0);

        let gauge_names = metrics.gauge_names();
        assert_eq!(gauge_names.len(), 2);
        assert!(gauge_names.contains(&"gauge1".to_string()));
    }

    #[test]
    fn test_clone() {
        let metrics1 = TestMetricsCollector::new();
        metrics1.increment_counter("test", 5);

        let metrics2 = metrics1.clone();
        assert_eq!(metrics2.get_counter("test"), 5);

        // Changes to clone affect original (they share the same Arc)
        metrics2.increment_counter("test", 3);
        assert_eq!(metrics1.get_counter("test"), 8);
    }

    #[test]
    fn test_labeled_counter() {
        let metrics = TestMetricsCollector::new();

        metrics.increment_counter_with_labels("juncture.llm.calls", 1, &[("model", "gpt-4")]);
        metrics.increment_counter_with_labels("juncture.llm.calls", 1, &[("model", "gpt-4")]);
        metrics.increment_counter_with_labels("juncture.llm.calls", 1, &[("model", "claude")]);

        assert_eq!(
            metrics.get_counter_with_labels("juncture.llm.calls", &[("model", "gpt-4")]),
            2
        );
        assert_eq!(
            metrics.get_counter_with_labels("juncture.llm.calls", &[("model", "claude")]),
            1
        );
        assert_eq!(
            metrics.get_counter_with_labels("juncture.llm.calls", &[("model", "llama")]),
            0
        );
    }

    #[test]
    fn test_labeled_counter_key_ordering() {
        let metrics = TestMetricsCollector::new();

        metrics.increment_counter_with_labels("test", 1, &[("b", "2"), ("a", "1")]);
        assert_eq!(
            metrics.get_counter_with_labels("test", &[("a", "1"), ("b", "2")]),
            1
        );
    }
}

// Rust guideline compliant 2026-05-19