class HubStep::Rack::Middleware

Rack middleware for wrapping a request in a span.

Constants

SPAN

Public Class Methods

get_span(env) click to toggle source

Get the span that represents this request

env - a Rack env Hash

Returns a Span.

# File lib/hubstep/rack/middleware.rb, line 16
def self.get_span(env)
  env[SPAN] || Tracer::InertSpan.instance
end
new(app, tracer:, enable_if:, include_urls: false) click to toggle source

Create a Middleware

tracer - a HubStep::Tracer instance enable_if - Proc that is passed the env for each request. If the Proc

returns true, the tracer will be enabled for the duration
of the request. If the Proc returns false, the tracer will
be disabled for the duration of the request.

include_urls - Boolean specifying whether the `http.url` tag should be

added to the spans this middleware creates. URLs can
contain sensitive information, so they are omitted by
default.
# File lib/hubstep/rack/middleware.rb, line 31
def initialize(app, tracer:, enable_if:, include_urls: false)
  @app = app
  @tracer = tracer
  @enable_if = enable_if
  @include_urls = include_urls
end

Public Instance Methods

call(env) click to toggle source
# File lib/hubstep/rack/middleware.rb, line 38
def call(env)
  @tracer.with_enabled(@enable_if.call(env)) do
    trace(env) do
      @app.call(env)
    end
  end
end

Private Instance Methods

record_request(span, env) click to toggle source
# File lib/hubstep/rack/middleware.rb, line 62
def record_request(span, env)
  tags(::Rack::Request.new(env)).each do |key, value|
    span.set_tag(key, value)
  end
end
record_response(span, status, _headers, _body) click to toggle source
# File lib/hubstep/rack/middleware.rb, line 68
def record_response(span, status, _headers, _body)
  span.set_tag("http.status_code", status)
  return if status.to_i < 500
  span.set_tag("error", true)
end
request_id(request) click to toggle source
# File lib/hubstep/rack/middleware.rb, line 91
def request_id(request)
  request.env["HTTP_X_GITHUB_REQUEST_ID"]
end
tags(request) click to toggle source
# File lib/hubstep/rack/middleware.rb, line 74
def tags(request)
  tags = {
    "component" => "rack",
    "span.kind" => "server",
    "http.method" => request.request_method,
  }
  if @include_urls
    tags["http.url"] = request.url
  end
  id = request_id(request)
  if id
    tags["guid:github_request_id"] = id
  end

  tags.freeze
end
trace(env) { || ... } click to toggle source
# File lib/hubstep/rack/middleware.rb, line 48
def trace(env)
  @tracer.span("Rack #{env["REQUEST_METHOD"]}") do |span|
    env[SPAN] = span

    span.configure { record_request(span, env) }

    result = yield

    span.configure { record_response(span, *result) }

    result
  end
end