coolhand 0.10.0 → 0.11.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.
@@ -1,23 +1,40 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "net/http"
4
+ require "openssl"
3
5
  require "stringio"
6
+ require "timeout"
7
+ require "zlib"
8
+
9
+ require_relative "body_stream_tap"
10
+ require_relative "path_normalizer"
11
+ require_relative "stream_read"
4
12
 
5
13
  module Coolhand
6
14
  module NetHttpInterceptor
7
15
  # Response streaming interceptor nested under NetHttpInterceptor
8
16
  module ResponseInterceptor
9
17
  def read_body(dest = nil, &block)
10
- # Only buffer while a #request call below is actively capturing —
11
- # otherwise every block-form read_body in the process (including
12
- # ones on responses this gem never intercepted) accumulates into a
13
- # thread-local that's never freed, which is an unbounded memory
14
- # leak on any thread that streams large non-LLM responses.
15
- return super unless block && Thread.current[:coolhand_capturing_stream]
16
-
17
- super do |chunk|
18
- Thread.current[:coolhand_stream_buffer] ||= +""
19
- Thread.current[:coolhand_stream_buffer] << chunk
20
- yield(chunk)
18
+ # Only buffer this exact response while a #request call below is
19
+ # actively capturing it — otherwise every block-form read_body in
20
+ # the process (including ones on responses this gem never
21
+ # intercepted, such as a nested request made from inside the host's
22
+ # streaming block) accumulates into a thread-local that's never
23
+ # freed, and leaks one request's chunks into another's log.
24
+ return super unless block && Thread.current[:coolhand_capturing_stream].equal?(self)
25
+
26
+ finished = false
27
+ begin
28
+ result = super do |chunk|
29
+ Helpers.buffer_stream_chunk(chunk)
30
+ yield(chunk)
31
+ end
32
+ finished = true
33
+ result
34
+ ensure
35
+ # Also runs when the host's block breaks, throws or raises: read_body then never reached the
36
+ # end of the body, which is what marks the log stream_incomplete.
37
+ StreamRead.record(finished)
21
38
  end
22
39
  end
23
40
  end
@@ -118,23 +135,34 @@ module Coolhand
118
135
  # chunks, mixing one request's content into another's log.
119
136
  previous_stream_buffer = Thread.current[:coolhand_stream_buffer]
120
137
  previous_capturing_stream = Thread.current[:coolhand_capturing_stream]
138
+ previous_stream_read = Thread.current[:coolhand_stream_read]
121
139
  Thread.current[:coolhand_stream_buffer] = nil
122
- Thread.current[:coolhand_capturing_stream] = true
140
+ Thread.current[:coolhand_capturing_stream] = nil
141
+ Thread.current[:coolhand_stream_read] = nil
142
+ host_block_errors = []
143
+ tracked_block = Helpers.track_streaming_block(block, host_block_errors)
123
144
 
124
145
  begin
125
- response = super
126
- body_content = Thread.current[:coolhand_stream_buffer] || response&.body
127
- body_content = body_content.dup.force_encoding("UTF-8") if body_content.is_a?(String)
128
- status_code = response.respond_to?(:code) ? response.code.to_i : nil
129
- response_body = BaseInterceptor.parse_json(body_content)
146
+ response = super(req, body, &tracked_block)
147
+ status_code, response_body = Helpers.capture_response(response)
130
148
  rescue StandardError => e
131
- status_code = Helpers.extract_status_from_exception(e)
132
- response_body = { "error" => { "class" => e.class.name, "message" => e.message } }
149
+ status_code, response_body = Helpers.error_details(e, host_block_errors)
133
150
  raise
134
151
  ensure
152
+ # First, so the host's own stream is back on its request whatever fails below.
153
+ request_body = Helpers.finalize_request_body(captured_body, req)
154
+ stream_incomplete = StreamRead.incomplete?
155
+ # A stream abandoned by break, throw or raise: what was buffered so far is logged (cleaned of a
156
+ # split multibyte character) instead of the error, or of the capture above after a break.
157
+ logged_response = response
158
+ if stream_incomplete
159
+ logged_response = Thread.current[:coolhand_capturing_stream]
160
+ status_code, response_body = StreamRead.partial_response(logged_response)
161
+ end
135
162
  active.delete(self)
