Debian Codegraph @

samplers/probability/consistent/parent.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package consistent // import "go.opentelemetry.io/contrib/samplers/probability/consistent"
5
6 import (
7 "strings"
8
9 "go.opentelemetry.io/otel"
10 sdktrace "go.opentelemetry.io/otel/sdk/trace"
11 "go.opentelemetry.io/otel/trace"
12 )
13
14 type (
15 parentProbabilitySampler struct {
16 delegate sdktrace.Sampler
17 }
18 )
19
20 // ParentProbabilityBased is an implementation of the OpenTelemetry
21 // Trace Sampler interface that provides additional checks for tracestate
22 // Probability Sampling fields.
23 func ParentProbabilityBased(root sdktrace.Sampler, samplers ...sdktrace.ParentBasedSamplerOption) sdktrace.Sampler {
24 return &parentProbabilitySampler{
25 delegate: sdktrace.ParentBased(root, samplers...),
26 }
27 }
28
29 // ShouldSample implements "go.opentelemetry.io/otel/sdk/trace".Sampler.
30 func (p *parentProbabilitySampler) ShouldSample(params sdktrace.SamplingParameters) sdktrace.SamplingResult {
31 psc := trace.SpanContextFromContext(params.ParentContext)
32
33 // Note: We do not check psc.IsValid(), i.e., we repair the tracestate
34 // with or without a parent TraceId and SpanId.
35 state := psc.TraceState()
36
37 otts, err := parseOTelTraceState(state.Get(traceStateKey), psc.IsSampled())
38 if err != nil {
39 otel.Handle(err)
40 value := otts.serialize()
41 if value != "" {
42 // Note: see the note in
43 // "go.opentelemetry.io/otel/trace".TraceState.Insert(). The
44 // error below is not a condition we're supposed to handle.
45 state, _ = state.Insert(traceStateKey, value)
46 } else {
47 state = state.Delete(traceStateKey)
48 }
49
50 // Fix the broken tracestate before calling the delegate.
51 params.ParentContext = trace.ContextWithSpanContext(params.ParentContext, psc.WithTraceState(state))
52 }
53
54 return p.delegate.ShouldSample(params)
55 }
56
57 // Description returns the same description as the built-in
58 // ParentBased sampler, with "ParentBased" replaced by
59 // "ParentProbabilityBased".
60 func (p *parentProbabilitySampler) Description() string {
61 return "ParentProbabilityBased" + strings.TrimPrefix(p.delegate.Description(), "ParentBased")
62 }