Module: Profiler::Instrumentation::NetHttpInstrumentation

Defined in:
lib/profiler/instrumentation/net_http_instrumentation.rb

Defined Under Namespace

Modules: RequestPatch

Constant Summary collapse

SKIP_HOSTS =
%w[127.0.0.1 localhost ::1].freeze
TEXT_BODY_LIMIT =

512 KB

512 * 1024
BINARY_BODY_LIMIT =

256 KB (before base64)

256 * 1024
TEXT_CONTENT_TYPES =
/\A(text\/|application\/(json|xml|xhtml|javascript|x-www-form-urlencoded)|image\/svg)/i
BINARY_CONTENT_TYPES =
/\A(image\/|application\/pdf|application\/octet-stream|application\/zip|audio\/|video\/)/i

Class Method Summary collapse

Class Method Details

.decompress_body(body, content_encoding) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/profiler/instrumentation/net_http_instrumentation.rb', line 125

def self.decompress_body(body, content_encoding)
  return body if content_encoding.empty? || body.nil? || body.empty?

  case content_encoding
  when "gzip", "x-gzip"
    Zlib::GzipReader.new(StringIO.new(body)).read
  when "deflate"
    Zlib::Inflate.inflate(body)
  else
    body
  end
rescue StandardError
  body
end

.extract_backtraceObject



155
156
157
158
159
160
# File 'lib/profiler/instrumentation/net_http_instrumentation.rb', line 155

def self.extract_backtrace
  caller_locations(5, 15)
    .reject { |l| l.path.to_s.include?("net/http") || l.path.to_s.include?("profiler/instrumentation") }
    .first(5)
    .map { |l| "#{l.path}:#{l.lineno}:in `#{l.label}`" }
end

.install!Object



114
115
116
117
118
# File 'lib/profiler/instrumentation/net_http_instrumentation.rb', line 114

def self.install!
  return if @installed
  Net::HTTP.prepend(RequestPatch)
  @installed = true
end

.process_body(body, content_type) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/profiler/instrumentation/net_http_instrumentation.rb', line 140

def self.process_body(body, content_type)
  return { body: nil, encoding: "text" } if body.nil? || body.empty?

  mime = content_type.split(";").first.to_s.strip

  if mime.match?(BINARY_CONTENT_TYPES)
    truncated = body.byteslice(0, BINARY_BODY_LIMIT) || ""
    { body: Base64.strict_encode64(truncated.b), encoding: "base64" }
  else
    # Text (including unknown content types)
    text = body.encode("UTF-8", invalid: :replace, undef: :replace, replace: "?")
    { body: text.byteslice(0, TEXT_BODY_LIMIT), encoding: "text" }
  end
end

.skip_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


120
121
122
123
# File 'lib/profiler/instrumentation/net_http_instrumentation.rb', line 120

def self.skip_host?(host)
  SKIP_HOSTS.include?(host) ||
    Profiler.configuration.http_skip_hosts.any? { |p| host.match?(p) }
end