136
163
  Thread.current[:coolhand_stream_buffer] = previous_stream_buffer
137
164
  Thread.current[:coolhand_capturing_stream] = previous_capturing_stream
165
+ Thread.current[:coolhand_stream_read] = previous_stream_read
138
166
  end_time = Time.now
139
167
  duration_ms = ((end_time - start_time) * 1000).round(2)
140
168
 
@@ -145,14 +173,15 @@ module Coolhand
145
173
  method: req.method,
146
174
  url: url,
147
175
  request_headers: BaseInterceptor.sanitize_headers(req),
148
- request_body: captured_body,
149
- response_headers: BaseInterceptor.sanitize_headers(response),
176
+ request_body: request_body,
177
+ response_headers: BaseInterceptor.sanitize_headers(logged_response),
150
178
  response_body: response_body,
151
179
  status_code: status_code,
152
180
  start_time: start_time,
153
181
  end_time: end_time,
154
182
  duration_ms: duration_ms,
155
- is_streaming: !!block
183
+ is_streaming: !!block,
184
+ stream_incomplete: stream_incomplete
156
185
  )
157
186
  end
158
187
 
@@ -166,6 +195,47 @@ module Coolhand
166
195
  module Helpers
167
196
  module_function
168
197
 
198
+ HOST_BLOCK_ERROR_MESSAGE = "[redacted: raised in host streaming block]"
199
+ # Socket-level failures can surface inside the host's block (read_body runs there); they
200
+ # carry no app data, so they keep their message even when they pass through the host block.
201
+ TRANSPORT_ERRORS = [
202
+ IOError, SystemCallError, Timeout::Error, Net::ProtocolError, OpenSSL::SSL::SSLError,
203
+ Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Zlib::Error
204
+ ].freeze
205
+ private_constant :HOST_BLOCK_ERROR_MESSAGE, :TRANSPORT_ERRORS
206
+
207
+ # Wraps the host's streaming block so (a) read_body only buffers the response being
208
+ # captured here, and (b) exceptions raised by the host's own code can be told apart from
209
+ # transport errors (see TRANSPORT_ERRORS). Returns nil when there is no block.
210
+ def track_streaming_block(block, host_block_errors)
211
+ return unless block
212
+
213
+ proc do |res|
214
+ Thread.current[:coolhand_capturing_stream] = res
215
+ Thread.current[:coolhand_stream_read] = nil
216
+ block.call(res)
217
+ rescue StandardError => e
218
+ host_block_errors << e unless transport_error?(e)
219
+ raise
220
+ end
221
+ end
222
+
223
+ # Matched by class, so a host block raising its own IOError/SystemCallError subclass keeps its
224
+ # message too; accepted trade-off, as telling those apart from socket failures isn't possible.
225
+ def transport_error?(error)
226
+ TRANSPORT_ERRORS.any? { |klass| error.is_a?(klass) }
227
+ end
228
+
229
+ # 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 only its class is logged and no status is
231
+ # derived from it; transport errors keep their message and status. Returns [status, body].
232
+ def error_details(error, host_block_errors)
233
+ from_host = host_block_errors.any? { |host_error| host_error.equal?(error) }
234
+ status = from_host ? nil : extract_status_from_exception(error)
235
+ message = from_host ? HOST_BLOCK_ERROR_MESSAGE : error.message
236
+ [status, { "error" => { "class" => error.class.name, "message" => message } }]
237
+ end
238
+
169
239
  def should_capture?
170
240
  return true if Coolhand.configuration.debug_mode
171
241
 
@@ -184,24 +254,132 @@ module Coolhand
184
254
 
185
255
  content = body || req.body
186
256
  if content.nil? && req.respond_to?(:body_stream) && req.body_stream
187
- content = req.body_stream.read
188
- req.body_stream = StringIO.new(content)
257
+ result = capture_body_stream(req)
258
+ return result unless result.is_a?(String)
259
+
260
+ content = result
189
261
  end
