use super::event::TraceId;
#[derive(Debug, Clone)]
pub struct TraceContext {
#[allow(dead_code)]
pub trace_id: TraceId,
#[allow(dead_code)]
pub start_time: u64,
pub flags: TraceFlags,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct TraceFlags {
pub sampled: bool,
#[allow(dead_code)]
pub debug: bool,
#[allow(dead_code)]
pub app_initiated: bool,
}
impl TraceContext {
pub fn new(trace_id: TraceId) -> Self {
Self {
trace_id,
start_time: crate::tracing::timestamp_now(),
flags: TraceFlags::default(),
}
}
#[allow(dead_code)]
pub fn with_flags(trace_id: TraceId, flags: TraceFlags) -> Self {
Self {
trace_id,
start_time: crate::tracing::timestamp_now(),
flags,
}
}
#[allow(dead_code)]
pub fn trace_id(&self) -> TraceId {
self.trace_id
}
#[allow(dead_code)]
pub(super) fn is_sampled(&self) -> bool {
self.flags.sampled
}
#[allow(dead_code)]
pub(super) fn enable_sampling(&mut self) {
self.flags.sampled = true;
}
}
impl Default for TraceContext {
fn default() -> Self {
Self::new(TraceId::default())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trace_context() {
let trace_id = TraceId::new();
let mut context = TraceContext::new(trace_id);
assert_eq!(context.trace_id(), trace_id);
assert!(!context.is_sampled());
context.enable_sampling();
assert!(context.is_sampled());
}
#[test]
fn test_trace_flags() {
let flags = TraceFlags {
sampled: true,
debug: false,
app_initiated: true,
};
let trace_id = TraceId::new();
let context = TraceContext::with_flags(trace_id, flags);
assert!(context.is_sampled());
assert!(context.flags.app_initiated);
assert!(!context.flags.debug);
}
}