coolhand 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +43 -0
- data/README.md +14 -1
- data/docs/anthropic.md +15 -16
- data/docs/configuration.md +8 -6
- data/docs/declared_workloads.md +24 -1
- data/docs/feedback.md +33 -1
- data/docs/openai.md +2 -0
- data/docs/savings.md +95 -0
- data/lib/coolhand/api_service.rb +45 -68
- data/lib/coolhand/base_interceptor.rb +28 -15
- data/lib/coolhand/configuration.rb +6 -0
- data/lib/coolhand/declared_context.rb +29 -7
- data/lib/coolhand/default_intercept_path_patterns.yml +2 -2
- data/lib/coolhand/errors.rb +2 -1
- data/lib/coolhand/feedback_service.rb +49 -2
- data/lib/coolhand/log_queue.rb +222 -16
- data/lib/coolhand/net_http_interceptor.rb +22 -10
- data/lib/coolhand/optimization_feedback_link_service.rb +3 -8
- data/lib/coolhand/post_delivery.rb +139 -0
- data/lib/coolhand/read_requests.rb +9 -0
- data/lib/coolhand/response_warnings.rb +11 -4
- data/lib/coolhand/savings_service.rb +33 -0
- data/lib/coolhand/string_body_redactor.rb +60 -11
- data/lib/coolhand/version.rb +1 -1
- data/lib/coolhand/write_requests.rb +3 -3
- data/lib/coolhand.rb +18 -5
- metadata +5 -2
|
@@ -67,24 +67,28 @@ module Coolhand
|
|
|
67
67
|
sanitized = raw.dup
|
|
68
68
|
|
|
69
69
|
sanitized.each do |k, v|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
key_down = k.to_s.downcase
|
|
73
|
-
|
|
74
|
-
if key_down == "authorization"
|
|
75
|
-
sanitized[k] = if v.to_s.match?(/\ABearer\s+/i)
|
|
76
|
-
v.to_s.gsub(/\ABearer\s+.+/i, "Bearer [REDACTED]")
|
|
77
|
-
else
|
|
78
|
-
"[REDACTED]"
|
|
79
|
-
end
|
|
80
|
-
elsif sensitive_header?(key_down)
|
|
81
|
-
sanitized[k] = "[REDACTED]"
|
|
82
|
-
end
|
|
70
|
+
sanitized[k] = sanitize_header_value(k.to_s.downcase, v) unless v.nil?
|
|
83
71
|
end
|
|
84
72
|
|
|
85
73
|
sanitized
|
|
86
74
|
end
|
|
87
75
|
|
|
76
|
+
# The value to log for one header: redacted by name, or with credentials scrubbed out of a URL it holds.
|
|
77
|
+
def sanitize_header_value(key_down, value)
|
|
78
|
+
if key_down == "authorization"
|
|
79
|
+
# Keep only the scheme: nothing after "Bearer " survives, whatever the value contains.
|
|
80
|
+
value.to_s.match?(/\ABearer\s+/i) ? "Bearer [REDACTED]" : "[REDACTED]"
|
|
81
|
+
elsif sensitive_header?(key_down)
|
|
82
|
+
"[REDACTED]"
|
|
83
|
+
elsif value.include?("://")
|
|
84
|
+
# Location, Referer, Link and upload-URL headers carry URLs whose query string can hold a
|
|
85
|
+
# presigned signature or API key; run them through the same scrub as the request URL.
|
|
86
|
+
value.gsub(HEADER_URL_PATTERN) { |url| sanitize_url(url) }
|
|
87
|
+
else
|
|
88
|
+
value
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
88
92
|
# Helper: convert arrays -> joined string, otherwise to_s
|
|
89
93
|
def normalize_header_value(value)
|
|
90
94
|
if value.is_a?(Array)
|
|
@@ -94,6 +98,10 @@ module Coolhand
|
|
|
94
98
|
end
|
|
95
99
|
end
|
|
96
100
|
|
|
101
|
+
# An absolute URL inside a header value (stops at whitespace and the delimiters that separate
|
|
102
|
+
# URLs in Link and similar headers).
|
|
103
|
+
HEADER_URL_PATTERN = %r{[a-z][a-z0-9+.-]*://[^\s<>",;]+}i
|
|
104
|
+
|
|
97
105
|
# Matches query param *names* that signal sensitive content, the same way
|
|
98
106
|
# SENSITIVE_HEADER_PATTERN does for headers — covers exact params this
|
|
99
107
|
# gem already knew about (key/token/secret) as well as presigned-URL
|
|
@@ -267,11 +275,16 @@ module Coolhand
|
|
|
267
275
|
raw_request[:stream_incomplete] = true if stream_incomplete
|
|
268
276
|
|
|
269
277
|
request_data = { raw_request: raw_request }
|
|
278
|
+
# client_unique_id rides in the snapshot but is a log attribute, not workload identity.
|
|
279
|
+
client_unique_id = declared&.dig(:client_unique_id)
|
|
280
|
+
declared = declared&.except(:client_unique_id)
|
|
270
281
|
request_data[:declared] = declared if declared && !declared.empty?
|
|
282
|
+
request_data[:client_unique_id] = client_unique_id if client_unique_id
|
|
271
283
|
|
|
272
|
-
LogQueue.submit do
|
|
273
|
-
Coolhand::ApiService.new.send_llm_request_log(request_data)
|
|
284
|
+
LogQueue.submit(client_unique_id: client_unique_id) do
|
|
285
|
+
result = Coolhand::ApiService.new.send_llm_request_log(request_data)
|
|
274
286
|
Coolhand.log "📤 Sent complete request/response log for #{request_id} (duration: #{duration_ms}ms)"
|
|
287
|
+
result
|
|
275
288
|
end
|
|
276
289
|
rescue StandardError => e
|
|
277
290
|
Coolhand.log "❌ Error sending complete request log: #{e.message}"
|
|
@@ -32,6 +32,12 @@ module Coolhand
|
|
|
32
32
|
:max_captured_body_bytes, :webhook_replay_tolerance_seconds, :webhook_id_store, :async_logging
|
|
33
33
|
attr_reader :intercept_addresses, :intercept_path_patterns, :base_url, :auto_declare
|
|
34
34
|
|
|
35
|
+
# Keeps the API key out of `p config`, `Rails.logger.info(config)` and error-page dumps.
|
|
36
|
+
def inspect
|
|
37
|
+
"#<#{self.class} base_url=#{base_url.inspect} enabled=#{enabled.inspect} " \
|
|
38
|
+
"api_key=#{api_key ? '[REDACTED]' : 'nil'}>"
|
|
39
|
+
end
|
|
40
|
+
|
|
35
41
|
def initialize
|
|
36
42
|
# Set defaults
|
|
37
43
|
@environment = "production"
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module Coolhand
|
|
4
|
-
# Ambient workload/template identity for captured calls, set
|
|
5
|
-
# interceptor snapshots {current} on the calling thread before a
|
|
6
|
-
# background log worker does not inherit thread-locals. See
|
|
4
|
+
# Ambient workload/template identity and caller-supplied `client_unique_id` for captured calls, set
|
|
5
|
+
# with {Coolhand.with_context}. The interceptor snapshots {current} on the calling thread before a
|
|
6
|
+
# log is queued, because the background log worker does not inherit thread-locals. See
|
|
7
|
+
# docs/declared_workloads.md.
|
|
7
8
|
module DeclaredContext
|
|
8
9
|
THREAD_KEY = :coolhand_declared_context
|
|
9
10
|
|
|
@@ -27,12 +28,13 @@ module Coolhand
|
|
|
27
28
|
# key by key: `{ id: x }` merged with `{ key: y }` would declare both, and the server prefers `id`.
|
|
28
29
|
# A template belongs to a workload, so a block that declares a workload without a template does
|
|
29
30
|
# not inherit the outer one; it would pair the new workload with a template from another.
|
|
30
|
-
def with(reporter: nil, workload: nil, template: nil)
|
|
31
|
+
def with(reporter: nil, workload: nil, template: nil, client_unique_id: nil)
|
|
31
32
|
previous = current
|
|
32
33
|
declared = {
|
|
33
34
|
reporter: normalize_reporter(reporter),
|
|
34
35
|
workload: normalize_part(:workload, workload, WORKLOAD_FIELDS),
|
|
35
|
-
template: normalize_part(:template, template, TEMPLATE_FIELDS)
|
|
36
|
+
template: normalize_part(:template, template, TEMPLATE_FIELDS),
|
|
37
|
+
client_unique_id: normalize_client_unique_id(client_unique_id)
|
|
36
38
|
}.compact
|
|
37
39
|
inherited = previous || {}
|
|
38
40
|
inherited = inherited.except(:template) if declared.key?(:workload) && !declared.key?(:template)
|
|
@@ -50,6 +52,22 @@ module Coolhand
|
|
|
50
52
|
reporter.to_s
|
|
51
53
|
end
|
|
52
54
|
|
|
55
|
+
# The caller's own id for the next logged request(s), so feedback can find them by
|
|
56
|
+
# `create_feedback(client_unique_id:)`. Unlike a workload key, a bad value is dropped rather than
|
|
57
|
+
# raised: a correlation id must never break the caller's LLM call, and a value the server may
|
|
58
|
+
# refuse (over-long, control characters) should not put the whole log at risk.
|
|
59
|
+
MAX_CLIENT_UNIQUE_ID_LENGTH = 255
|
|
60
|
+
CLIENT_UNIQUE_ID_FORMAT = /\A[^\p{Cntrl}\p{Cf}]*[^\p{Cntrl}\p{Cf}[:space:]][^\p{Cntrl}\p{Cf}]*\z/
|
|
61
|
+
|
|
62
|
+
def normalize_client_unique_id(value)
|
|
63
|
+
return nil if value.nil?
|
|
64
|
+
return value.dup.freeze if valid_string?(value, MAX_CLIENT_UNIQUE_ID_LENGTH, CLIENT_UNIQUE_ID_FORMAT)
|
|
65
|
+
|
|
66
|
+
Coolhand.log "Ignoring client_unique_id: expected a non-blank String of at most " \
|
|
67
|
+
"#{MAX_CLIENT_UNIQUE_ID_LENGTH} characters with no control or invisible characters"
|
|
68
|
+
nil
|
|
69
|
+
end
|
|
70
|
+
|
|
53
71
|
# Mirrors the server's key rules: at most 255 characters, no control or invisible characters, no
|
|
54
72
|
# leading or trailing whitespace, and no leading, trailing or doubled "/". The server answers a
|
|
55
73
|
# bad key with a 422 that rejects the whole log, so it is checked here, before the call is made.
|
|
@@ -62,9 +80,13 @@ module Coolhand
|
|
|
62
80
|
}x
|
|
63
81
|
|
|
64
82
|
def valid_key?(key)
|
|
65
|
-
|
|
83
|
+
valid_string?(key, MAX_KEY_LENGTH, KEY_FORMAT)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def valid_string?(value, max_length, format)
|
|
87
|
+
value.is_a?(String) && value.length <= max_length && format.match?(value)
|
|
66
88
|
rescue ArgumentError, EncodingError
|
|
67
|
-
false # a string with a broken or incompatible encoding is not
|
|
89
|
+
false # a string with a broken or incompatible encoding is not valid
|
|
68
90
|
end
|
|
69
91
|
|
|
70
92
|
# A template given by key, with no workload to create it in, is a 422 that drops the log. A
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# Colon-action path suffixes from Google's API Discovery convention
|
|
2
2
|
# (e.g. ".../v1beta/models/gemini-pro:generateContent"). These have no host
|
|
3
3
|
# component of their own, so — unlike intercept_addresses — they are only
|
|
4
|
-
# ever matched against the *path* of requests whose host is
|
|
5
|
-
# googleapis.com or a googleapis.com subdomain. They can never match on
|
|
4
|
+
# ever matched against the *end of the path* of requests whose host is
|
|
5
|
+
# already googleapis.com or a googleapis.com subdomain. They can never match on
|
|
6
6
|
# their own against an unrelated/attacker-controlled host.
|
|
7
7
|
#
|
|
8
8
|
# Users can extend defaults: c.intercept_path_patterns << ":myAction"
|
data/lib/coolhand/errors.rb
CHANGED
|
@@ -7,7 +7,8 @@ module Coolhand
|
|
|
7
7
|
# answers with a non-2xx status.
|
|
8
8
|
#
|
|
9
9
|
# `status` is carried so callers can branch on it (404 vs retryable 504) without matching the
|
|
10
|
-
# message text.
|
|
10
|
+
# message text. The exception message is sanitized for printing, but `body` is the raw (length-capped)
|
|
11
|
+
# response body for callers that parse it, so treat it as untrusted before logging it.
|
|
11
12
|
class HttpError < Error
|
|
12
13
|
attr_reader :status, :body
|
|
13
14
|
|
|
@@ -1,15 +1,62 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require_relative "api_service"
|
|
4
|
+
require_relative "log_queue"
|
|
4
5
|
|
|
5
6
|
module Coolhand
|
|
6
7
|
class FeedbackService < ApiService
|
|
8
|
+
# How long feedback addressed by `client_unique_id` waits for its own log to finish sending.
|
|
9
|
+
LOG_WAIT_TIMEOUT = LogQueue::DEFAULT_FLUSH_TIMEOUT
|
|
10
|
+
|
|
7
11
|
def initialize
|
|
8
12
|
super("v2/llm_request_log_feedbacks")
|
|
9
13
|
end
|
|
10
14
|
|
|
11
|
-
|
|
12
|
-
|
|
15
|
+
# Returns the parsed response. A failure returns nil (and logs, unless `config.silent`); pass
|
|
16
|
+
# `raise_on_error: true` to get {Coolhand::HttpError} (non-2xx) or {Coolhand::Error} (no API
|
|
17
|
+
# key, network error, or the log for `client_unique_id` failed to send) instead. In debug mode
|
|
18
|
+
# nothing is sent and the result is nil. See docs/feedback.md.
|
|
19
|
+
#
|
|
20
|
+
# The fields may be passed as a Hash or as bare keywords (`create_feedback(client_unique_id: "x")`).
|
|
21
|
+
#
|
|
22
|
+
# Feedback carrying a `client_unique_id` whose log is still queued in this process is held until
|
|
23
|
+
# that log's send completes, so it can't arrive first. If that send failed, Coolhand never got the
|
|
24
|
+
# log and the feedback has nothing to attach to, so it is not sent.
|
|
25
|
+
def create_feedback(feedback = nil, raise_on_error: false, **fields)
|
|
26
|
+
# A Hash plus stray keywords is almost certainly a misspelled option, which would otherwise be
|
|
27
|
+
# merged into the payload and silently not raise.
|
|
28
|
+
raise ArgumentError, "unknown keywords: #{fields.keys.join(', ')}" if feedback && fields.any?
|
|
29
|
+
|
|
30
|
+
payload = (feedback || {}).merge(fields)
|
|
31
|
+
return log_failed(payload[:client_unique_id], raise_on_error) unless log_delivered?(payload[:client_unique_id])
|
|
32
|
+
|
|
33
|
+
super(payload, "manual", raise_on_error: raise_on_error)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
private
|
|
37
|
+
|
|
38
|
+
# Feedback for a log that failed to send is not posted: returns nil, or raises when asked to.
|
|
39
|
+
def log_failed(client_unique_id, raise_on_error)
|
|
40
|
+
message = "Not sending feedback: the log for client_unique_id #{client_unique_id.inspect} failed to send"
|
|
41
|
+
raise Error, message if raise_on_error
|
|
42
|
+
|
|
43
|
+
log "⚠️ #{message}"
|
|
44
|
+
nil
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def log_delivered?(client_unique_id)
|
|
48
|
+
return true unless client_unique_id
|
|
49
|
+
|
|
50
|
+
case LogQueue.await_delivery(client_unique_id, timeout: LOG_WAIT_TIMEOUT)
|
|
51
|
+
when :failed
|
|
52
|
+
false
|
|
53
|
+
when :timeout
|
|
54
|
+
log "⚠️ Sending feedback for client_unique_id #{client_unique_id.inspect} before its log finished " \
|
|
55
|
+
"sending (waited #{LOG_WAIT_TIMEOUT}s)"
|
|
56
|
+
true
|
|
57
|
+
else
|
|
58
|
+
true
|
|
59
|
+
end
|
|
13
60
|
end
|
|
14
61
|
end
|
|
15
62
|
end
|
data/lib/coolhand/log_queue.rb
CHANGED
|
@@ -13,10 +13,138 @@ module Coolhand
|
|
|
13
13
|
# is flushed at process exit. Work runs inline instead when `config.async_logging` is false,
|
|
14
14
|
# when `config.debug_mode` is on (debug output should appear in order), or when the caller is
|
|
15
15
|
# already a worker thread (a queued job's own sends don't re-enter a queue).
|
|
16
|
+
#
|
|
17
|
+
# A job submitted with a `client_unique_id` is also tracked, so {LogQueue.await_delivery} can wait
|
|
18
|
+
# for that one log (not the whole queue) and learn whether its send actually succeeded.
|
|
16
19
|
module LogQueue
|
|
17
20
|
MAX_QUEUE_SIZE = 1000
|
|
18
21
|
DEFAULT_FLUSH_TIMEOUT = 5
|
|
19
22
|
|
|
23
|
+
# Delivery state of one queued job: pending until the job returns (delivered when it returned a
|
|
24
|
+
# non-nil result, failed when it returned nil, raised, or was dropped before it ran).
|
|
25
|
+
class Delivery
|
|
26
|
+
def initialize
|
|
27
|
+
@mutex = Mutex.new
|
|
28
|
+
@done = ConditionVariable.new
|
|
29
|
+
@state = nil
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def finish(delivered)
|
|
33
|
+
@mutex.synchronize do
|
|
34
|
+
@state ||= delivered ? :delivered : :failed
|
|
35
|
+
@done.broadcast
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# The final state (:delivered or :failed), or nil if the deadline passed first.
|
|
40
|
+
def wait(deadline)
|
|
41
|
+
@mutex.synchronize do
|
|
42
|
+
loop do
|
|
43
|
+
return @state if @state
|
|
44
|
+
return nil unless LogQueue.wait_for(@done, @mutex, deadline)
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Wraps a job so its outcome lands on a Delivery and its registry entry is always cleared.
|
|
51
|
+
class TrackedJob
|
|
52
|
+
def initialize(job, delivery, on_settle)
|
|
53
|
+
@job = job
|
|
54
|
+
@delivery = delivery
|
|
55
|
+
@on_settle = on_settle
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def call
|
|
59
|
+
delivered = false
|
|
60
|
+
begin
|
|
61
|
+
result = @job.call
|
|
62
|
+
delivered = !result.nil?
|
|
63
|
+
result
|
|
64
|
+
ensure
|
|
65
|
+
settle(delivered)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# The job was discarded before it could run (queue full, reset).
|
|
70
|
+
def abandon
|
|
71
|
+
settle(false)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
private
|
|
75
|
+
|
|
76
|
+
def settle(delivered)
|
|
77
|
+
@delivery.finish(delivered)
|
|
78
|
+
@on_settle.call(delivered)
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The pending deliveries, keyed by client_unique_id (several logs may share an id), plus the
|
|
83
|
+
# most recent ids whose last send failed, so feedback arriving after the fact still sees it.
|
|
84
|
+
class Deliveries
|
|
85
|
+
MAX_FAILED_IDS = 1000
|
|
86
|
+
|
|
87
|
+
def initialize
|
|
88
|
+
@mutex = Mutex.new
|
|
89
|
+
@by_id = Hash.new { |hash, id| hash[id] = [] }
|
|
90
|
+
@failed = {}
|
|
91
|
+
@pid = Process.pid
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def track(client_unique_id, job)
|
|
95
|
+
delivery = Delivery.new
|
|
96
|
+
@mutex.synchronize do
|
|
97
|
+
drop_inherited_entries
|
|
98
|
+
@by_id[client_unique_id] << delivery
|
|
99
|
+
end
|
|
100
|
+
TrackedJob.new(job, delivery, ->(delivered) { settle(client_unique_id, delivery, delivered) })
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# [pending deliveries, whether the id's last finished send failed]
|
|
104
|
+
def snapshot(client_unique_id)
|
|
105
|
+
@mutex.synchronize do
|
|
106
|
+
drop_inherited_entries
|
|
107
|
+
[@by_id.key?(client_unique_id) ? @by_id[client_unique_id].dup : [], @failed.key?(client_unique_id)]
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def clear
|
|
112
|
+
@mutex.synchronize do
|
|
113
|
+
@by_id.clear
|
|
114
|
+
@failed.clear
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
private
|
|
119
|
+
|
|
120
|
+
def settle(client_unique_id, delivery, delivered)
|
|
121
|
+
@mutex.synchronize do
|
|
122
|
+
remember_outcome(client_unique_id, delivered)
|
|
123
|
+
next unless @by_id.key?(client_unique_id)
|
|
124
|
+
|
|
125
|
+
@by_id[client_unique_id].delete(delivery)
|
|
126
|
+
@by_id.delete(client_unique_id) if @by_id[client_unique_id].empty?
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def remember_outcome(client_unique_id, delivered)
|
|
131
|
+
@failed.delete(client_unique_id)
|
|
132
|
+
return if delivered
|
|
133
|
+
|
|
134
|
+
@failed[client_unique_id] = true
|
|
135
|
+
@failed.shift while @failed.size > MAX_FAILED_IDS
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# A forked child inherits the parent's entries but not the worker that would settle them.
|
|
139
|
+
def drop_inherited_entries
|
|
140
|
+
return if @pid == Process.pid
|
|
141
|
+
|
|
142
|
+
@pid = Process.pid
|
|
143
|
+
@by_id.clear
|
|
144
|
+
@failed.clear
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
20
148
|
# One bounded FIFO plus the thread that drains it.
|
|
21
149
|
class Lane
|
|
22
150
|
attr_reader :thread
|
|
@@ -49,13 +177,7 @@ module Coolhand
|
|
|
49
177
|
# A dead worker will never drain the queue, so don't wait on it.
|
|
50
178
|
return @jobs.empty? unless @thread&.alive?
|
|
51
179
|
|
|
52
|
-
|
|
53
|
-
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
54
|
-
return false unless remaining.positive?
|
|
55
|
-
|
|
56
|
-
@idle.wait(@mutex, remaining)
|
|
57
|
-
end
|
|
58
|
-
true
|
|
180
|
+
wait_until_drained(deadline)
|
|
59
181
|
end
|
|
60
182
|
end
|
|
61
183
|
|
|
@@ -63,6 +185,7 @@ module Coolhand
|
|
|
63
185
|
thread = nil
|
|
64
186
|
@mutex.synchronize do
|
|
65
187
|
thread = @thread
|
|
188
|
+
abandon(@jobs)
|
|
66
189
|
@jobs.clear
|
|
67
190
|
@thread = nil
|
|
68
191
|
@busy = false
|
|
@@ -75,8 +198,21 @@ module Coolhand
|
|
|
75
198
|
|
|
76
199
|
private
|
|
77
200
|
|
|
201
|
+
# The caller holds the mutex.
|
|
202
|
+
def wait_until_drained(deadline)
|
|
203
|
+
loop do
|
|
204
|
+
return true unless @jobs.any? || @busy
|
|
205
|
+
return false unless LogQueue.wait_for(@idle, @mutex, deadline)
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
def abandon(jobs)
|
|
210
|
+
jobs.each { |job| job.abandon if job.respond_to?(:abandon) }
|
|
211
|
+
end
|
|
212
|
+
|
|
78
213
|
def drop_oldest
|
|
79
|
-
@jobs.shift
|
|
214
|
+
abandon([@jobs.shift])
|
|
215
|
+
LogQueue.record_failure
|
|
80
216
|
Coolhand.log "⚠️ Log queue full (#{MAX_QUEUE_SIZE}); dropping the oldest pending log"
|
|
81
217
|
end
|
|
82
218
|
|
|
@@ -126,44 +262,114 @@ module Coolhand
|
|
|
126
262
|
def run(job)
|
|
127
263
|
job.call
|
|
128
264
|
rescue StandardError => e
|
|
265
|
+
LogQueue.record_failure
|
|
129
266
|
Coolhand.log "❌ Error in background log job: #{e.message}"
|
|
130
267
|
end
|
|
131
268
|
end
|
|
132
269
|
|
|
133
270
|
LANES = { default: Lane.new, batch: Lane.new }.freeze
|
|
271
|
+
DELIVERIES = Deliveries.new
|
|
134
272
|
|
|
135
273
|
@at_exit_mutex = Mutex.new
|
|
136
274
|
@at_exit_registered = false
|
|
275
|
+
@failure_mutex = Mutex.new
|
|
276
|
+
@failures = 0
|
|
277
|
+
@failures_pid = Process.pid
|
|
137
278
|
|
|
138
279
|
class << self
|
|
139
|
-
|
|
280
|
+
# Queues the job on a background lane, or runs it inline (see the module comment). With a
|
|
281
|
+
# `client_unique_id`, the job's outcome is tracked for {await_delivery}: it counts as delivered
|
|
282
|
+
# when the block returns a non-nil value, and as failed when it returns nil or raises.
|
|
283
|
+
def submit(lane: :default, client_unique_id: nil, &job)
|
|
140
284
|
return yield unless async?
|
|
141
285
|
|
|
142
286
|
register_at_exit
|
|
143
|
-
|
|
287
|
+
job = DELIVERIES.track(client_unique_id, job) if client_unique_id
|
|
288
|
+
enqueue_or_abandon(LANES.fetch(lane), job)
|
|
144
289
|
nil
|
|
145
290
|
end
|
|
146
291
|
|
|
292
|
+
# Waits for the queued log(s) carrying this client_unique_id, ignoring everything else in the
|
|
293
|
+
# queue. Returns :delivered or :failed once its send has completed (:failed also covers a send
|
|
294
|
+
# that failed earlier and hasn't been retried), :timeout if it is still sending, or :none when
|
|
295
|
+
# this process has no record of it (sent inline, or never queued here).
|
|
296
|
+
def await_delivery(client_unique_id, timeout: DEFAULT_FLUSH_TIMEOUT)
|
|
297
|
+
deliveries, failed_earlier = DELIVERIES.snapshot(client_unique_id)
|
|
298
|
+
return (failed_earlier ? :failed : :none) if deliveries.empty?
|
|
299
|
+
|
|
300
|
+
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
301
|
+
states = deliveries.map { |delivery| delivery.wait(deadline) }
|
|
302
|
+
return :timeout if states.include?(nil)
|
|
303
|
+
|
|
304
|
+
states.include?(:delivered) ? :delivered : :failed
|
|
305
|
+
end
|
|
306
|
+
|
|
147
307
|
# Blocks until every queued job has finished or the timeout elapses. Returns true when
|
|
148
|
-
# every lane drained in time
|
|
308
|
+
# every lane drained in time and no log send failed (after retries) since the last drained
|
|
309
|
+
# flush; false means a timeout or a lost log. A job that finished is not a job that delivered.
|
|
149
310
|
def flush(timeout = DEFAULT_FLUSH_TIMEOUT)
|
|
150
311
|
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
151
|
-
LANES.values.map { |lane| lane.flush(deadline) }.all?
|
|
312
|
+
drained = LANES.values.map { |lane| lane.flush(deadline) }.all?
|
|
313
|
+
drained && take_failures.zero?
|
|
314
|
+
end
|
|
315
|
+
|
|
316
|
+
# Called by a worker's send that gave up, so `flush` can report it.
|
|
317
|
+
def record_failure
|
|
318
|
+
@failure_mutex.synchronize do
|
|
319
|
+
forget_inherited_failures
|
|
320
|
+
@failures += 1
|
|
321
|
+
end
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
# True on a queue worker, whose sends are retried and tracked rather than run in the host's path.
|
|
325
|
+
def worker_thread?
|
|
326
|
+
LANES.each_value.any? { |lane| lane.thread == Thread.current }
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
# One condition-variable wait bounded by a monotonic deadline (the caller holds the mutex and
|
|
330
|
+
# re-checks its condition). False once the deadline has passed.
|
|
331
|
+
def wait_for(condition, mutex, deadline)
|
|
332
|
+
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
333
|
+
return false unless remaining.positive?
|
|
334
|
+
|
|
335
|
+
condition.wait(mutex, remaining)
|
|
336
|
+
true
|
|
152
337
|
end
|
|
153
338
|
|
|
154
339
|
# Testing-only: discard queued work and stop the workers.
|
|
155
340
|
def reset!
|
|
156
341
|
LANES.each_value(&:reset!)
|
|
342
|
+
DELIVERIES.clear
|
|
343
|
+
take_failures
|
|
157
344
|
end
|
|
158
345
|
|
|
159
346
|
private
|
|
160
347
|
|
|
161
|
-
|
|
162
|
-
|
|
348
|
+
# A tracked job that never reaches the queue must still settle, or waiters would hang on it.
|
|
349
|
+
def enqueue_or_abandon(lane, job)
|
|
350
|
+
lane.enqueue(job)
|
|
351
|
+
rescue StandardError
|
|
352
|
+
job.abandon if job.respond_to?(:abandon)
|
|
353
|
+
raise
|
|
163
354
|
end
|
|
164
355
|
|
|
165
|
-
def
|
|
166
|
-
|
|
356
|
+
def take_failures
|
|
357
|
+
@failure_mutex.synchronize do
|
|
358
|
+
forget_inherited_failures
|
|
359
|
+
@failures.tap { @failures = 0 }
|
|
360
|
+
end
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
# A forked child inherits the parent's count, but those sends were the parent's.
|
|
364
|
+
def forget_inherited_failures
|
|
365
|
+
return if @failures_pid == Process.pid
|
|
366
|
+
|
|
367
|
+
@failures_pid = Process.pid
|
|
368
|
+
@failures = 0
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
def async?
|
|
372
|
+
Coolhand.configuration.async_logging && !Coolhand.configuration.debug_mode && !worker_thread?
|
|
167
373
|
end
|
|
168
374
|
|
|
169
375
|
def register_at_exit
|
|
@@ -195,14 +195,15 @@ module Coolhand
|
|
|
195
195
|
module Helpers
|
|
196
196
|
module_function
|
|
197
197
|
|
|
198
|
-
|
|
198
|
+
NON_TRANSPORT_ERROR_MESSAGE = "[redacted: not a transport error]"
|
|
199
199
|
# Socket-level failures can surface inside the host's block (read_body runs there); they
|
|
200
200
|
# carry no app data, so they keep their message even when they pass through the host block.
|
|
201
|
+
# SocketError (DNS failures) is neither an IOError nor a SystemCallError, so it is listed too.
|
|
201
202
|
TRANSPORT_ERRORS = [
|
|
202
|
-
IOError, SystemCallError, Timeout::Error, Net::ProtocolError, OpenSSL::SSL::SSLError,
|
|
203
|
+
IOError, SystemCallError, SocketError, Timeout::Error, Net::ProtocolError, OpenSSL::SSL::SSLError,
|
|
203
204
|
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Zlib::Error
|
|
204
205
|
].freeze
|
|
205
|
-
private_constant :
|
|
206
|
+
private_constant :NON_TRANSPORT_ERROR_MESSAGE, :TRANSPORT_ERRORS
|
|
206
207
|
|
|
207
208
|
# Wraps the host's streaming block so (a) read_body only buffers the response being
|
|
208
209
|
# captured here, and (b) exceptions raised by the host's own code can be told apart from
|
|
@@ -220,20 +221,27 @@ module Coolhand
|
|
|
220
221
|
end
|
|
221
222
|
end
|
|
222
223
|
|
|
223
|
-
# Matched by class, so
|
|
224
|
-
# message too; accepted trade-off, as telling those
|
|
224
|
+
# Matched by class, so host code (the streaming block or a custom body_stream) raising its own
|
|
225
|
+
# IOError/SystemCallError subclass keeps its message too; accepted trade-off, as telling those
|
|
226
|
+
# apart from socket failures isn't possible.
|
|
225
227
|
def transport_error?(error)
|
|
226
228
|
TRANSPORT_ERRORS.any? { |klass| error.is_a?(klass) }
|
|
227
229
|
end
|
|
228
230
|
|
|
229
231
|
# An error raised by the host's streaming block can carry app-level data in its message (and
|
|
230
|
-
# in a #status or message-embedded status code), so
|
|
231
|
-
#
|
|
232
|
+
# in a #status or message-embedded status code), so no status is derived from it. Other errors
|
|
233
|
+
# (e.g. one raised by `super` itself) still have a status extracted. Independently of that,
|
|
234
|
+
# every non-transport error, whether from the streaming block or other host code such as a
|
|
235
|
+
# custom body_stream, is logged with only its class; transport errors keep their message.
|
|
236
|
+
# Returns [status, body].
|
|
232
237
|
def error_details(error, host_block_errors)
|
|
233
238
|
from_host = host_block_errors.any? { |host_error| host_error.equal?(error) }
|
|
234
239
|
status = from_host ? nil : extract_status_from_exception(error)
|
|
235
|
-
message =
|
|
240
|
+
message = transport_error?(error) ? error.message : NON_TRANSPORT_ERROR_MESSAGE
|
|
236
241
|
[status, { "error" => { "class" => error.class.name, "message" => message } }]
|
|
242
|
+
rescue StandardError
|
|
243
|
+
# A host exception whose #message or #status raises must not replace the host's own error.
|
|
244
|
+
[nil, { "error" => { "class" => error.class.name, "message" => NON_TRANSPORT_ERROR_MESSAGE } }]
|
|
237
245
|
end
|
|
238
246
|
|
|
239
247
|
def should_capture?
|
|
@@ -417,7 +425,9 @@ module Coolhand
|
|
|
417
425
|
return false unless google_api_host_configured?(addresses)
|
|
418
426
|
return false unless host == "googleapis.com" || host.end_with?(".googleapis.com")
|
|
419
427
|
|
|
420
|
-
|
|
428
|
+
# A colon action is always a path's last segment, so a pattern only matches at the end:
|
|
429
|
+
# a Cloud Storage object whose name merely contains ":generateContent" is not Gemini traffic.
|
|
430
|
+
Coolhand.configuration.intercept_path_patterns.any? { |p| path.end_with?(p) }
|
|
421
431
|
end
|
|
422
432
|
|
|
423
433
|
# The capture decision runs before the host's real request, so a bad config value (e.g. a
|
|
@@ -506,7 +516,9 @@ module Coolhand
|
|
|
506
516
|
|
|
507
517
|
url = "#{scheme}://#{host}"
|
|
508
518
|
url << ":#{port}" if port != default
|
|
509
|
-
|
|
519
|
+
path = req.path.to_s
|
|
520
|
+
path = "/#{path}" unless path.start_with?("/")
|
|
521
|
+
url << path
|
|
510
522
|
url
|
|
511
523
|
end
|
|
512
524
|
end
|
|
@@ -22,7 +22,8 @@ module Coolhand
|
|
|
22
22
|
def link_feedback(optimization_id, feedback_id, note: nil)
|
|
23
23
|
validate_id!("link_feedback", "feedback_id", feedback_id)
|
|
24
24
|
url = links_url("link_feedback", optimization_id)
|
|
25
|
-
|
|
25
|
+
result = request_json(:post, url, ERROR_NOUN, body: { feedback_id: feedback_id.strip, note: note }.compact)
|
|
26
|
+
ensure_json_object!(result, ERROR_NOUN)
|
|
26
27
|
end
|
|
27
28
|
|
|
28
29
|
# Lists over 100 ids are sent in batches; a failing batch raises and earlier ones stay applied,
|
|
@@ -56,18 +57,12 @@ module Coolhand
|
|
|
56
57
|
private
|
|
57
58
|
|
|
58
59
|
def merge_bulk_result!(totals, result)
|
|
59
|
-
|
|
60
|
+
ensure_json_object!(result, ERROR_NOUN)
|
|
60
61
|
|
|
61
62
|
%i[linked already_linked errored].each { |key| totals[key] += result[key].to_i }
|
|
62
63
|
totals[:not_found].concat(Array(result[:not_found]))
|
|
63
64
|
end
|
|
64
65
|
|
|
65
|
-
def ensure_object!(result)
|
|
66
|
-
raise Error, "#{ERROR_NOUN} response was not a JSON object" unless result.is_a?(Hash)
|
|
67
|
-
|
|
68
|
-
result
|
|
69
|
-
end
|
|
70
|
-
|
|
71
66
|
def links_url(method_name, optimization_id)
|
|
72
67
|
validate_id!(method_name, "optimization_id", optimization_id)
|
|
73
68
|
URI.parse("#{api_endpoint}/#{escape_path_segment(optimization_id.strip)}/feedback_links")
|