Class: Codebeacon::Tracer::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/codebeacon/tracer/src/rails/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



4
5
6
7
# File 'lib/codebeacon/tracer/src/rails/middleware.rb', line 4

def initialize(app)
  @app = app
  @first_run = true
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/codebeacon/tracer/src/rails/middleware.rb', line 9

def call(env)
  response = nil
  # tracer = Tracer.news
  begin
    Codebeacon::Tracer.config.set_query_config(env['QUERY_STRING'])
    if !@first_run #Codebeacon::Tracer.config.trace_enabled? && !@first_run
      # For middleware, the caller is this method itself
      Codebeacon::Tracer.trace(trigger_type: "middleware") do |tracer|
        dry_run_log = Codebeacon::Tracer.config.dry_run? ? "--DRY RUN-- " : ""
        Codebeacon::Tracer.logger.info(dry_run_log + "Tracing enabled for URI=#{env['REQUEST_URI']}")
        response = @app.call(env).tap do |_|
          Codebeacon::Tracer.logger.info("Tracing disabled for URI=#{env['REQUEST_URI']}")
        end
        begin
          params = env['action_dispatch.request.parameters'].dup
          tracer.name = "#{params.delete('controller')}##{params.delete('action')}"
          tracer.description = params.to_json
          # Update the metadata with the Rails-specific information
          tracer..instance_variable_set(:@name, tracer.name)
          tracer..instance_variable_set(:@description, tracer.description)
        rescue => e
          Codebeacon::Tracer.logger.error("Error setting tracer metadata: #{e.message}")
        end
        response
      end
    else
      if Codebeacon::Tracer.config.trace_enabled? && @first_run
        Codebeacon::Tracer.logger.info("Bypassing first request for performance.")
      end
      @first_run = false if @first_run
      response = @app.call(env)
    end
  rescue => e
    Codebeacon::Tracer.logger.error("Error in middleware: #{e.message}")
    Codebeacon::Tracer.logger.error(e.backtrace.join("\n")) if Codebeacon::Tracer.config.debug?
    # Ensure the request is processed even if tracing fails
    response = @app.call(env) if response.nil?
  end
  response
end