Sha256: 84a1068c30a6d8351b3e2b9222e7c7b6b18f027f7dc620e83284c6c659214251

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

module BuilderApm
  module Middleware
    class Timing
      def initialize(app, redis_client: BuilderApm::RedisClient.client)
        @redis_client = redis_client
        @app = app
      end

      def call(env)
        request_id = env["action_dispatch.request_id"]
        Thread.current["request_id"] = request_id
        start_time = Time.now.to_f * 1000

        begin
          result = @app.call(env)
        rescue => e
          handle_exception(e, start_time, request_id)
          raise e
        end

        end_time = Time.now.to_f * 1000
        handle_timing(start_time, end_time, request_id)

        result
      end

      private

      def handle_timing(start_time, end_time, request_id)
        duration = end_time - start_time;
        data = Thread.current['request_data']

        if data
          data[:real_start_time] = start_time 
          data[:real_end_time] = end_time
          data[:real_duration_time] = end_time - start_time
          Thread.current['request_data'] = nil
          
          @redis_client.zadd("builder_apm:timestamps", end_time, request_id)
          @redis_client.set("builder_apm:Request:#{data[:request_id]}", data.to_json)
        end
      end

      def handle_exception(e, start_time, request_id)
        end_time = Time.now.to_f * 1000

        data = Thread.current['request_data'] || {}
        data[:exception_class] = e.class.to_s
        data[:exception_message] = e.message
        data[:exception_backtrace] = e.backtrace

        handle_timing(start_time, end_time, request_id)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
builder_apm-0.2.0 lib/builder_apm/middleware/timing.rb