190
262
  return nil if content.nil?
191
263
 
192
264
  cap_and_parse(content, req)
193
265
  end
194
266
 
267
+ # A body_stream request: the log body (a marker, or the BodyStreamTap resolved after the send),
268
+ # or the stream's content as a String when it was read here and still needs cap_and_parse.
269
+ def capture_body_stream(req)
270
+ # A declared Content-Length over the cap means we never need the bytes: skip
271
+ # before .read so a huge stream is not buffered just to be discarded.
272
+ too_large = oversized_declared_length(req)
273
+ return too_large if too_large
274
+
275
+ # No usable Content-Length (chunked): the size is unknown, so don't read ahead. Tap the
276
+ # stream instead and build the log body once Net::HTTP has sent it (finalize_request_body).
277
+ unless declared_content_length(req)
278
+ return skipped_capture_marker(req, "unsupported_body_stream") unless BodyStreamTap.tappable?(req.body_stream)
279
+
280
+ return BodyStreamTap.install(req)
281
+ end
282
+
283
+ content = req.body_stream.read
284
+ req.body_stream = StringIO.new(content)
285
+ content
286
+ end
287
+
288
+ # The effective cap: nil disables it; a non-Integer or negative value (e.g. an unparsed
289
+ # ENV string) falls back to the default rather than raising into the host's request or stream.
290
+ def capture_limit
291
+ limit = Coolhand.configuration.max_captured_body_bytes
292
+ return limit if limit.nil? || (limit.is_a?(Integer) && !limit.negative?)
293
+
294
+ Coolhand::Configuration::DEFAULT_MAX_CAPTURED_BODY_BYTES
295
+ end
296
+
297
+ def over_capture_limit?(size)
298
+ limit = capture_limit
299
+ !limit.nil? && size > limit
300
+ end
301
+
302
+ def body_too_large_marker(carrier, size)
303
+ skipped_capture_marker(carrier, "body_too_large", size_bytes: size, max_bytes: capture_limit)
304
+ end
305
+
306
+ # Returns a body_too_large marker when the request declares a Content-Length above the
307
+ # cap, else nil. Chunked/absent/malformed lengths return nil (the caller then taps the
308
+ # stream, which enforces the cap on the bytes actually sent).
309
+ def oversized_declared_length(req)
310
+ length = declared_content_length(req)
311
+ body_too_large_marker(req, length) if length && over_capture_limit?(length)
312
+ end
313
+
314
+ # Net::HTTP sends a chunked body without regard to any Content-Length header, so it is not a
315
+ # declaration of what goes on the wire then.
316
+ def declared_content_length(req)
317
+ req.content_length if req.respond_to?(:content_length) && !req.chunked?
318
+ rescue StandardError
319
+ nil
320
+ end
321
+
322
+ # The request body for the log. A tapped body_stream (see BodyStreamTap.install) only has its
323
+ # content once the request has been attempted, so it is resolved here and the host's own
324
+ # stream is put back on the request. Runs in #request's ensure: it must not raise.
325
+ def finalize_request_body(captured, req)
326
+ return captured unless captured.is_a?(BodyStreamTap)
327
+
328
+ captured.restore_stream(req)
329
+ captured.body_for_log(req)
330
+ rescue StandardError => e
331
+ Coolhand.log "❌ Error capturing request body: #{e.message}"
332
+ nil
333
+ end
334
+
335
+ # Appends a streamed response chunk to the thread-local capture buffer, up to the cap.
336
+ # Past the cap the buffer is dropped and replaced by a running byte count (an Integer),
337
+ # so memory stays bounded; the host always still receives every chunk because the caller
338
+ # yields it regardless. Only #request (via response_body_for_log) reads this slot.
339
+ def buffer_stream_chunk(chunk)
340
+ buffer = Thread.current[:coolhand_stream_buffer]
341
+ total = (buffer.is_a?(Integer) ? buffer : buffer.to_s.bytesize) + chunk.bytesize
342
+
343
+ Thread.current[:coolhand_stream_buffer] =
344
+ if buffer.is_a?(Integer) || over_capture_limit?(total)
345
+ total
346
+ else
347
+ (buffer || +"") << chunk
348
+ end
349
+ rescue StandardError => e
350
+ # Runs inside the host's read_body loop: a capture failure must never reach the host.
351
+ Coolhand.log "❌ Error buffering streamed response chunk: #{e.message}"
352
+ end
353
+
354
+ # [status_code, response_body] for the log. Called after the real request has succeeded, so a
355
+ # failure here is logged and swallowed rather than re-raised into the host app.
356
+ def capture_response(response)
357
+ captured = Thread.current[:coolhand_stream_buffer] || response&.body
358
+ # captured is a String, or an Integer byte count when a streamed body overflowed the cap.
359
+ [response.respond_to?(:code) ? response.code.to_i : nil, response_body_for_log(captured, response)]
360
+ rescue StandardError => e
361
+ Coolhand.log "❌ Error capturing response: #{e.message}"
362
+ [nil, nil]
363
+ end
364
+
365
+ # Builds the logged response body from either an Integer (streamed body that overflowed
366
+ # the cap, see buffer_stream_chunk) or the body String/nil. An oversized String is
367
+ # replaced by a marker before the dup/JSON.parse so we don't copy or parse it.
368
+ def response_body_for_log(body, response)
369
+ size = body.is_a?(Integer) ? body : body.to_s.bytesize
370
+ return body_too_large_marker(response, size) if body.is_a?(Integer) || over_capture_limit?(size)
371
+
372
+ body = body.dup.force_encoding("UTF-8") if body.is_a?(String)
373
+ BaseInterceptor.parse_json(body)
374
+ end
375
+
195
376
  def binary_upload?(req)
