Module: Coolhand::NetHttpInterceptor
Defined Under Namespace
Modules: ResponseInterceptor
Class Method Summary
collapse
Instance Method Summary
collapse
clean_request_headers, clean_response_headers, extract_response_data, extract_usage_metadata, normalize_header_value, parse_json, sanitize_headers, sanitize_url, send_complete_request_log
Class Method Details
.patch! ⇒ Object
20
21
22
23
24
25
26
27
28
|
# File 'lib/coolhand/net_http_interceptor.rb', line 20
def self.patch!
return if @patched
Net::HTTP.prepend(self)
Net::HTTPResponse.prepend(ResponseInterceptor)
@patched = true
Coolhand.log "🔗 Net::HTTP interceptor patched"
end
|
.patched? ⇒ Boolean
37
38
39
|
# File 'lib/coolhand/net_http_interceptor.rb', line 37
def self.patched?
@patched
end
|
.unpatch! ⇒ Object
30
31
32
33
34
35
|
# File 'lib/coolhand/net_http_interceptor.rb', line 30
def self.unpatch!
@patched = false
Coolhand.log "🔌 Faraday monitoring disabled ..."
end
|
Instance Method Details
#request(req, body = nil, &block) ⇒ Object
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
# File 'lib/coolhand/net_http_interceptor.rb', line 41
def request(req, body = nil, &block)
return super unless NetHttpInterceptor.patched?
active = (Thread.current[:coolhand_active_requests] ||= {}.compare_by_identity)
return super if active.key?(self)
url = build_url_for_request(self, req)
return super unless intercept?(url)
return super unless should_capture?
captured_body = capture_request_body(req, body)
active[self] = true
start_time = Time.now
request_id = SecureRandom.uuid
response = nil
status_code = nil
response_body = nil
Thread.current[:coolhand_stream_buffer] = nil
begin
response = super
body_content = Thread.current[:coolhand_stream_buffer] || response&.body
body_content = body_content.dup.force_encoding("UTF-8") if body_content.is_a?(String)
status_code = response.respond_to?(:code) ? response.code.to_i : nil
response_body = parse_json(body_content)
rescue StandardError => e
status_code = (e)
response_body = { "error" => { "class" => e.class.name, "message" => e.message } }
raise
ensure
active.delete(self)
Thread.current[:coolhand_stream_buffer] = nil
end_time = Time.now
duration_ms = ((end_time - start_time) * 1000).round(2)
send_complete_request_log(
request_id: request_id,
method: req.method,
url: url,
request_headers: (req),
request_body: captured_body,
response_headers: (response),
response_body: response_body,
status_code: status_code,
start_time: start_time,
end_time: end_time,
duration_ms: duration_ms,
is_streaming: !!block
)
end
response
end
|