Class: Bigcommerce::Lightstep::Middleware::Faraday

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/bigcommerce/lightstep/middleware/faraday.rb

Overview

Faraday middleware. It will add appropriate OT tags and trace IDs to outgoing connections done by Faraday

Constant Summary collapse

HTTP_ERROR_STATUS_THRESHOLD =
400
HTTP_STATUS_REQUEST_TIMEOUT =
408
HTTP_STATUS_INTERNAL_ERROR =
500
HTTP_STATUS_SERVICE_UNAVAIL =
503
OT_TAG_TRACE_ID =
'ot-tracer-traceid'
OT_TAG_SPAN_ID =
'ot-tracer-spanid'
OT_TAG_SAMPLED =
'ot-tracer-sampled'

Instance Method Summary collapse

Constructor Details

#initialize(app, service_name = nil) ⇒ Faraday

Returns a new instance of Faraday.



32
33
34
35
# File 'lib/bigcommerce/lightstep/middleware/faraday.rb', line 32

def initialize(app, service_name = nil)
  super(app)
  @service_name = (service_name || 'external').to_s
end

Instance Method Details

#call(request_env) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/bigcommerce/lightstep/middleware/faraday.rb', line 37

def call(request_env)
  uri = uri_from_env(request_env)
  tracer = ::Bigcommerce::Lightstep::Tracer.instance

  tracer.start_span(service_key, context: request_env[:request_headers]) do |span|
    span.set_tag('http.url', uri.to_s.split('?').first)
    span.set_tag('http.method', request_env[:method].to_s.downcase)
    span.set_tag('http.external-service', true)
    span.set_tag('span.kind', 'client')

    inject_ot_tags!(request_env, span)

    begin
      response = @app.call(request_env).on_complete do |response_env|
        span.set_tag('http.status_code', response_env[:status].to_s)
        span.set_tag('error', true) if response_env[:status].to_i >= HTTP_ERROR_STATUS_THRESHOLD
        response_env
      end
    rescue ::Net::ReadTimeout
      span.set_tag('error', true)
      span.set_tag('http.status_code', HTTP_STATUS_REQUEST_TIMEOUT)
      raise
    rescue ::Faraday::ConnectionFailed
      span.set_tag('error', true)
      span.set_tag('http.status_code', HTTP_STATUS_SERVICE_UNAVAIL)
      raise
    rescue ::Faraday::ClientError
      span.set_tag('error', true)
      span.set_tag('http.status_code', HTTP_STATUS_INTERNAL_ERROR)
      raise
    end

    response
  end
end