Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for HTTPX? #71

Open
brandondrew opened this issue Dec 29, 2023 · 1 comment
Open

Support for HTTPX? #71

brandondrew opened this issue Dec 29, 2023 · 1 comment
Assignees

Comments

@brandondrew
Copy link

Do you support HTTPX? If not, do you plan to support it?

@yuma-brendan
Copy link

Implemented as a httpx plugin

# frozen_string_literal: true

module Sniffer::Adapters::HttpxAdapter
  module Tracer
    module_function

    def call(request)
      data_item = start_sniffer(request)
      start_time = Time.now

      return unless data_item

      request.on(:response, &method(:finish_sniffer).curry(3)[data_item, start_time])
    end

    def start_sniffer(request)
      # binding.b
      data_item = Sniffer::DataItem.new
      body = ""
      body = request.body.to_s unless request.body.empty? || request.body.unbounded_body?

      data_item.request =
        Sniffer::DataItem::Request.new(
          host: request.uri.host,
          method: request.verb,
          query: request.query,
          port: request.uri.port,
          headers: request.headers,
          body: body
        )
      Sniffer.store(data_item)
      data_item
    end

    def finish_sniffer(data_item, start_time, response)
      # binding.b
      timing = Time.now - start_time
      status = response.is_a?(HTTPX::ErrorResponse) ? 0 : response.status
      headers = response.is_a?(HTTPX::ErrorResponse) ? {} : response.headers
      body = response.is_a?(HTTPX::ErrorResponse) ? "" : response.body.to_s

      data_item.response = Sniffer::DataItem::Response.new(status: status, headers: headers, body: body, timing: timing)
      Sniffer.notify_response(data_item)
    end
  end

  module RequestMethods
    def __sniffer_enable_trace!
      return if @__sniffer_enable_trace

      Tracer.call(self)
      @__sniffer_enable_trace = true
    end
  end

  module ConnectionMethods
    def send(request)
      request.__sniffer_enable_trace!

      super
    end
  end
end

if defined?(::Sniffer)
  sniffer_session = HTTPX.plugin(Sniffer::Adapters::HttpxAdapter)

  HTTPX.send(:remove_const, :Session)
  HTTPX.send(:const_set, :Session, sniffer_session.class)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants