Sha256: 93a61569afea63f5b7a829f887b3cce2a05885c6d5bf75e408d37b3de1d04c3f

Contents?: true

Size: 1.57 KB

Versions: 6

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

require 'rack'

module OpenTracing
  module Instrumentation
    module Rack
      # ExtractMiddleware extract trace context and push it to scope manager.
      class ExtractMiddleware
        # @private
        class FakeSpan
          attr_reader :context

          def initialize(context)
            @context = context
          end
        end

        # @param app [RackApp] inner rack application
        # @param tracer [OpenTracing::Tracer]
        # @param logger [Logger]
        def initialize(
          app,
          tracer: OpenTracing.global_tracer,
          logger: nil
        )
          @app = app
          @tracer = tracer
          @logger = logger
        end

        # @param env [Hash<String, String>] rack env
        def call(env)
          span_context = @tracer.extract(OpenTracing::FORMAT_RACK, env)
          return @app.call(env) unless span_context

          with_scope(span_context) do
            @app.call(env)
          end
        end

        private

        def with_scope(span_context)
          scope = safe_create_scope(span_context)

          yield
        ensure
          safe_close_scope(scope)
        end

        def safe_create_scope(span_context)
          fake_span = FakeSpan.new(span_context)
          @tracer.scope_manager.activate(fake_span, finish_on_close: false)
        rescue StandardError => e
          @logger&.error(e)
          nil
        end

        def safe_close_scope(scope)
          scope&.close
        rescue StandardError => e
          @logger&.error(e)
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
opentracing-instrumentation-0.2.1 lib/opentracing/instrumentation/rack/extract_middleware.rb
opentracing-instrumentation-0.2.0 lib/opentracing/instrumentation/rack/extract_middleware.rb
opentracing-instrumentation-0.1.18 lib/opentracing/instrumentation/rack/extract_middleware.rb
opentracing-instrumentation-0.1.17 lib/opentracing/instrumentation/rack/extract_middleware.rb
opentracing-instrumentation-0.1.16 lib/opentracing/instrumentation/rack/extract_middleware.rb
opentracing-instrumentation-0.1.15 lib/opentracing/instrumentation/rack/extract_middleware.rb