Sha256: 0bc0795854f8234a4c4c58a9927e10d28c21255759e1757cb55df1633361110d

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 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
          @status, @headers, @response = @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)

        [@status, @headers, @response]
      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.1 lib/builder_apm/middleware/timing.rb