cf_rustracing/
tracer.rs

1use crate::sampler::Sampler;
2use crate::span::{SpanReceiver, SpanSender, StartSpanOptions};
3use std::borrow::Cow;
4use std::sync::Arc;
5use tokio::sync::mpsc;
6
7/// Tracer.
8///
9/// # Examples
10///
11/// ```
12/// use cf_rustracing::Tracer;
13/// use cf_rustracing::sampler::AllSampler;
14///
15/// # #[tokio::main]
16/// # async fn main(){
17/// let (tracer, mut span_rx) = Tracer::new(AllSampler);
18/// {
19///    let _span = tracer.span("foo").start_with_state(());
20/// }
21/// let span = span_rx.recv().await.unwrap();
22/// assert_eq!(span.operation_name(), "foo");
23/// # }
24/// ```
25#[derive(Debug)]
26pub struct Tracer<S, T> {
27    sampler: Arc<S>,
28    span_tx: SpanSender<T>,
29}
30impl<S: Sampler<T>, T> Tracer<S, T> {
31    /// Makes a new `Tracer` instance.
32    pub fn new(sampler: S) -> (Self, SpanReceiver<T>) {
33        let (span_tx, span_rx) = mpsc::unbounded_channel();
34
35        (
36            Tracer {
37                sampler: Arc::new(sampler),
38                span_tx,
39            },
40            span_rx,
41        )
42    }
43
44    /// Returns `StartSpanOptions` for starting a span which has the name `operation_name`.
45    pub fn span<N>(&self, operation_name: N) -> StartSpanOptions<'_, S, T>
46    where
47        N: Into<Cow<'static, str>>,
48    {
49        StartSpanOptions::new(operation_name, &self.span_tx, &self.sampler)
50    }
51}
52impl<S, T> Tracer<S, T> {
53    /// Clone with the given `sampler`.
54    pub fn clone_with_sampler<U: Sampler<T>>(&self, sampler: U) -> Tracer<U, T> {
55        Tracer {
56            sampler: Arc::new(sampler),
57            span_tx: self.span_tx.clone(),
58        }
59    }
60}
61impl<S, T> Clone for Tracer<S, T> {
62    fn clone(&self) -> Self {
63        Tracer {
64            sampler: Arc::clone(&self.sampler),
65            span_tx: self.span_tx.clone(),
66        }
67    }
68}