Skip to main content

cf_rustracing/
tracer.rs

1use crate::sampler::Sampler;
2use crate::span::{SharedSpanConsumer, SpanConsumer, SpanReceiver, 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: SharedSpanConsumer<T>,
29}
30impl<S: Sampler<T>, T: Send + 'static> Tracer<S, T> {
31    /// Makes a new `Tracer` instance with an unbounded [`tokio::sync::mpsc`] channel.
32    pub fn new(sampler: S) -> (Self, SpanReceiver<T>) {
33        let (span_tx, span_rx) = mpsc::unbounded_channel();
34        (Self::with_consumer(sampler, span_tx), span_rx)
35    }
36}
37impl<S: Sampler<T>, T> Tracer<S, T> {
38    /// Makes a new `Tracer` instance with a custom consumer implementation.
39    pub fn with_consumer<C: SpanConsumer<T> + 'static>(sampler: S, consumer: C) -> Self {
40        Self {
41            sampler: Arc::new(sampler),
42            span_tx: SharedSpanConsumer::new(consumer),
43        }
44    }
45
46    /// Returns `StartSpanOptions` for starting a span which has the name `operation_name`.
47    pub fn span<N>(&self, operation_name: N) -> StartSpanOptions<'_, S, T>
48    where
49        N: Into<Cow<'static, str>>,
50    {
51        StartSpanOptions::new(operation_name, &self.span_tx, &self.sampler)
52    }
53}
54impl<S, T> Tracer<S, T> {
55    /// Clone with the given `sampler`.
56    pub fn clone_with_sampler<U: Sampler<T>>(&self, sampler: U) -> Tracer<U, T> {
57        Tracer {
58            sampler: Arc::new(sampler),
59            span_tx: self.span_tx.clone(),
60        }
61    }
62}
63impl<S, T> Clone for Tracer<S, T> {
64    fn clone(&self) -> Self {
65        Tracer {
66            sampler: Arc::clone(&self.sampler),
67            span_tx: self.span_tx.clone(),
68        }
69    }
70}