196
377
  content_type = req.respond_to?(:content_type) ? req.content_type : nil
197
378
  content_type && !content_type.match?(/json/i)
198
379
  end
199
380
 
200
381
  def cap_and_parse(content, req)
201
- max_bytes = Coolhand.configuration.max_captured_body_bytes
202
- if max_bytes && content.bytesize > max_bytes
203
- return skipped_capture_marker(req, "body_too_large", size_bytes: content.bytesize, max_bytes: max_bytes)
204
- end
382
+ return body_too_large_marker(req, content.bytesize) if over_capture_limit?(content.bytesize)
205
383
 
206
384
  BaseInterceptor.parse_json(content)
207
385
  end
@@ -227,10 +405,11 @@ module Coolhand
227
405
  uri = safe_parse(url)
228
406
  return false unless uri&.host
229
407
 
230
- return false if excluded_by_pattern?(uri)
408
+ raw_path = uri.path.to_s
409
+ path = normalize_path(raw_path)
410
+ return false if excluded_by_pattern?(uri, raw_path, path)
231
411
 
232
412
  host = uri.host.downcase.chomp(".")
233
- path = uri.path.to_s
234
413
  addresses = Coolhand.configuration.intercept_addresses
235
414
  authorities = [host, "#{host}:#{uri.port}"]
236
415
  return true if addresses.any? { |a| authorities.any? { |authority| address_matches?(authority, path, a) } }
@@ -251,12 +430,13 @@ module Coolhand
251
430
  nil
252
431
  end
253
432
 
254
- def excluded_by_pattern?(uri)
433
+ # The deny-list fails closed: a pattern that matches either the raw or the normalized path
434
+ # excludes the request, so normalization can only add exclusions, never lift one.
435
+ def excluded_by_pattern?(uri, raw_path, path)
255
436
  patterns = Coolhand.configuration.exclude_api_patterns
256
437
  return false if patterns.nil? || patterns.empty?
257
438
 
258
- path = uri.path.to_s
259
- matched = patterns.find { |pattern| path.include?(pattern) }
439
+ matched = patterns.find { |pattern| path.include?(pattern) || raw_path.include?(pattern) }
260
440
  if matched && Coolhand.configuration.debug_mode
