Class: XRay::Rack::Middleware

Inherits:
Object
  • Object
show all
Includes:
Facets::Helper
Defined in:
lib/aws-xray-sdk/facets/rack.rb

Overview

Rack middleware that generates a segment for each request/response cycle.

Constant Summary collapse

X_FORWARD =
'HTTP_X_FORWARDED_FOR'.freeze

Constants included from Facets::Helper

Facets::Helper::TRACE_HEADER, Facets::Helper::TRACE_HEADER_PROXY

Instance Method Summary collapse

Methods included from Facets::Helper

#construct_header, #prep_header_str, #should_sample?

Constructor Details

#initialize(app, recorder: nil) ⇒ Middleware

Returns a new instance of Middleware.



12
13
14
15
# File 'lib/aws-xray-sdk/facets/rack.rb', line 12

def initialize(app, recorder: nil)
  @app = app
  @recorder = recorder || XRay.recorder
end

Instance Method Details

#call(env) ⇒ Object



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
54
55
56
57
58
59
60
# File 'lib/aws-xray-sdk/facets/rack.rb', line 17

def call(env)
  header = construct_header(headers: env)
  req = ::Rack::Request.new(env)

  # params required for path based sampling
  host = req.host
  url_path = req.path
  method = req.request_method

  # get sampling decision
  sampled = should_sample?(
    header_obj: header, recorder: @recorder,
    host: host, method: method, path: url_path
  )

  # get segment name from host header if applicable
  seg_name = @recorder.segment_naming.provide_name(host: req.host)

  # begin the segment
  segment = @recorder.begin_segment seg_name, trace_id: header.root, parent_id: header.parent_id,
                                              sampled: sampled

  # add neccessary http request metadata to the segment
  req_meta = extract_request_meta(req)
  segment.merge_http_request request: req_meta unless req_meta.empty?
  begin
    status, headers, body = @app.call env
    resp_meta = {}
    resp_meta[:status] = status
    # Don't set content_length if it is not available on headers.
    resp_obj = ::Rack::Response.new body: body, status: status, headers: headers
    if len = resp_obj.content_length
      resp_meta[:content_length] = len
    end
    segment.merge_http_response response: resp_meta
    [status, headers, body]
  rescue Exception => e
    segment.apply_status_code status: 500
    segment.add_exception exception: e
    raise e
  ensure
    @recorder.end_segment
  end
end