Sha256: bc51c06a6709ddd2806bbd40e9857b8405bd417f79d6472abf27f338835cfc07

Contents?: true

Size: 1.89 KB

Versions: 2

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

# Copyright 2019 OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0

module OpenTelemetry
  module SDK
    module Trace
      module Samplers
        # @api private
        #
        # Implements sampling based on a probability.
        class ProbabilitySampler
          def initialize(probability, ignore_parent:, apply_to_remote_parent:, apply_to_all_spans:)
            @probability = probability
            @id_upper_bound = format('%016x', (probability * (2**64 - 1)).ceil)
            @use_parent_sampled_flag = !ignore_parent
            @apply_to_remote_parent = apply_to_remote_parent
            @apply_to_all_spans = apply_to_all_spans
          end

          # @api private
          #
          # Callable interface for probability sampler. See {Samplers}.
          def call(trace_id:, span_id:, parent_context:, links:, name:, kind:, attributes:)
            # Ignored for sampling decision: links, name, kind, attributes.

            if sample?(trace_id, parent_context)
              RECORD_AND_SAMPLED
            else
              NOT_RECORD
            end
          end

          private

          def sample?(trace_id, parent_context)
            if parent_context.nil?
              sample_trace_id?(trace_id)
            else
              parent_sampled?(parent_context) || sample_trace_id_for_child?(parent_context, trace_id)
            end
          end

          def parent_sampled?(parent_context)
            @use_parent_sampled_flag && parent_context.trace_flags.sampled?
          end

          def sample_trace_id_for_child?(parent_context, trace_id)
            (@apply_to_all_spans || (@apply_to_remote_parent && parent_context.remote?)) && sample_trace_id?(trace_id)
          end

          def sample_trace_id?(trace_id)
            @probability == 1.0 || trace_id[16, 16] < @id_upper_bound
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
opentelemetry-sdk-0.4.0 lib/opentelemetry/sdk/trace/samplers/probability_sampler.rb
opentelemetry-sdk-0.3.0 lib/opentelemetry/sdk/trace/samplers/probability_sampler.rb