261
441
  Coolhand.log "🚫 Skipping capture for #{BaseInterceptor.sanitize_url(uri.to_s)} " \
262
442
  "(matched exclude_api_pattern: \"#{matched}\")"
@@ -264,6 +444,11 @@ module Coolhand
264
444
  !!matched
265
445
  end
266
446
 
447
+ # See PathNormalizer: used for matching only, never for the URL that is sent or logged.
448
+ def normalize_path(path)
449
+ PathNormalizer.normalize(path)
450
+ end
451
+
267
452
  # intercept_path_patterns only ever applies to googleapis.com hosts, and only when the
268
453
  # user still wants Google API traffic intercepted at all — otherwise overriding
269
454
  # intercept_addresses to exclude Google hosts wouldn't actually stop Google API capture.
@@ -5,6 +5,16 @@ require_relative "../../coolhand"
5
5
  module Coolhand
6
6
  module OpenAi
7
7
  class BatchResultProcessor
8
+ # Batch input/output files carry relative URLs (e.g. "/v1/chat/completions"); logs need the
9
+ # absolute form so backend URL-shape classification matches the rest of the gem's OpenAI traffic.
10
+ OPENAI_API_BASE_URL = "https://api.openai.com"
11
+ SOURCE_API = "openai"
12
+ # Real IDs look like "batch_<hex>" and "file-<alnum>" (Azure uses UUID tails with hyphens).
13
+ # These values end up in OpenAI API calls made with the host app's key, so keep "/", "?", "#",
14
+ # "." and whitespace out of them.
15
+ BATCH_ID_PATTERN = /\Abatch_[A-Za-z0-9_-]{1,128}\z/
16
+ FILE_ID_PATTERN = /\Afile[-_][A-Za-z0-9_-]{1,128}\z/
17
+
8
18
  attr_reader :event_data
9
19
 
10
20
  def initialize(event_data:)
@@ -13,6 +23,7 @@ module Coolhand
13
23
 
14
24
  def call
15
25
  Rails.logger.info("[Interceptor] BatchResultProcessor: #{event_data}")
26
+ return unless valid_id?(event_data.is_a?(Hash) ? event_data["id"] : nil, BATCH_ID_PATTERN, "batch")
16
27
 
17
28
  case batch_info["status"]
18
29
  when "completed"
@@ -41,84 +52,159 @@ module Coolhand
41
52
  end
42
53
 
43
54
  def process_completed_batch
44
- input_file_id = batch_info["input_file_id"]
45
- return unless input_file_id
46
-
47
- output_file_id = batch_info["output_file_id"]
48
- return unless output_file_id
49
-
50
- # Download and process results
51
- batch_request_items = download_batch_results(input_file_id)
55
+ input_file_id, output_file_id = result_file_ids
56
+ return unless input_file_id && output_file_id
52
57
 
53
- # Download and process results
54
- batch_response_items = download_batch_results(output_file_id)
58
+ window = batch_window
59
+ return unless window
55
60
 
56
- request_items_by_id = batch_request_items.each_with_object({}) do |item, index|
57
- index[item["custom_id"]] ||= item
61
+ request_items_by_id = {}
62
+ each_batch_result(input_file_id) do |item, line_size|
63
+ request_items_by_id[item["custom_id"]] ||= request_entry(item, line_size)
58
64
  end
59
65
 
60
- batch_response_items.each do |response_item|
66
+ each_batch_result(output_file_id) do |response_item, line_size|
61
67
  request_item = request_items_by_id[response_item["custom_id"]]
62
-
63
- next unless request_item
64
-
65
- send_complete_request_log(request_id: response_item["response"]["request_id"],
66
- method: request_item["method"],
67
- url: request_item["url"],
68
- request_body: request_item["body"],
69
- response_body: response_item["response"]["body"],
70
- status_code: response_item["response"]["status_code"],
71
- start_time: batch_info["in_progress_at"].to_i,
72
- end_time: batch_info["completed_at"].to_i)
73
- rescue StandardError => e
74
- Rails.logger.error("[Interceptor] Failed to send request log: #{e.message}")
68
+ send_item_log(request_item, response_item, window, line_size) if request_item
75
69
  end
