Skip to main content

provide_telemetry/
tracing.rs

1// SPDX-FileCopyrightText: Copyright (C) 2026 provide.io llc
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-Comment: Part of provide-telemetry.
4//
5
6use std::collections::BTreeMap;
7
8use crate::context::trace_snapshot;
9use crate::tracer::Tracer;
10
11pub fn get_tracer(name: Option<&str>) -> Tracer {
12    crate::tracer::get_tracer(name)
13}
14
15pub fn get_trace_context() -> BTreeMap<String, Option<String>> {
16    let snapshot = trace_snapshot();
17    BTreeMap::from([
18        ("trace_id".to_string(), snapshot.trace_id),
19        ("span_id".to_string(), snapshot.span_id),
20    ])
21}
22
23pub fn trace<T, F>(name: &str, callback: F) -> T
24where
25    F: FnOnce() -> T,
26{
27    crate::tracer::trace(name, callback)
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33    use crate::testing::{acquire_test_state_lock, reset_trace_context};
34    use crate::tracer::set_trace_context;
35
36    #[test]
37    fn tracing_test_tracer_names_match_contract() {
38        assert_eq!(get_tracer(None).name(), "provide.telemetry");
39        assert_eq!(get_tracer(Some("custom.tracer")).name(), "custom.tracer");
40    }
41
42    #[test]
43    fn tracing_test_trace_invokes_callback() {
44        // The lock is required even though this test asserts nothing about
45        // counters: trace() bumps the shared emitted_traces health counter, and
46        // tracer_tests::tracer_test_trace_sets_context_inside_callback_and_emits
47        // asserts an exact before+1. Emitting outside the lock makes that test
48        // fail with left: 2, right: 1 — roughly two runs in three at
49        // RUST_TEST_THREADS=4.
50        let _guard = acquire_test_state_lock();
51        let result = trace("test.span", || 42_i32);
52        assert_eq!(result, 42);
53    }
54
55    #[test]
56    fn tracing_test_get_trace_context_reflects_bound_snapshot() {
57        let _guard = acquire_test_state_lock();
58        reset_trace_context();
59
60        let _ctx = set_trace_context(Some("a".repeat(32)), Some("b".repeat(16)));
61        let snapshot = get_trace_context();
62
63        assert_eq!(snapshot.get("trace_id"), Some(&Some("a".repeat(32))));
64        assert_eq!(snapshot.get("span_id"), Some(&Some("b".repeat(16))));
65    }
66}