module ElasticAPM::Spies::NetHTTPSpy::Ext

def request(req, body = nil, &block)

rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
def request(req, body = nil, &block)
  unless (transaction = ElasticAPM.current_transaction)
    return super(req, body, &block)
  end
  if ElasticAPM::Spies::NetHTTPSpy.disabled?
    return super(req, body, &block)
  end
  host = req['host']&.split(':')&.first || address || 'localhost'
  method = req.method.to_s.upcase
  uri_or_path = URI(req.path)
  # Support the case where a whole url is passed as a path to a nil host
  uri =
    if uri_or_path.host
      uri_or_path
    else
      path, query = req.path.split('?')
      url = use_ssl? ? +'https://' : +'http://'
      url << host
      url << ":#{port}" if port
      url << path
      url << "?#{query}" if query
      URI(url)
    end
  context =
    ElasticAPM::Span::Context.new(
      http: { url: uri, method: method },
      destination: ElasticAPM::Span::Context::Destination.from_uri(uri, type: SUBTYPE)
    )
  ElasticAPM.with_span(
    "#{method} #{host}",
    TYPE,
    subtype: SUBTYPE,
    context: context
  ) do |span|
    trace_context = span&.trace_context || transaction.trace_context
    trace_context.apply_headers { |key, value| req[key] = value }
    result = super(req, body, &block)
    if (http = span&.context&.http)
      http.status_code = result.code
    end
    span&.outcome = Span::Outcome.from_http_status(result.code)
    result
  end
end