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
SCHEME_SEPARATOR =
"://".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.



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

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

Instance Method Details

#call(env) ⇒ Object



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
61
62
# File 'lib/aws-xray-sdk/facets/rack.rb', line 18

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 segment name from host header if applicable
  seg_name = @recorder.segment_naming.provide_name(host: req.host)

  # get sampling decision
  sampled = should_sample?(
    header_obj: header, recorder: @recorder, sampling_req:
    { host: host, http_method: method, url_path: url_path, service: seg_name }
  )

  # 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
    trace_header = {TRACE_HEADER => TraceHeader.from_entity(entity: segment).root_string}
    headers.merge!(trace_header)
    [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