Class: LogBrew::FaradayTracingMiddleware

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/logbrew/faraday_tracing.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, client:, on_capture_error: nil) ⇒ FaradayTracingMiddleware

Returns a new instance of FaradayTracingMiddleware.



8
9
10
11
12
# File 'lib/logbrew/faraday_tracing.rb', line 8

def initialize(app, client:, on_capture_error: nil)
  super(app)
  @client = client
  @on_capture_error = on_capture_error
end

Instance Method Details

#call(env) ⇒ Object



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
49
50
51
52
53
# File 'lib/logbrew/faraday_tracing.rb', line 14

def call(env)
  prepared = HttpClientTracing.prepare(
    client: @client,
    source: "faraday",
    on_capture_error: @on_capture_error
  ) do
    url = env.url
    [env.method, url && url.host, HttpClientTracing::FaradayHeaderSnapshot.new(env.request_headers)]
  end
  return @app.call(env) unless prepared

  operation, header = prepared
  begin
    header.inject(operation.traceparent)
  rescue StandardError => error
    operation.capture_error(error)
    HttpClientTracing.reset_header(header, operation)
    return @app.call(env)
  end

  response = nil
  begin
    response = operation.around { @app.call(env) }
  rescue StandardError => error
    operation.finish(error: error)
    raise
  ensure
    HttpClientTracing.reset_header(header, operation)
  end

  begin
    response.on_complete do |completed|
      operation.finish(status_code: HttpClientTracing.read_status(completed, :status, operation))
    end
  rescue StandardError => error
    operation.capture_error(error)
    operation.finish(status_code: HttpClientTracing.read_status(response, :status, operation))
  end
  response
end