coolhand 0.12.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 +28 -0
- data/docs/anthropic.md +0 -1
- data/docs/configuration.md +8 -6
- data/docs/declared_workloads.md +1 -1
- data/docs/feedback.md +22 -1
- data/docs/openai.md +2 -0
- data/lib/coolhand/api_service.rb +45 -68
- data/lib/coolhand/base_interceptor.rb +24 -15
- data/lib/coolhand/configuration.rb +6 -0
- 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/post_delivery.rb +139 -0
- data/lib/coolhand/read_requests.rb +3 -0
- data/lib/coolhand/response_warnings.rb +11 -4
- 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 +4 -2
- metadata +3 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9906b58a2849265b01a3e2136f8fb71e42d60616082575d18b80f9b158c8e14f
|
|
4
|
+
data.tar.gz: 9225209cb6d52fadca9617ce83cb7c623af6b684730802b596530975996eaac0
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: b0415471072c6bd6123eeb70a1562415353e5bc54e91e022f7e9f52fd06912ddead12af018e27e995248578b783e3a03548722477f2cbe90e299e363f90c2cdc
|
|
7
|
+
data.tar.gz: 55b55edd36d5ebb2d537d9dccbf9b3ce54b1180849e66cff3b3d29ff3e400e7c9b320dda48461fc025ba2468f13376b1cccfedd6743ed69185b1b50b68cf139b
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.13.0] - 2026-11-25
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- `create_feedback(client_unique_id:)` now waits for its own log ([#233](https://github.com/Coolhand-Labs/coolhand-ruby/pull/233)). Logs are sent in the background, so feedback used to need a `Coolhand.flush` first or it could arrive before the log it refers to. Feedback that carries a `client_unique_id` now waits (up to 5 seconds) for the queued log with that id to finish sending, and only that log: unrelated traffic doesn't delay it. No `Coolhand.flush` is needed any more, and `docs/feedback.md`, `docs/declared_workloads.md` and `docs/anthropic.md` drop the workaround. This only covers logs queued in the same process; feedback sent from a different process still needs its log delivered first.
|
|
14
|
+
- `create_feedback(..., raise_on_error: true)` raises `Coolhand::HttpError` (with `status` and `body`) or `Coolhand::Error` instead of returning `nil` ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)). Fields can be passed as a Hash or as bare keywords. The success message now names the identifier used (for example `Client Unique ID: order-42.1`) instead of `ID: N/A`.
|
|
15
|
+
- Logs sent from the background queue retry transient failures (connect failure or timeout, HTTP 429, 502 or 503) twice with a short backoff ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)). A read timeout, connection reset or 504 is not retried, because the server may have stored the log and a retry could duplicate it.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
- **Behavior change:** if the log for a `client_unique_id` failed to send, `create_feedback` now logs a warning and returns `nil` without posting (or raises `Coolhand::Error` with `raise_on_error: true`), instead of sending feedback Coolhand can't match to a log ([#233](https://github.com/Coolhand-Labs/coolhand-ruby/pull/233)). The failed id is remembered (last 1,000) until a later log with that id sends successfully. If the log is still sending after 5 seconds, the feedback is sent anyway with a warning. Feedback without a `client_unique_id` behaves as before.
|
|
19
|
+
- **Behavior change:** `Coolhand.flush` returns `false` (once, until the next flush that drains) when a log was not delivered ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)): a send that failed after its retries, a queued job that raised, or a log dropped from a full queue. Code that treated `flush == true` as always-true will now see `false` after a lost log. A 2xx response with a blank or non-JSON body now counts as delivered. `create_feedback(hash, unknown_keyword: ...)` now raises `ArgumentError`, since a stray keyword next to a Hash is almost certainly a misspelled option.
|
|
20
|
+
- Redaction now also covers JSON that fails to parse ([#231](https://github.com/Coolhand-Labs/coolhand-ruby/pull/231)). A streamed response cut off mid-line (the `stream_incomplete` case) or a malformed JSON text body used to be logged as received, credentials included. The value of every credential-named string pair in it is now replaced with `[REDACTED]` in place, including a value cut off before its closing quote, and the rest of the partial text is kept. URL-valued fields and the `client_secret` object form are still only handled in JSON that parses (see `docs/configuration.md`).
|
|
21
|
+
- A Google `intercept_path_patterns` entry (such as `:generateContent`) now matches only at the end of the request path ([#229](https://github.com/Coolhand-Labs/coolhand-ruby/pull/229)). Before, any `googleapis.com` path that merely contained the pattern was captured, for example a Cloud Storage object named `notes:generateContent.txt`. If you added a custom pattern that is not a path suffix, it no longer matches.
|
|
22
|
+
- Errors raised by host code during `Net::HTTP#request` other than your streaming block (for example a custom `body_stream` whose `read` raises) are now logged with only their class and `[redacted: not a transport error]` as the message ([#228](https://github.com/Coolhand-Labs/coolhand-ruby/pull/228)). Transport errors keep their message, and `SocketError` (DNS failures) is now one of them.
|
|
23
|
+
- Hardening ([#230](https://github.com/Coolhand-Labs/coolhand-ruby/pull/230)): a `Bearer` authorization header is always logged as `Bearer [REDACTED]`, the body of a failed Coolhand API response is stripped of control, bidi and zero-width characters before it reaches your stdout or an `HttpError` message (`HttpError#body` stays the raw, length-capped body, so treat it as untrusted), and GET requests that read from Coolhand now have a 5 second `write_timeout`.
|
|
24
|
+
- Docs: `docs/configuration.md` notes that `exclude_api_patterns` is case-sensitive on purpose and what to do behind a case-insensitive gateway, and `docs/openai.md` notes that the batch processor keeps each input item's capped request body in memory until the output file is read ([#229](https://github.com/Coolhand-Labs/coolhand-ruby/pull/229)).
|
|
25
|
+
- Internal: the POST logic moved from `ApiService` into `Coolhand::PostDelivery` ([#234](https://github.com/Coolhand-Labs/coolhand-ruby/pull/234)).
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
- Credentials in URL-valued headers are redacted. A header value that holds a URL (`Location`, `Referer`, `Link`, an upload-URL header) went to Coolhand as is, so a presigned signature or API key in its query string was logged even though the request URL itself was scrubbed. They now go through the same query-string scrub as the request URL.
|
|
29
|
+
- A 2xx response from Coolhand whose body is the JSON literal `null` now counts as a delivered log, like a blank or non-JSON 2xx body. Before, it made the send look failed, so `Coolhand.flush` returned `false` and a `create_feedback` waiting on that `client_unique_id` was skipped, even though Coolhand had stored the log.
|
|
30
|
+
- `Coolhand.configuration.inspect` no longer prints the API key, so `p config` or a logged config object can't leak it.
|
|
31
|
+
- An exception raised by host code whose own `#message` or `#status` raises no longer replaces the host's original error while Coolhand records it.
|
|
32
|
+
- The logged URL no longer drops the `/` before a slash-less request path ([#235](https://github.com/Coolhand-Labs/coolhand-ruby/pull/235)). Requests that reach `Net::HTTP` with a path such as `v1/messages` (the Anthropic SDK's Bedrock client does this) were logged as `https://bedrock-runtime.us-east-1.amazonaws.comv1/messages`, which broke provider classification downstream. The same URL feeds the intercept check, so host and path matching now also work for slash-less paths, which were silently skipped before.
|
|
33
|
+
|
|
34
|
+
### Dependencies
|
|
35
|
+
- `ruby/setup-ruby` bumped to 1.343.0 in CI and the publish workflow ([#224](https://github.com/Coolhand-Labs/coolhand-ruby/pull/224)).
|
|
36
|
+
- `rubygems/release-gem` bumped to 1.4.2 in the publish workflow ([#225](https://github.com/Coolhand-Labs/coolhand-ruby/pull/225)).
|
|
37
|
+
|
|
10
38
|
## [0.12.0] - 2026-11-23
|
|
11
39
|
|
|
12
40
|
### Added
|
data/docs/anthropic.md
CHANGED
|
@@ -321,7 +321,6 @@ Coolhand.with_context(client_unique_id: "support-ticket-123.1") do
|
|
|
321
321
|
end
|
|
322
322
|
|
|
323
323
|
# The log is tagged with the id above, so feedback can be matched to that request
|
|
324
|
-
Coolhand.flush # logs are sent in the background; make sure this one has been delivered
|
|
325
324
|
Coolhand.feedback_service.create_feedback(
|
|
326
325
|
client_unique_id: "support-ticket-123.1",
|
|
327
326
|
sentiment: "like",
|
data/docs/configuration.md
CHANGED
|
@@ -52,8 +52,9 @@ Besides headers and URLs, Coolhand redacts credentials in the JSON body of both
|
|
|
52
52
|
Limits:
|
|
53
53
|
- A secret that is part of a URL's path (for example `https://actions.zapier.com/mcp/SECRET/sse`) cannot be detected generically and is sent as is.
|
|
54
54
|
- Parsed JSON objects and arrays are walked as described above. Subtrees nested more than 100 levels deep are replaced with `[REDACTED]`.
|
|
55
|
-
- A raw String body is checked in two cases: JSON text (e.g. a webhook body that is a JSON string) is parsed, redacted and re-serialized, and the JSON object/array payload on each `data:` line of a streamed (server-sent event) response is redacted the same way. A JSON payload is always re-serialized (compact, a repeated key keeps its last value), even when nothing in it was redacted, so its whitespace and string escapes may differ from the original and numbers are normalized to double precision (integers of any size are kept). Provider streams are compact JSON already, so they usually come through identical.
|
|
56
|
-
-
|
|
55
|
+
- A raw String body is checked in two cases (plus the fallback for JSON that does not parse, next): JSON text (e.g. a webhook body that is a JSON string) is parsed, redacted and re-serialized, and the JSON object/array payload on each `data:` line of a streamed (server-sent event) response is redacted the same way. A JSON payload is always re-serialized (compact, a repeated key keeps its last value), even when nothing in it was redacted, so its whitespace and string escapes may differ from the original and numbers are normalized to double precision (integers of any size are kept). Provider streams are compact JSON already, so they usually come through identical.
|
|
56
|
+
- JSON that does not parse, typically a stream cut off mid-line (see [Abandoned Streams](#abandoned-streams-stream_incomplete)), cannot be re-serialized, so it is kept as received except that the value of every credential-named string pair (the same key list and name matching as above) is replaced with `[REDACTED]` in place, including a value that was cut off before its closing quote. Only the key list is scrubbed: redactions that depend on the structure around a key are applied only to JSON that parses, namely URL-valued fields (so the userinfo and secret query parameters of any URL field in such a body are logged as received), the `client_secret` object form and the Realtime `{"value", "expires_at"}` ephemeral key, MCP tool `headers` maps, and Azure `data_sources`. The scan relies on the quoting being well formed up to the cut (as in any truncated stream), so a value after an unescaped quote inside an earlier string is not found, and only whitespace is recognized between a key, its colon and its value, so a pair with a JSON comment in between (some JSON parser versions accept them) is not found.
|
|
57
|
+
- Everything else in a String is sent as received: plain text, `[DONE]`, `event:`/`id:`/`retry:` and comment lines, a `data:` line that is not a JSON object or array, a JSON payload split across several `data:` lines (the continuation lines are not scanned), and newline-delimited JSON streams (no `data:` prefix), except that a whole body starting with `{` or `[` that does not parse as one document, such as a newline-delimited stream, gets the credential-named string scrub described above. Secrets inside free text such as model output are never detected.
|
|
57
58
|
- A String JSON payload nested more than 100 levels deep is replaced with `{"_coolhand_capture_skipped": "nesting_too_deep"}` (as JSON text, since it replaces text). If redacting a payload (or a whole String body) fails for any reason, it is replaced with `{"_coolhand_capture_skipped": "redaction_failed"}` rather than logged unchecked.
|
|
58
59
|
- Streamed bodies are capped by `max_captured_body_bytes` (see [Body Capture Limits](#body-capture-limits)) before redaction, so an over-limit stream is logged as the `body_too_large` placeholder and never scanned.
|
|
59
60
|
|
|
@@ -70,10 +71,11 @@ end
|
|
|
70
71
|
```
|
|
71
72
|
|
|
72
73
|
**How it behaves:**
|
|
73
|
-
- The queue is bounded at 1,000 pending logs. If Coolhand is down long enough to fill it, the *oldest* pending log is dropped (with a log line) rather than blocking your app or growing memory.
|
|
74
|
+
- The queue is bounded at 1,000 pending logs. If Coolhand is down long enough to fill it, the *oldest* pending log is dropped (with a log line) rather than blocking your app or growing memory; the next `Coolhand.flush` then returns `false`.
|
|
74
75
|
- The bound is on the *number* of pending logs, not their size: each holds its captured response body in memory until sent, so a long Coolhand outage under heavy traffic with large responses can hold a lot of memory. Batch jobs use their own lane, so a long-running batch never delays or evicts per-request logs.
|
|
75
76
|
- A forked process (Puma/Unicorn workers, Spring) starts its own worker automatically.
|
|
76
|
-
- Pending logs are flushed at process exit (up to 5 seconds in total, so a batch job still running at exit may be only partly logged). In a short-lived script, or to wait explicitly, call `Coolhand.flush(timeout: 5)` — it returns `true` once everything has been sent.
|
|
77
|
+
- Pending logs are flushed at process exit (up to 5 seconds in total, so a batch job still running at exit may be only partly logged). In a short-lived script, or to wait explicitly, call `Coolhand.flush(timeout: 5)` — it returns `true` once everything has been sent, and `false` if the timeout elapsed first **or** a log could not be delivered (see the retry bullet below).
|
|
78
|
+
- A queued log send that fails with a transient error (a connect failure or connect timeout, or HTTP 429/502/503) is retried twice with a short backoff (so during an outage each queued log can hold its lane for a few extra seconds). Failures where the log may already be stored (a read timeout, a connection reset, a 504) and other 4xx errors are not retried. A log that could not be delivered (a send that failed after retries, a queued job that raised, or a log dropped because the queue was full) makes the next `Coolhand.flush` return `false` (once; it reports failures since the previous flush). Inline sends (`async_logging = false`) are never retried.
|
|
77
79
|
- OpenAI and Vertex batch results are processed as a single background job per batch.
|
|
78
80
|
- `config.debug_mode` always runs inline so printed payloads appear in order.
|
|
79
81
|
- Logs queued but not yet sent are lost if the process is killed hard (`kill -9`, OOM). Set `async_logging = false` if you need delivery before each call returns.
|
|
@@ -138,7 +140,7 @@ Path-anchoring is also how the Azure defaults work: multi-service hosts like `co
|
|
|
138
140
|
|
|
139
141
|
**Note on Azure ML managed online endpoints:** `inference.ml.azure.com` and `inference.ml.azure.us` are intentionally captured *without* a path anchor. Every Azure ML managed online endpoint scores at `/score` regardless of what model sits behind it, so there's no path that distinguishes an LLM deployment from a tabular or vision one — this gem chooses to capture broadly rather than silently miss LLM deployments. If that over-captures for your setup, override `intercept_addresses` to a custom list omitting these two entries.
|
|
140
142
|
|
|
141
|
-
A small number of Google API endpoints use a colon-suffixed path (e.g. `.../gemini-pro:generateContent`) with no host of their own. Those live in the separate `intercept_path_patterns` setting (default: `Coolhand::Configuration::DEFAULT_INTERCEPT_PATH_PATTERNS`) and, unlike `intercept_addresses`, are only checked against the path of requests whose host is already `googleapis.com` or a subdomain of it — and only when `intercept_addresses` still includes at least one `googleapis.com` host. If you override `intercept_addresses` to a list with no Google hosts, `intercept_path_patterns` has no effect and Google API traffic is not captured at all.
|
|
143
|
+
A small number of Google API endpoints use a colon-suffixed path (e.g. `.../gemini-pro:generateContent`) with no host of their own. Those live in the separate `intercept_path_patterns` setting (default: `Coolhand::Configuration::DEFAULT_INTERCEPT_PATH_PATTERNS`) and, unlike `intercept_addresses`, are only checked against the end of the path of requests whose host is already `googleapis.com` or a subdomain of it (a request matches when its normalized path, query string excluded, ends with the pattern; a Cloud Storage object whose name merely contains `:generateContent` mid-name is not captured, though one whose name ends with it still is) — and only when `intercept_addresses` still includes at least one `googleapis.com` host. If you override `intercept_addresses` to a list with no Google hosts, `intercept_path_patterns` has no effect and Google API traffic is not captured at all.
|
|
142
144
|
|
|
143
145
|
`intercept_addresses` is a required allow-list — nothing is captured unless its host matches an entry here. Because of that, `config.intercept_addresses = []` is **not** a supported way to disable capture (it's ignored, with a warning logged, and the previous value is kept). To disable capture entirely, use `config.enabled = false` or `config.capture = false` instead — see [Capture Control](#capture-control) below.
|
|
144
146
|
|
|
@@ -154,7 +156,7 @@ Coolhand.configure do |config|
|
|
|
154
156
|
end
|
|
155
157
|
```
|
|
156
158
|
|
|
157
|
-
Before `exclude_api_patterns`, path-anchored `intercept_addresses` entries (like `api.cohere.com/v2/chat`, see above) and `intercept_path_patterns` are compared, the request path is normalized for matching only (the URL that is sent and logged is unchanged): repeated `/` are collapsed, `.` and `..` segments are resolved (never above the root), and percent-escapes of unreserved characters (`A-Z a-z 0-9 - . _ ~`) are decoded, so `/openai//files`, `/openai/./files` and `/openai/%66iles` are excluded just like `/openai/files`. Reserved escapes such as `%2F` stay encoded, and path matching remains case-sensitive. Your own patterns are compared literally, so write them in normalized form; an exclude pattern also fails closed, matching if either the raw or the normalized path contains it.
|
|
159
|
+
Before `exclude_api_patterns`, path-anchored `intercept_addresses` entries (like `api.cohere.com/v2/chat`, see above) and `intercept_path_patterns` are compared, the request path is normalized for matching only (the URL that is sent and logged is unchanged): repeated `/` are collapsed, `.` and `..` segments are resolved (never above the root), and percent-escapes of unreserved characters (`A-Z a-z 0-9 - . _ ~`) are decoded, so `/openai//files`, `/openai/./files` and `/openai/%66iles` are excluded just like `/openai/files`. Reserved escapes such as `%2F` stay encoded, and path matching remains case-sensitive. Case-sensitivity is deliberate, and the default patterns are written in the providers' canonical lowercase spelling; we have not verified that every covered provider rejects differently-cased paths. If a provider, or a gateway in front of it, routes paths case-insensitively, add the extra spellings to `exclude_api_patterns` yourself. Your own patterns are compared literally, so write them in normalized form; an exclude pattern also fails closed, matching if either the raw or the normalized path contains it.
|
|
158
160
|
|
|
159
161
|
Unlike `intercept_addresses`, `exclude_api_patterns` genuinely supports `= []` — since it only narrows an allow-list that already passed, an empty deny-list just means "exclude nothing," which is safe.
|
|
160
162
|
|
data/docs/declared_workloads.md
CHANGED
|
@@ -68,7 +68,7 @@ Coolhand.feedback_service.create_feedback(
|
|
|
68
68
|
|
|
69
69
|
- It must be a non-blank String of at most 255 characters with no control or invisible characters. An invalid value is **ignored** rather than raised: your block still runs and the call is logged, just without the id.
|
|
70
70
|
- Use an id that is unique per request (e.g. `"<call_id>.<n>"`). Every call inside the block carries the same id, so wrap one LLM call per block when you need to tell them apart.
|
|
71
|
-
- Logs are sent in the background by default, so
|
|
71
|
+
- Logs are sent in the background by default, so `create_feedback(client_unique_id:)` waits (up to 5 seconds) for the log with that id to finish sending before it sends the feedback; no `Coolhand.flush` is needed. If that log failed to send (remembered until a log with that id is sent successfully), the feedback is skipped and `create_feedback` returns `nil`. This only covers logs queued in the same process; when feedback is sent from another process, make sure the log was delivered first. Pass `raise_on_error: true` to get an exception instead of `nil` (see [docs/feedback.md](feedback.md#knowing-whether-feedback-was-delivered)).
|
|
72
72
|
- It travels as `llm_request_log.client_unique_id`, not inside `declared`, and it works without a `workload` or `template`.
|
|
73
73
|
- Matching happens on the Coolhand server, so whether the id is honoured depends on the server version. What happens when two logs share an id is also decided by the server.
|
|
74
74
|
|
data/docs/feedback.md
CHANGED
|
@@ -34,10 +34,31 @@ Coolhand.with_context(client_unique_id: 'order-42.1') do
|
|
|
34
34
|
client.chat(...) # logged with client_unique_id 'order-42.1'
|
|
35
35
|
end
|
|
36
36
|
|
|
37
|
-
Coolhand.flush # logs are sent in the background; make sure this one has been delivered
|
|
38
37
|
feedback_service.create_feedback(client_unique_id: 'order-42.1', sentiment: 'like')
|
|
39
38
|
```
|
|
40
39
|
|
|
40
|
+
Logs are sent in the background, so `create_feedback` holds the feedback until the log with that `client_unique_id` has finished sending (up to 5 seconds), then sends it. You don't need to call `Coolhand.flush` first. If that log's send failed (the failure is remembered for later `create_feedback` calls with that id, until a log with it is sent successfully), the feedback is not sent and `create_feedback` returns `nil`, because Coolhand never received the log. When several logs share an id, it waits for all of them and sends if any one was delivered. This ordering only covers logs queued in the same process; if you send feedback from a different process (a background job, say), make sure the log has been delivered first.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Knowing whether feedback was delivered
|
|
45
|
+
|
|
46
|
+
By default `create_feedback` never raises: on any failure (non-2xx response, network error, missing API key) it logs the problem, unless `config.silent` is set, and returns `nil`. On success it returns the parsed response, so `nil` means the feedback was not stored (or, in `debug_mode`, was deliberately not sent).
|
|
47
|
+
|
|
48
|
+
Pass `raise_on_error: true` when you need to tell lost feedback from delivered feedback, for example to retry:
|
|
49
|
+
|
|
50
|
+
```ruby
|
|
51
|
+
begin
|
|
52
|
+
feedback_service.create_feedback(client_unique_id: 'order-42.1', sentiment: 'like', raise_on_error: true)
|
|
53
|
+
rescue Coolhand::HttpError => e
|
|
54
|
+
e.status # 422, 500, ...: the API's answer (e.body has the response body)
|
|
55
|
+
rescue Coolhand::Error => e
|
|
56
|
+
# no API key, or a network error
|
|
57
|
+
end
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Feedback is never retried automatically, because repeating the POST could store it twice; retrying is up to you. With a `client_unique_id`, `create_feedback` already waits for that log when it was queued in the same process, and with `raise_on_error: true` it raises a `Coolhand::Error` instead of returning `nil` when that log failed to send. A `client_unique_id` that matches no log yet is the common reason to retry feedback sent from another process: make sure the log was delivered first (`Coolhand.flush` in the process that logged it returns `false` when a queued log was not delivered: it failed to send after retrying transient errors, raised in its job, or was dropped from a full queue).
|
|
61
|
+
|
|
41
62
|
---
|
|
42
63
|
|
|
43
64
|
## Field Reference
|
data/docs/openai.md
CHANGED
|
@@ -71,6 +71,8 @@ Each batch item is logged with `source_api: "openai"` and the `model` from the i
|
|
|
71
71
|
|
|
72
72
|
Each item's request body and response body are capped separately by [`max_captured_body_bytes`](configuration.md#body-capture-limits): one over the limit is logged as a `{"_coolhand_capture_skipped" => "body_too_large", ...}` placeholder (the item itself is still logged, and `model` is still taken from the full request body). See [Body Capture Limits](configuration.md#body-capture-limits) for the other placeholders. When the OpenAI client returns a result file as a String or IO, it is read and parsed one JSONL line at a time; a client that returns the file already parsed (`ruby-openai` does) has loaded it in full before Coolhand sees it. A malformed line is skipped and counted in an error log, and the other lines are still processed.
|
|
73
73
|
|
|
74
|
+
To match each output line to its request, Coolhand keeps every input item's (capped) request body in memory until the output file has been read, so peak memory in the process that handled the webhook scales with the size of the batch input (OpenAI limits an input file to 200 MB and 50,000 requests). The work normally runs on the background log queue (inline when `async_logging` is `false` or `debug_mode` is on), and either way it shares your web process's memory. If that matters for very large batches, lower [`max_captured_body_bytes`](configuration.md#body-capture-limits) (an item over the limit is kept as a small placeholder) or run the webhook on a worker process with headroom.
|
|
75
|
+
|
|
74
76
|
The batch ID from the webhook payload and the batch's input/output file IDs are used in calls to the OpenAI API with your `OPENAI_API_KEY`, so they are format-checked first (`batch_...` and `file-...`/`file_...`, letters, digits, `_` and `-` only). An event or batch whose IDs don't match is ignored with an error in `Rails.logger`.
|
|
75
77
|
|
|
76
78
|
## Signature header and secret rotation
|
data/lib/coolhand/api_service.rb
CHANGED
|
@@ -5,6 +5,8 @@ require "uri"
|
|
|
5
5
|
require "json"
|
|
6
6
|
require_relative "collector"
|
|
7
7
|
require_relative "errors"
|
|
8
|
+
require_relative "log_queue"
|
|
9
|
+
require_relative "post_delivery"
|
|
8
10
|
require_relative "read_requests"
|
|
9
11
|
require_relative "response_warnings"
|
|
10
12
|
|
|
@@ -14,11 +16,23 @@ module Coolhand
|
|
|
14
16
|
# log and return nil.
|
|
15
17
|
include ReadRequests
|
|
16
18
|
include ResponseWarnings
|
|
19
|
+
include PostDelivery
|
|
17
20
|
|
|
18
21
|
# Caps how much of a failed response body is interpolated into a log line or an exception
|
|
19
22
|
# message. Without it an oversized body from a proxy or gateway becomes the message.
|
|
20
23
|
ERROR_BODY_LIMIT = 2000
|
|
21
24
|
|
|
25
|
+
# How much of a failed response body is sanitized before it is cut to ERROR_BODY_LIMIT
|
|
26
|
+
# characters (a character is at most 4 bytes).
|
|
27
|
+
ERROR_BODY_SCAN_BYTES = ERROR_BODY_LIMIT * 4
|
|
28
|
+
|
|
29
|
+
FEEDBACK_ID_LABELS = {
|
|
30
|
+
llm_request_log_id: "LLM Request Log ID",
|
|
31
|
+
llm_provider_unique_id: "Provider Unique ID",
|
|
32
|
+
client_unique_id: "Client Unique ID"
|
|
33
|
+
}.freeze
|
|
34
|
+
private_constant :FEEDBACK_ID_LABELS
|
|
35
|
+
|
|
22
36
|
attr_reader :api_endpoint
|
|
23
37
|
|
|
24
38
|
def initialize(endpoint = "v2/llm_request_logs")
|
|
@@ -38,7 +52,7 @@ module Coolhand
|
|
|
38
52
|
log JSON.pretty_generate(sanitize_payload_for_json(payload))
|
|
39
53
|
nil
|
|
40
54
|
else
|
|
41
|
-
result = send_request(payload, "✅ Successfully sent request metadata")
|
|
55
|
+
result = send_request(payload, "✅ Successfully sent request metadata", background: LogQueue.worker_thread?)
|
|
42
56
|
log_response_warnings(result)
|
|
43
57
|
result
|
|
44
58
|
end
|
|
@@ -78,53 +92,6 @@ module Coolhand
|
|
|
78
92
|
}
|
|
79
93
|
end
|
|
80
94
|
|
|
81
|
-
def send_request(payload, success_message)
|
|
82
|
-
return nil if missing_api_key?
|
|
83
|
-
|
|
84
|
-
uri = URI.parse(@api_endpoint)
|
|
85
|
-
http = Net::HTTP.new(uri.host, uri.port)
|
|
86
|
-
http.use_ssl = (uri.scheme == "https")
|
|
87
|
-
# Bound worst-case latency: with async_logging off this call happens inline in
|
|
88
|
-
# the intercepted request's path (otherwise it ties up the background log
|
|
89
|
-
# worker), so a slow/unreachable Coolhand backend must not hang for Ruby's
|
|
90
|
-
# ~60s Net::HTTP defaults (a stalled upload hits write_timeout).
|
|
91
|
-
http.open_timeout = 5
|
|
92
|
-
http.read_timeout = 5
|
|
93
|
-
http.write_timeout = 5
|
|
94
|
-
|
|
95
|
-
request = Net::HTTP::Post.new(uri.request_uri)
|
|
96
|
-
apply_headers(request, create_request_options(payload))
|
|
97
|
-
|
|
98
|
-
# Clean payload and ensure UTF-8 encoding before JSON generation
|
|
99
|
-
cleaned_payload = sanitize_payload_for_json(payload)
|
|
100
|
-
json_body = JSON.generate(cleaned_payload)
|
|
101
|
-
|
|
102
|
-
# Ensure the request body is properly encoded as UTF-8
|
|
103
|
-
request.body = json_body.force_encoding("UTF-8")
|
|
104
|
-
|
|
105
|
-
begin
|
|
106
|
-
# This request goes through the same patched Net::HTTP as the host
|
|
107
|
-
# app's real LLM calls. Without this, a base_url/intercept_addresses
|
|
108
|
-
# configuration that also matches Coolhand's own API host would
|
|
109
|
-
# re-intercept this log-shipping call, generating a second log
|
|
110
|
-
# request that itself gets intercepted, and so on — unbounded
|
|
111
|
-
# request amplification.
|
|
112
|
-
response = Coolhand.without_capture { http.request(request) }
|
|
113
|
-
|
|
114
|
-
if response.is_a?(Net::HTTPSuccess)
|
|
115
|
-
result = JSON.parse(response.body, symbolize_names: true)
|
|
116
|
-
log success_message
|
|
117
|
-
result
|
|
118
|
-
else
|
|
119
|
-
log "❌ Request failed: #{response.code} - #{format_error_body(response.body)}"
|
|
120
|
-
nil
|
|
121
|
-
end
|
|
122
|
-
rescue StandardError => e
|
|
123
|
-
log "❌ Request error: #{e.message}"
|
|
124
|
-
nil
|
|
125
|
-
end
|
|
126
|
-
end
|
|
127
|
-
|
|
128
95
|
def log(*args)
|
|
129
96
|
puts args.join(" ") unless silent
|
|
130
97
|
end
|
|
@@ -133,8 +100,10 @@ module Coolhand
|
|
|
133
100
|
log("═" * 60) unless silent
|
|
134
101
|
end
|
|
135
102
|
|
|
136
|
-
|
|
137
|
-
|
|
103
|
+
# Returns the parsed response, or nil on failure (and in debug mode, where nothing is sent). With
|
|
104
|
+
# `raise_on_error`, a failure raises {Coolhand::HttpError} / {Coolhand::Error} instead.
|
|
105
|
+
def create_feedback(feedback, collection_method = nil, raise_on_error: false)
|
|
106
|
+
return reject_missing_key(raise_on_error) if !debug_mode? && missing_api_key?
|
|
138
107
|
|
|
139
108
|
normalized = normalize_feedback_sentiment(feedback)
|
|
140
109
|
feedback_with_collector = add_collector_to_data(normalized, collection_method)
|
|
@@ -151,10 +120,8 @@ module Coolhand
|
|
|
151
120
|
log JSON.pretty_generate(payload)
|
|
152
121
|
nil
|
|
153
122
|
else
|
|
154
|
-
result = send_request(
|
|
155
|
-
|
|
156
|
-
"✅ Successfully created feedback with ID: #{feedback[:llm_request_log_id] || 'N/A'}"
|
|
157
|
-
)
|
|
123
|
+
result = send_request(payload, "✅ Successfully created feedback #{feedback_identifier(feedback)}".strip,
|
|
124
|
+
raise_on_error: raise_on_error)
|
|
158
125
|
|
|
159
126
|
log_separator
|
|
160
127
|
|
|
@@ -179,10 +146,7 @@ module Coolhand
|
|
|
179
146
|
log JSON.pretty_generate(payload)
|
|
180
147
|
nil
|
|
181
148
|
else
|
|
182
|
-
result = send_request(
|
|
183
|
-
payload,
|
|
184
|
-
"✅ Successfully logged to API"
|
|
185
|
-
)
|
|
149
|
+
result = send_request(payload, "✅ Successfully logged to API", background: LogQueue.worker_thread?)
|
|
186
150
|
|
|
187
151
|
puts "✅ Successfully logged to API with ID: #{result[:id]}" if result && !silent
|
|
188
152
|
|
|
@@ -220,9 +184,12 @@ module Coolhand
|
|
|
220
184
|
def format_error_body(body)
|
|
221
185
|
return nil if body.nil?
|
|
222
186
|
|
|
223
|
-
|
|
187
|
+
# The body is server-controlled and ends up on the host's stdout, so strip control characters.
|
|
188
|
+
# Only a bounded prefix is sanitized, so a multi-megabyte body costs no more than a small one.
|
|
189
|
+
raw = body.to_s
|
|
190
|
+
text = strip_control_characters(raw.byteslice(0, ERROR_BODY_SCAN_BYTES))
|
|
224
191
|
return "#{text[0..200]}... [HTML error page truncated]" if text.include?("<!DOCTYPE html>")
|
|
225
|
-
return text if text.length <= ERROR_BODY_LIMIT
|
|
192
|
+
return text if text.length <= ERROR_BODY_LIMIT && raw.bytesize <= ERROR_BODY_SCAN_BYTES
|
|
226
193
|
|
|
227
194
|
"#{text[0, ERROR_BODY_LIMIT]}... [truncated]"
|
|
228
195
|
end
|
|
@@ -276,17 +243,27 @@ module Coolhand
|
|
|
276
243
|
feedback.except(:like).merge(sentiment: sentiment)
|
|
277
244
|
end
|
|
278
245
|
|
|
246
|
+
# The identifier the feedback is matched by, as [field, value]; nil when it has none.
|
|
247
|
+
def feedback_match(feedback)
|
|
248
|
+
field = FEEDBACK_ID_LABELS.keys.find { |name| feedback[name] }
|
|
249
|
+
[field, feedback[field]] if field
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# For the success message; "" when the feedback has no identifier.
|
|
253
|
+
def feedback_identifier(feedback)
|
|
254
|
+
field, value = feedback_match(feedback)
|
|
255
|
+
field ? "(#{FEEDBACK_ID_LABELS[field]}: #{value})" : ""
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def feedback_announcement(feedback)
|
|
259
|
+
field, value = feedback_match(feedback)
|
|
260
|
+
field ? "\n📝 CREATING FEEDBACK for #{FEEDBACK_ID_LABELS[field]}: #{value}" : "\n📝 CREATING FEEDBACK"
|
|
261
|
+
end
|
|
262
|
+
|
|
279
263
|
def log_feedback_info(feedback)
|
|
280
264
|
return if silent
|
|
281
265
|
|
|
282
|
-
|
|
283
|
-
if feedback[:llm_request_log_id]
|
|
284
|
-
puts "\n📝 CREATING FEEDBACK for LLM Request Log ID: #{feedback[:llm_request_log_id]}"
|
|
285
|
-
elsif feedback[:llm_provider_unique_id]
|
|
286
|
-
puts "\n📝 CREATING FEEDBACK for Provider Unique ID: #{feedback[:llm_provider_unique_id]}"
|
|
287
|
-
else
|
|
288
|
-
puts "\n📝 CREATING FEEDBACK"
|
|
289
|
-
end
|
|
266
|
+
puts feedback_announcement(feedback)
|
|
290
267
|
|
|
291
268
|
puts "💬 Sentiment: #{feedback[:sentiment]}" if feedback[:sentiment]
|
|
292
269
|
|
|
@@ -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+.+/im, "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
|
|
@@ -273,9 +281,10 @@ module Coolhand
|
|
|
273
281
|
request_data[:declared] = declared if declared && !declared.empty?
|
|
274
282
|
request_data[:client_unique_id] = client_unique_id if client_unique_id
|
|
275
283
|
|
|
276
|
-
LogQueue.submit do
|
|
277
|
-
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)
|
|
278
286
|
Coolhand.log "📤 Sent complete request/response log for #{request_id} (duration: #{duration_ms}ms)"
|
|
287
|
+
result
|
|
279
288
|
end
|
|
280
289
|
rescue StandardError => e
|
|
281
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,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
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
require_relative "errors"
|
|
7
|
+
require_relative "log_queue"
|
|
8
|
+
|
|
9
|
+
module Coolhand
|
|
10
|
+
# The POST half of {ApiService}: the logging writes (logs and feedback). Failures are logged and
|
|
11
|
+
# swallowed (`nil`) so instrumentation can't break the host app, unless the caller opts in with
|
|
12
|
+
# `raise_on_error:`. Sends made from a {LogQueue} worker retry transient failures and report an
|
|
13
|
+
# unrecovered one to {LogQueue}, so `Coolhand.flush` can say the logs were not delivered. Mix into
|
|
14
|
+
# an {ApiService}: it relies on `api_key`, `log`, `apply_headers`, `format_error_body`,
|
|
15
|
+
# `sanitize_payload_for_json` and {ReadRequests#raise_http_error} from there.
|
|
16
|
+
module PostDelivery
|
|
17
|
+
# Retries after the first attempt, and the base of the linear backoff between them.
|
|
18
|
+
LOG_SEND_RETRIES = 2
|
|
19
|
+
RETRY_BACKOFF = 0.5
|
|
20
|
+
# Failures where the log was most likely not stored: the connection never opened, or a proxy or
|
|
21
|
+
# the server turned the request away. A read timeout, a connection reset or a 504 are ambiguous
|
|
22
|
+
# (the server may have stored the log), so they are not retried: a retry could duplicate it.
|
|
23
|
+
RETRYABLE_ERRORS = [Net::OpenTimeout, SocketError, Errno::ECONNREFUSED].freeze
|
|
24
|
+
RETRYABLE_STATUSES = [429, 502, 503].freeze
|
|
25
|
+
MISSING_KEY_MESSAGE = "Request failed: an API key is required"
|
|
26
|
+
|
|
27
|
+
protected
|
|
28
|
+
|
|
29
|
+
# Returns the parsed response on success. On failure returns nil, or raises {Coolhand::HttpError}
|
|
30
|
+
# (non-2xx) / {Coolhand::Error} (everything else) when `raise_on_error`. `background` marks a
|
|
31
|
+
# send from a queue worker: it is retried and its failure recorded for `Coolhand.flush`.
|
|
32
|
+
def send_request(payload, success_message, raise_on_error: false, background: false)
|
|
33
|
+
return reject_missing_key(raise_on_error) if missing_api_key?
|
|
34
|
+
|
|
35
|
+
attempt_send(payload, success_message, raise_on_error: raise_on_error, background: background)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def reject_missing_key(raise_on_error)
|
|
39
|
+
raise Error, MISSING_KEY_MESSAGE if raise_on_error
|
|
40
|
+
|
|
41
|
+
nil
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
private
|
|
45
|
+
|
|
46
|
+
def attempt_send(payload, success_message, raise_on_error:, background:)
|
|
47
|
+
result = deliver(build_post(payload), background ? LOG_SEND_RETRIES : 0)
|
|
48
|
+
rescue StandardError => e
|
|
49
|
+
fail_send(e, raise_on_error: raise_on_error, background: background)
|
|
50
|
+
else
|
|
51
|
+
announce_success(success_message)
|
|
52
|
+
result
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Outside the rescue above: a failing log write (a closed stdout) must not turn a delivered
|
|
56
|
+
# request into a failure, nor raise into the host app.
|
|
57
|
+
def announce_success(message)
|
|
58
|
+
log message
|
|
59
|
+
rescue StandardError
|
|
60
|
+
nil
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def build_post(payload)
|
|
64
|
+
uri = URI.parse(@api_endpoint)
|
|
65
|
+
request = Net::HTTP::Post.new(uri.request_uri)
|
|
66
|
+
apply_headers(request, create_request_options(payload))
|
|
67
|
+
# Clean payload and ensure UTF-8 encoding before JSON generation
|
|
68
|
+
request.body = JSON.generate(sanitize_payload_for_json(payload)).force_encoding("UTF-8")
|
|
69
|
+
[uri, request]
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def deliver(built, retries)
|
|
73
|
+
attempts = 0
|
|
74
|
+
begin
|
|
75
|
+
post_once(*built)
|
|
76
|
+
rescue StandardError => e
|
|
77
|
+
attempts += 1
|
|
78
|
+
raise unless attempts <= retries && transient?(e)
|
|
79
|
+
|
|
80
|
+
log "⚠️ Request failed (#{e.message}); retrying (#{attempts}/#{retries})"
|
|
81
|
+
sleep(RETRY_BACKOFF * attempts)
|
|
82
|
+
retry
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def post_once(uri, request)
|
|
87
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
88
|
+
http.use_ssl = (uri.scheme == "https")
|
|
89
|
+
# Bound worst-case latency: with async_logging off this call happens inline in
|
|
90
|
+
# the intercepted request's path (otherwise it ties up the background log
|
|
91
|
+
# worker), so a slow/unreachable Coolhand backend must not hang for Ruby's
|
|
92
|
+
# ~60s Net::HTTP defaults (a stalled upload hits write_timeout).
|
|
93
|
+
http.open_timeout = 5
|
|
94
|
+
http.read_timeout = 5
|
|
95
|
+
http.write_timeout = 5
|
|
96
|
+
|
|
97
|
+
# This request goes through the same patched Net::HTTP as the host
|
|
98
|
+
# app's real LLM calls. Without this, a base_url/intercept_addresses
|
|
99
|
+
# configuration that also matches Coolhand's own API host would
|
|
100
|
+
# re-intercept this log-shipping call, generating a second log
|
|
101
|
+
# request that itself gets intercepted, and so on — unbounded
|
|
102
|
+
# request amplification.
|
|
103
|
+
response = Coolhand.without_capture { http.request(request) }
|
|
104
|
+
raise_http_error(response, "Coolhand API") unless response.is_a?(Net::HTTPSuccess)
|
|
105
|
+
|
|
106
|
+
parse_success_body(response.body)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# The server already accepted the request, so a blank, non-JSON or `null` 2xx body (a 204, say) is
|
|
110
|
+
# still a delivery: reporting it as a failure would make a retrying caller store it twice.
|
|
111
|
+
def parse_success_body(body)
|
|
112
|
+
JSON.parse(body.to_s, symbolize_names: true) || {}
|
|
113
|
+
rescue JSON::ParserError
|
|
114
|
+
{}
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def transient?(error)
|
|
118
|
+
return RETRYABLE_STATUSES.include?(error.status) if error.is_a?(HttpError)
|
|
119
|
+
|
|
120
|
+
RETRYABLE_ERRORS.any? { |klass| error.is_a?(klass) }
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def fail_send(error, raise_on_error:, background:)
|
|
124
|
+
log failure_message(error)
|
|
125
|
+
LogQueue.record_failure if background
|
|
126
|
+
return nil unless raise_on_error
|
|
127
|
+
|
|
128
|
+
raise error if error.is_a?(Error)
|
|
129
|
+
|
|
130
|
+
raise Error, "Request failed: #{error.message}"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def failure_message(error)
|
|
134
|
+
return "❌ Request error: #{error.message}" unless error.is_a?(HttpError)
|
|
135
|
+
|
|
136
|
+
"❌ Request failed: #{error.status} - #{format_error_body(error.body)}"
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
@@ -16,6 +16,8 @@ module Coolhand
|
|
|
16
16
|
# and one response runs several. A tighter read timeout pre-empts the 504 callers should retry.
|
|
17
17
|
READ_OPEN_TIMEOUT = 5
|
|
18
18
|
READ_TIMEOUT = 60
|
|
19
|
+
# A GET writes only its request line and headers, so a stalled write is a dead connection.
|
|
20
|
+
READ_WRITE_TIMEOUT = 5
|
|
19
21
|
|
|
20
22
|
# ERROR_BODY_LIMIT caps the message; this caps the body the exception object itself carries.
|
|
21
23
|
RETAINED_ERROR_BODY_LIMIT = 8_000
|
|
@@ -74,6 +76,7 @@ module Coolhand
|
|
|
74
76
|
http.use_ssl = (uri.scheme == "https")
|
|
75
77
|
http.open_timeout = READ_OPEN_TIMEOUT
|
|
76
78
|
http.read_timeout = READ_TIMEOUT
|
|
79
|
+
http.write_timeout = READ_WRITE_TIMEOUT
|
|
77
80
|
http
|
|
78
81
|
end
|
|
79
82
|
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module Coolhand
|
|
4
|
-
# Prints the `warnings` a Coolhand log response carries, for {ApiService}.
|
|
4
|
+
# Prints the `warnings` a Coolhand log response carries, for {ApiService}. Also owns
|
|
5
|
+
# `strip_control_characters`, which {ApiService#format_error_body} (and so every
|
|
6
|
+
# {ReadRequests}/{WriteRequests} caller) uses on the error body.
|
|
5
7
|
#
|
|
6
8
|
# Warnings come from the response body and are written to the host app's stdout, so they are
|
|
7
9
|
# untrusted: each is coerced to a string, stripped of control characters and length-capped, and
|
|
@@ -27,10 +29,15 @@ module Coolhand
|
|
|
27
29
|
# Control characters and line/paragraph separators are replaced with a space, not dropped: a
|
|
28
30
|
# newline would forge a log line and ESC starts a terminal escape sequence. Unicode format
|
|
29
31
|
# characters (bidi overrides, zero-width) are invisible and can reorder or hide text in a
|
|
30
|
-
# terminal, so they are removed outright.
|
|
32
|
+
# terminal, so they are removed outright. Shared with ApiService#format_error_body, which
|
|
33
|
+
# prints another server-controlled string.
|
|
34
|
+
def strip_control_characters(value)
|
|
35
|
+
text = value.to_s.dup.force_encoding("UTF-8").scrub
|
|
36
|
+
text.gsub(/\p{Cf}+/, "").gsub(/[[:cntrl:]\p{Zl}\p{Zp}]+/, " ").strip
|
|
37
|
+
end
|
|
38
|
+
|
|
31
39
|
def sanitize_warning(warning)
|
|
32
|
-
text = warning
|
|
33
|
-
text = text.gsub(/\p{Cf}+/, "").gsub(/[[:cntrl:]\p{Zl}\p{Zp}]+/, " ").strip
|
|
40
|
+
text = strip_control_characters(warning)
|
|
34
41
|
return text if text.length <= MAX_WARNING_LENGTH
|
|
35
42
|
|
|
36
43
|
"#{text[0, MAX_WARNING_LENGTH]}... [truncated]"
|
|
@@ -4,10 +4,13 @@ module Coolhand
|
|
|
4
4
|
# Redacts credentials in raw String bodies, which BodyRedactor's tree walk never sees: a streamed
|
|
5
5
|
# (server-sent event) response arrives as one String of `data: {...}` lines, and a webhook body
|
|
6
6
|
# may be raw JSON text. Each JSON object/array payload is parsed, run through BodyRedactor and
|
|
7
|
-
# re-serialized; text that is not JSON (plain text, `[DONE]`, `event:` and comment lines
|
|
8
|
-
#
|
|
9
|
-
#
|
|
10
|
-
#
|
|
7
|
+
# re-serialized; text that is not JSON (plain text, `[DONE]`, `event:` and comment lines) is left
|
|
8
|
+
# byte for byte. JSON that fails to parse (typically a stream cut off mid-line) cannot be
|
|
9
|
+
# re-serialized, so each credential-named string value in it is scrubbed in place instead: the
|
|
10
|
+
# rest of the partial text is kept, and an unterminated value is scrubbed to the end of the text.
|
|
11
|
+
# A JSON payload is always re-serialized, even when nothing in it needed redacting: JSON.parse
|
|
12
|
+
# keeps only the last of a repeated key, so "nothing changed" cannot be trusted to mean "no
|
|
13
|
+
# credential in the original text".
|
|
11
14
|
module StringBodyRedactor
|
|
12
15
|
module_function
|
|
13
16
|
|
|
@@ -19,6 +22,13 @@ module Coolhand
|
|
|
19
22
|
# a rewritten line keeps its own.
|
|
20
23
|
DATA_LINE = /(?<![^\r\n\uFEFF])data:([ \t]*)([^\r\n]*)/
|
|
21
24
|
JSON_CONTAINER = /\A\uFEFF?\s*[\[{]/
|
|
25
|
+
# Scans JSON text that may not parse, one string literal at a time: a `"key": "value"` pair
|
|
26
|
+
# (first alternative; the key is group 1, the separator group 2) or any other string literal
|
|
27
|
+
# (second alternative, consumed whole so a quote inside it never starts a new match and the
|
|
28
|
+
# scan stays linear even when a regex engine does not memoize, as before Ruby 3.2). A string
|
|
29
|
+
# ends at its closing quote, or at the end of the text when it was cut off (possibly right
|
|
30
|
+
# after a backslash).
|
|
31
|
+
STRING_PAIR = /("(?:[^"\\]|\\.)*")(\s*:\s*)"(?:[^"\\]|\\.)*(?:"|\\?\z)|"(?:[^"\\]|\\.)*(?:"|\\?\z)/m
|
|
22
32
|
|
|
23
33
|
def redact(body)
|
|
24
34
|
text = utf8_text(body)
|
|
@@ -45,22 +55,61 @@ module Coolhand
|
|
|
45
55
|
|
|
46
56
|
# One pass with gsub (linear in the body); the original String is returned when no line differs
|
|
47
57
|
# once re-serialized (providers emit compact JSON, so a clean stream usually round-trips as is).
|
|
58
|
+
# Text that starts like JSON but did not parse as one document (a body cut off mid-value) also
|
|
59
|
+
# has its credential-named string values scrubbed.
|
|
48
60
|
def redact_stream(body, text)
|
|
49
|
-
changed = false
|
|
50
61
|
redacted = text.gsub(DATA_LINE) do |line|
|
|
51
62
|
match = Regexp.last_match
|
|
52
|
-
payload =
|
|
63
|
+
payload = redact_payload(match[2])
|
|
53
64
|
next line if payload.nil? || payload == match[2]
|
|
54
65
|
|
|
55
|
-
changed = true
|
|
56
66
|
"data:#{match[1]}#{payload}"
|
|
57
67
|
end
|
|
58
|
-
|
|
68
|
+
redacted = scrub_credential_strings(redacted) if text.match?(JSON_CONTAINER)
|
|
69
|
+
redacted == text ? body : redacted
|
|
59
70
|
end
|
|
60
71
|
|
|
61
|
-
# The redacted
|
|
62
|
-
|
|
63
|
-
|
|
72
|
+
# The redacted text of a `data:` payload, or nil when it is not JSON-looking and stays as is.
|
|
73
|
+
def redact_payload(payload)
|
|
74
|
+
return unless payload.match?(JSON_CONTAINER)
|
|
75
|
+
|
|
76
|
+
redacted_json(payload) || scrub_credential_strings(payload)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Fallback for JSON text that did not parse: replaces the value of every credential-named
|
|
80
|
+
# string pair (see BodyRedactor::CREDENTIAL_BODY_KEYS) without needing a valid document.
|
|
81
|
+
# URL-valued keys and `client_secret` objects are only handled for parsed JSON.
|
|
82
|
+
def scrub_credential_strings(text)
|
|
83
|
+
text.gsub(STRING_PAIR) do |pair|
|
|
84
|
+
match = Regexp.last_match
|
|
85
|
+
next pair unless match[1] && credential_key?(match[1])
|
|
86
|
+
|
|
87
|
+
"#{match[1]}#{match[2]}#{JSON.generate(BaseInterceptor::REDACTED)}"
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# `quoted_key` is a JSON string literal, so decode it (`"\u0061pi_key"` names `api_key`).
|
|
92
|
+
def credential_key?(quoted_key)
|
|
93
|
+
BodyRedactor::CREDENTIAL_BODY_KEYS.include?(BodyRedactor.normalize_body_key(decode_key(quoted_key)))
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# A literal the JSON parser rejects (an invalid escape such as `\_`, a raw control character)
|
|
97
|
+
# is decoded leniently, the way older JSON versions did: `\uXXXX` becomes its character and any
|
|
98
|
+
# other backslash is dropped, so `"api\_key"` still names `api_key` and its value is scrubbed.
|
|
99
|
+
# `scrub` because a lone low surrogate (`"\udc00"`) parses to an invalid UTF-8 String, which
|
|
100
|
+
# String#delete would reject and fail the whole body closed instead of just this one key.
|
|
101
|
+
def decode_key(quoted_key)
|
|
102
|
+
JSON.parse(quoted_key).scrub
|
|
103
|
+
rescue JSON::ParserError
|
|
104
|
+
quoted_key[1..-2].gsub(/\\(?:u(\h{4})|(.))/m) do
|
|
105
|
+
hex, char = Regexp.last_match.captures
|
|
106
|
+
hex ? [hex.hex].pack("U") : char
|
|
107
|
+
end.scrub
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# The redacted, re-serialized JSON; nil when the text is not a parseable JSON object/array
|
|
111
|
+
# (callers fall back to scrub_credential_strings for the unparseable case). Anything else that
|
|
112
|
+
# goes wrong yields a `redaction_failed` marker rather than the unchecked text.
|
|
64
113
|
def redacted_json(text)
|
|
65
114
|
# NaN/Infinity are not JSON, but some servers emit them; a payload that failed to parse
|
|
66
115
|
# would be logged unredacted next to its credential-named fields.
|
data/lib/coolhand/version.rb
CHANGED
|
@@ -8,10 +8,10 @@ require_relative "read_requests"
|
|
|
8
8
|
|
|
9
9
|
module Coolhand
|
|
10
10
|
# POST/DELETE counterpart of {ReadRequests} for callers that act on the response: raises on any
|
|
11
|
-
# failure where {
|
|
11
|
+
# failure where {PostDelivery#send_request} logs and returns nil by default. Timeouts are the read ones, for
|
|
12
12
|
# the same server-side statement-bound reason. Mix into an {ApiService} subclass: it relies on
|
|
13
|
-
# `api_key`, `apply_headers` and `format_error_body`
|
|
14
|
-
# {ReadRequests}.
|
|
13
|
+
# `api_key`, `apply_headers` and `format_error_body` (which in turn needs {ResponseWarnings}'
|
|
14
|
+
# `strip_control_characters`) from there and the shared HTTP helpers from {ReadRequests}.
|
|
15
15
|
module WriteRequests
|
|
16
16
|
DOT_SEGMENTS = [".", ".."].freeze
|
|
17
17
|
|
data/lib/coolhand.rb
CHANGED
|
@@ -112,8 +112,10 @@ module Coolhand
|
|
|
112
112
|
end
|
|
113
113
|
|
|
114
114
|
# Blocks until log requests queued by async logging have been sent, or the timeout (in
|
|
115
|
-
# seconds) elapses. Returns true if everything was sent
|
|
116
|
-
#
|
|
115
|
+
# seconds) elapses. Returns true if everything was sent, false on a timeout or if a log was
|
|
116
|
+
# not delivered (a send that failed after retrying transient errors, a job that raised, or a
|
|
117
|
+
# log dropped from a full queue) since the previous flush that drained.
|
|
118
|
+
# Pending logs are also flushed automatically at process exit.
|
|
117
119
|
def flush(timeout: LogQueue::DEFAULT_FLUSH_TIMEOUT)
|
|
118
120
|
LogQueue.flush(timeout)
|
|
119
121
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: coolhand
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.13.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Michael Carroll
|
|
@@ -9,7 +9,7 @@ authors:
|
|
|
9
9
|
autorequire:
|
|
10
10
|
bindir: exe
|
|
11
11
|
cert_chain: []
|
|
12
|
-
date: 2026-11-
|
|
12
|
+
date: 2026-11-25 00:00:00.000000000 Z
|
|
13
13
|
dependencies:
|
|
14
14
|
- !ruby/object:Gem::Dependency
|
|
15
15
|
name: base64
|
|
@@ -85,6 +85,7 @@ files:
|
|
|
85
85
|
- lib/coolhand/optimization_feedback_link_service.rb
|
|
86
86
|
- lib/coolhand/pagination.rb
|
|
87
87
|
- lib/coolhand/path_normalizer.rb
|
|
88
|
+
- lib/coolhand/post_delivery.rb
|
|
88
89
|
- lib/coolhand/rails_auto_declare.rb
|
|
89
90
|
- lib/coolhand/railtie.rb
|
|
90
91
|
- lib/coolhand/read_query.rb
|