Sha256: db7d59b41cfe1ca5f6e7d4f3e805816038cdbb46b7d189d0f2b47290743ec876

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 KB

Contents

#
# frozen_string_literal: true

module ElasticAPM
  # @api private
  class Middleware
    include Logging

    def initialize(app)
      @app = app
    end

    def call(env)
      begin
        if running? && !path_ignored?(env)
          transaction = start_transaction(env)
        end

        resp = @app.call env
      rescue InternalError
        raise # Don't report ElasticAPM errors
      rescue ::Exception => e
        context = ElasticAPM.build_context(rack_env: env, for_type: :error)
        ElasticAPM.report(e, context: context, handled: false)
        raise
      ensure
        if resp && transaction
          status, headers, _body = resp
          transaction.add_response(status, headers: headers.dup)
        end

        ElasticAPM.end_transaction http_result(status)
      end

      resp
    end

    private

    def http_result(status)
      status && "HTTP #{status.to_s[0]}xx"
    end

    def path_ignored?(env)
      config.ignore_url_patterns.any? do |r|
        env['PATH_INFO'].match r
      end
    end

    def start_transaction(env)
      context = ElasticAPM.build_context(rack_env: env, for_type: :transaction)

      ElasticAPM.start_transaction 'Rack', 'request',
        context: context,
        trace_context: trace_context(env)
    end

    def trace_context(env)
      TraceContext.parse(env: env)
    rescue TraceContext::InvalidTraceparentHeader => e
      warn e.message
      nil
    end

    def running?
      ElasticAPM.running?
    end

    def config
      @config ||= ElasticAPM.agent.config
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
elastic-apm-3.6.0 lib/elastic_apm/middleware.rb
elastic-apm-3.5.0 lib/elastic_apm/middleware.rb