1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! # Sampler
//!
use crate::api;

/// Sampling options
#[derive(Clone, Debug)]
pub enum Sampler {
    /// Always sample the trace
    Always,
    /// Never sample the trace
    Never,
    /// Sample if the parent span is sampled
    Parent,
    /// Sample a given fraction of traces. Fractions >= 1 will always sample.
    /// If the parent span is sampled, then it's child spans will automatically
    /// be sampled. Fractions <0 are treated as zero, but spans may still be
    /// sampled if their parent is.
    Probability(f64),
}

impl api::Sampler for Sampler {
    fn should_sample(
        &self,
        parent_context: Option<&api::SpanContext>,
        _trace_id: api::TraceId,
        _span_id: api::SpanId,
        _name: &str,
        _span_kind: &api::SpanKind,
        _attributes: &[api::KeyValue],
        _links: &[api::Link],
    ) -> api::SamplingResult {
        let decision = match self {
            // Always sample the trace
            Sampler::Always => api::SamplingDecision::RecordAndSampled,
            // Never sample the trace
            Sampler::Never => api::SamplingDecision::NotRecord,
            // Sample if the parent span is sampled
            Sampler::Parent => {
                if parent_context.map(|ctx| ctx.is_sampled()).unwrap_or(false) {
                    api::SamplingDecision::RecordAndSampled
                } else {
                    api::SamplingDecision::NotRecord
                }
            }
            // Match parent or probabilistically sample the trace.
            Sampler::Probability(prob) => {
                if parent_context.map(|ctx| ctx.is_sampled()).unwrap_or(false) && *prob > 0.0 {
                    if *prob > 1.0 || *prob > rand::random() {
                        api::SamplingDecision::RecordAndSampled
                    } else {
                        api::SamplingDecision::NotRecord
                    }
                } else {
                    api::SamplingDecision::NotRecord
                }
            }
        };

        api::SamplingResult {
            decision,
            // No extra attributes ever set by the SDK samplers.
            attributes: Vec::new(),
        }
    }
}