Module: Amlexia::HttpWrap

Defined in:
lib/amlexia/http_wrap.rb

Class Method Summary collapse

Class Method Details

.provider_from_url(url) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/amlexia/http_wrap.rb', line 10

def provider_from_url(url)
  return "openai" if url.include?("openai")
  return "anthropic" if url.include?("anthropic")
  return "stripe" if url.include?("stripe")

  nil
end

.track_http_call(client, **event) ⇒ Object



48
49
50
# File 'lib/amlexia/http_wrap.rb', line 48

def track_http_call(client, **event)
  client.track(**event)
end

.wrap_net_http(client) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/amlexia/http_wrap.rb', line 18

def wrap_net_http(client)
  Net::HTTP.class_eval do
    alias_method :amlexia_original_request, :request unless method_defined?(:amlexia_original_request)

    define_method(:request) do |req, body = nil, &block|
      start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      status = 500
      err = nil
      begin
        res = amlexia_original_request(req, body, &block)
        status = res.code.to_i
        res
      rescue StandardError => e
        err = e.message
        raise
      ensure
        latency = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000).to_i
        client.track(
          endpoint: req.uri.to_s,
          method: req.method,
          status_code: status,
          latency_ms: latency,
          provider: Amlexia::HttpWrap.provider_from_url(req.uri.to_s),
          error_message: err
        )
      end
    end
  end
end