76
70
 
77
71
  Rails.logger.info("[Interceptor] Successfully processed OpenAI batch #{batch_info['id']}")
78
72
  end
79
73
 
80
- def download_batch_results(file_id)
81
- file_content = client.files.content(id: file_id)
74
+ # Returns [input_file_id, output_file_id], or nil when either is absent (quietly: a completed
75
+ # batch where every item failed legitimately has no output file) or malformed (logged).
76
+ def result_file_ids
77
+ input_file_id = batch_info["input_file_id"]
78
+ output_file_id = batch_info["output_file_id"]
79
+ return unless input_file_id && output_file_id
80
+ return unless valid_id?(input_file_id, FILE_ID_PATTERN, "input file") &&
81
+ valid_id?(output_file_id, FILE_ID_PATTERN, "output file")
82
82
 
83
- # Handle both string and array responses from the OpenAI client
84
- if file_content.is_a?(Array)
85
- # Client already parsed the JSONL into an array
86
- file_content
87
- else
88
- # Parse JSONL response manually
89
- file_content.split("\n").filter_map do |line|
90
- line.strip!
91
- next if line.empty?
83
+ [input_file_id, output_file_id]
84
+ end
85
+
86
+ def send_item_log(request_item, response_item, window, line_size)
87
+ send_complete_request_log(request_item: request_item, response_item: response_item, window: window,
88
+ line_size: line_size)
89
+ rescue StandardError => e
90
+ Rails.logger.error("[Interceptor] Failed to send request log: #{e.message}")
91
+ end
92
+
93
+ # What is kept of each input item while the output file is read: only the fields that get
94
+ # logged, with the body capped (see BatchBodyCap) so the index stays small. The model is read
95
+ # from the full body first, since a capped body is just a marker.
96
+ def request_entry(item, line_size)
97
+ { "method" => item["method"], "url" => item["url"], "model" => item_model(item["body"]),
98
+ "body" => BatchBodyCap.cap(item["body"], source_size: line_size) }
99
+ end
100
+
101
+ # Returns [start_time, end_time] or nil (after logging) when OpenAI didn't report usable
102
+ # in_progress_at/completed_at epoch seconds — better to skip than log epoch-0 timestamps.
103
+ def batch_window
104
+ started = batch_info["in_progress_at"]
105
+ completed = batch_info["completed_at"]
106
+ unless [started, completed].all? { |t| t.is_a?(Integer) && t.positive? }
107
+ Rails.logger.error("[Interceptor] OpenAI batch #{batch_info['id']} has a missing or invalid " \
108
+ "in_progress_at/completed_at; skipping request log")
109
+ return
110
+ end
111
+
112
+ warn_inverted_window if completed < started
113
+ [Time.at(started), Time.at([started, completed].max)]
114
+ end
92
115
 
93
- JSON.parse(line)
94
- end
116
+ def warn_inverted_window
117
+ Rails.logger.warn("[Interceptor] OpenAI batch #{batch_info['id']} has a completed_at before its " \
118
+ "in_progress_at; clamping duration_ms to 0")
119
+ end
120
+
121
+ def valid_id?(value, pattern, label)
122
+ return true if value.is_a?(String) && value.match?(pattern)
123
+
124
+ Rails.logger.error("[Interceptor] OpenAI batch has a missing or invalid #{label} ID " \
125
+ "(#{value.to_s[0, 100].inspect}); skipping")
126
+ false
127
+ end
128
+
129
+ # Yields each item of a batch input/output file with the byte size of the JSONL line it came
130
+ # from (nil when the client had already parsed it). A String/StringIO/IO result is read a line
131
+ # at a time, so only one parsed item exists at once instead of the whole file split into lines.
132
+ # A client that returns the whole file already parsed (an Array, or a Hash for a one-line file)
133
+ # has loaded it already; that is out of reach here.
134
+ def each_batch_result(file_id, &block)
135
+ file_content = download_batch_file(file_id)
136
+
137
+ case file_content
138
+ when nil then nil
139
+ when Array then file_content.each { |item| yield(item, nil) if item.is_a?(Hash) }
140
+ when Hash then yield(file_content, nil)
141
+ else each_jsonl_item(file_content, &block)
95
142
  end
