Module: Labkit::NetHttpPublisher

Defined in:
lib/labkit/net_http_publisher.rb

Overview

Prepend to Ruby’s Net/HTTP standard HTTP library to publish a notification whenever a HTTP request is triggered. Net::HTTP has different class methods for each http method. Those methods are delegated to corresponding instance methods. Eventually, ‘request` method is call to dispatch the HTTP request. Therefore, a prepender that override `request` method covers all HTTP calls.

For more information: github.com/ruby/ruby/blob/9b9cbbbc17bb5840581c7da37fd0feb0a7d4c1f3/lib/net/http.rb#L1510

Note: some use cases to take care of

  • Create a request from input URI

  • Create a request from input host, port, and path string

  • Create a singular request and closes the connection immediately

  • Create a persistent connection and perform multiple HTTP requests

  • Notification payload must separate URI components

  • Create a post request with a body

  • Create a post request with form data

  • Create a request with basic authentication

  • Make a request via a proxy server

  • Streaming

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.labkit_prepend!Object



29
30
31
32
33
34
35
36
37
# File 'lib/labkit/net_http_publisher.rb', line 29

def self.labkit_prepend!
  @prepend_mutex.synchronize do
    return if @prepended

    require "net/http"
    Net::HTTP.prepend(self)
    @prepended = true
  end
end

Instance Method Details

#request(request, *args, &block) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/labkit/net_http_publisher.rb', line 39

def request(request, *args, &block)
  return super unless started?

  start_time = ::Labkit::System.monotonic_time

  ActiveSupport::Notifications.instrument ::Labkit::EXTERNAL_HTTP_NOTIFICATION_TOPIC, create_request_payload(request) do |payload|
    response =
      begin
        super
      ensure
        payload[:duration] = (::Labkit::System.monotonic_time - start_time).to_f
      end
    payload[:code] = response.code
    response
  end
end