Skip to main content

scouter_types/
span_capture.rs

1use crate::trace::TraceSpanRecord;
2use crate::TraceId as ScouterTraceId;
3use std::collections::HashSet;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::RwLock;
6
7pub const CAPTURE_BUFFER_MAX: usize = 20_000;
8
9/// Whether local span capture is enabled.
10pub static CAPTURING: AtomicBool = AtomicBool::new(false);
11
12/// Global buffer of captured spans.
13pub static CAPTURE_BUFFER: RwLock<Vec<TraceSpanRecord>> = RwLock::new(Vec::new());
14
15/// Returns `true` if local span capture is currently enabled.
16pub fn is_capturing() -> bool {
17    CAPTURING.load(Ordering::Acquire)
18}
19
20/// Drain all captured spans from the buffer (takes ownership).
21pub fn drain_captured_spans() -> Vec<TraceSpanRecord> {
22    std::mem::take(&mut *CAPTURE_BUFFER.write().unwrap_or_else(|p| p.into_inner()))
23}
24
25/// Returns clones of spans matching the given trace_ids.
26/// Does NOT drain the buffer.
27pub fn get_captured_spans_by_trace_ids(
28    trace_ids: &HashSet<ScouterTraceId>,
29) -> Vec<TraceSpanRecord> {
30    let buf = CAPTURE_BUFFER.read().unwrap_or_else(|p| p.into_inner());
31    buf.iter()
32        .filter(|span| trace_ids.contains(&span.trace_id))
33        .cloned()
34        .collect()
35}
36
37/// Returns a clone of all captured spans without draining.
38pub fn get_all_captured_spans() -> Vec<TraceSpanRecord> {
39    CAPTURE_BUFFER
40        .read()
41        .unwrap_or_else(|p| p.into_inner())
42        .clone()
43}