96
- rescue JSON::ParserError => e
97
- Rails.logger.error("[Interceptor] Failed to parse OpenAI batch results: #{e.message}")
98
- []
143
+ end
144
+
145
+ def download_batch_file(file_id)
146
+ client.files.content(id: file_id)
99
147
  rescue StandardError => e
100
148
  Rails.logger.error("[Interceptor] Failed to download OpenAI batch results: #{e.message}")
101
- []
149
+ nil
102
150
  end
103
151
 
104
- def send_complete_request_log(request_id:, method:, url:, request_body:, response_body:, status_code:,
105
- start_time:, end_time:)
152
+ # A malformed line is skipped (JSONL lines are independent) and reported once at the end.
153
+ def each_jsonl_item(file_content)
154
+ skipped = 0
155
+ file_content.each_line do |line|
156
+ size = line.bytesize
157
+ next unless line.b.match?(/\S/) # byte-wise: String#strip raises on invalid UTF-8
158
+
159
+ item = parse_jsonl_line(line)
160
+ item ? yield(item, size) : skipped += 1
161
+ end
162
+ return if skipped.zero?
163
+
164
+ Rails.logger.error("[Interceptor] Failed to parse OpenAI batch results: skipped #{skipped} malformed line(s)")
165
+ end
166
+
167
+ # Only a JSON object is an item; any other valid JSON (a number, an array) counts as malformed.
168
+ def parse_jsonl_line(line)
169
+ item = JSON.parse(line)
170
+ item if item.is_a?(Hash)
171
+ rescue JSON::ParserError, EncodingError
172
+ nil
173
+ end
174
+
175
+ def send_complete_request_log(request_item:, response_item:, window:, line_size:)
176
+ start_time, end_time = window
177
+ response = response_item["response"]
106
178
  BaseInterceptor.send_complete_request_log(
107
- request_id: request_id,
108
- method: method,
109
- url: url,
179
+ request_id: response["request_id"],
180
+ method: request_item["method"],
181
+ url: absolute_url(request_item["url"]),
182
+ source_api: SOURCE_API,
183
+ model: request_item["model"] || item_model(response["body"]),
110
184
  request_headers: {},
111
- request_body: request_body,
185
+ request_body: request_item["body"],
112
186
  response_headers: {},
113
- response_body: response_body,
114
- status_code: status_code,
115
- start_time: Time.at(start_time),
116
- end_time: Time.at(end_time),
187
+ response_body: BatchBodyCap.cap(response["body"], source_size: line_size),
188
+ status_code: response["status_code"],
189
+ start_time: start_time,
190
+ end_time: end_time,
117
191
  duration_ms: ((end_time - start_time) * 1000).to_i,
118
192
  is_streaming: false
119
193
  )
120
194
  end
121
195
 
196
+ def absolute_url(url)
197
+ url.is_a?(String) && url.start_with?("/") ? "#{OPENAI_API_BASE_URL}#{url}" : url
198
+ end
199
+
200
+ def item_model(*bodies)
201
+ bodies.each do |body|
202
+ model = body["model"] if body.is_a?(Hash)
203
+ return model if model.is_a?(String) && Coolhand.required_field?(model)
204
+ end
205
+ nil
206
+ end
207
+
122
208
  def batch_info
123
209
  @batch_info ||= client.batches.retrieve(id: event_data["id"])
124
210
  end
@@ -27,6 +27,13 @@ module Coolhand
27
27
  end
28
28
  end
29
29
 
30
+ # Forgets a claim so the same id can be claimed again (used when processing failed and the
31
+ # sender retries). A no-op for an unknown id.
32
+ def release!(id)
33
+ @mutex.synchronize { @entries.delete(id) }
34
+ nil
35
+ end
36
+
30
37
  def seen?(id)
31
38
  @mutex.synchronize do
32
39
  prune