logbrew-sdk 0.1.17 → 0.1.20

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 25c59f04169b6fce06afa15c04f790fd7b0d3d8643b50c880ca2d451e71168b2
4
- data.tar.gz: dec9fb58c8ba57ad3745227d5858a400947a41e62c2fea3ce66d9d9096495372
3
+ metadata.gz: a0f4d5c699a2ad04533c601925d0f7f58c4271f16f345ffbf7f65f68ea5fde8f
4
+ data.tar.gz: 2683b8e1ebdb4a2af2c3db7765ce6f54ff16a925833c5adb03a533618fac54be
5
5
  SHA512:
6
- metadata.gz: 251d55bf921e65cd161648547aa60a9ac6242aee7659b48ef674d87e42bda61d6dea4234b7e164f2a7d996dd9af92b32cc54315bde1b5edc37a765a68bc00b36
7
- data.tar.gz: 3a66a2414a69c0f85a80050f772137b85482d2212a926f5d78b6a67edab7f73394473c27b1a1ceffa54c0eea59be98d7c47048ca1a1c25739b60d9526b9e0ee1
6
+ metadata.gz: d5045b002e7ea063d305484d4a641c9ad40fe9d3f284339f8f3361b342b5bb940c50d6c3913776d2943f015e5c14aaa2f495aa8b65f656d0f204a825ea708f5e
7
+ data.tar.gz: 60563aa13772a2e8d75d3632ea0fa26204edd8c627bb03a656fa079cef58e569de24cb1dd6d866259e7fa26c053e54c43b9e0859b1fbaa0501ed36f633d986a4
data/README.md CHANGED
@@ -23,7 +23,7 @@ needed:
23
23
 
24
24
  ```ruby
25
25
  # Gemfile
26
- gem "logbrew-sdk", "~> 0.1.17"
26
+ gem "logbrew-sdk", "~> 0.1.18"
27
27
  ```
28
28
 
29
29
  ```bash
@@ -51,9 +51,20 @@ Escaped request failures include exception identity,
51
51
  `rails.middleware` with `handled: false`, and up to 32 newest-first sanitized
52
52
  frames. Handled Rails reports use `rails.error_reporter` with `handled: true`.
53
53
  It does not record concrete request paths, query strings, request or response
54
- bodies, arbitrary headers, authorization values, cookies, user IDs, exception
55
- messages, raw backtrace text, source snippets, locals, arguments, or absolute
56
- paths. Exception messages and raw backtrace text are separate opt-ins.
54
+ bodies, arbitrary headers, authorization values, cookies, exception messages,
55
+ raw backtrace text, source snippets, locals, arguments, or absolute paths.
56
+ Exception messages and raw backtrace text are separate opt-ins.
57
+
58
+ To see which user hit an error, call `LogBrew.set_user` with your app's opaque
59
+ user ID, for example in a `before_action`. Every issue, log, span, and metric
60
+ of that request then carries the user. Pass an ID, never an email address or a
61
+ name. Outside a request, the call does nothing and returns `false`:
62
+
63
+ ```ruby
64
+ class ApplicationController < ActionController::Base
65
+ before_action { LogBrew.set_user(current_user.id.to_s) if current_user }
66
+ end
67
+ ```
57
68
 
58
69
  ActiveJob needs no extra initializer. Each enqueue and execution emits a
59
70
  producer or worker span, including bounded adapter identity, retry count, and
@@ -79,6 +90,13 @@ gem, startup, and out-of-trace logs remain local. Messages are limited to 2,048
79
90
  characters and include `messageState: captured` or `messageState: truncated`.
80
91
  Log messages are application-provided telemetry and can contain sensitive
81
92
  values, so enable this only after the application applies its normal filtering.
93
+ Each captured message in a request also becomes a breadcrumb, so an issue shows
94
+ the last 64 log lines that led to it. Messages longer than 512 characters are
95
+ cut in the breadcrumb. Add your own breadcrumbs with `LogBrew.add_breadcrumb`.
96
+
97
+ Set `LOGBREW_CAPTURE_REQUEST_METRICS=true` to record an `http.server.duration`
98
+ histogram in milliseconds for each request. Its metadata holds only the method,
99
+ route template, status code, status class, service, environment, and release.
82
100
 
83
101
  The explicit Rails capture settings are:
84
102
 
@@ -95,6 +113,7 @@ The explicit Rails capture settings are:
95
113
  | `LOGBREW_FLUSH_THRESHOLD` | `100` | Queue size from 1 to 1000 that requests an earlier flush |
96
114
  | `LOGBREW_CAPTURE_EXCEPTION_MESSAGES` | `false` | Opt in to exception message capture |
97
115
  | `LOGBREW_CAPTURE_RAILS_LOGS` | `false` | Opt in to bounded application-origin logs on active request and job traces |
116
+ | `LOGBREW_CAPTURE_REQUEST_METRICS` | `false` | Opt in to one request duration metric per request |
98
117
  | `LOGBREW_INCLUDE_EXCEPTION_BACKTRACE` | `false` | Opt in to raw exception backtrace text; sanitized structured frames are always captured |
99
118
 
100
119
  `LOGBREW_API_KEY` and `LOGBREW_INGEST_KEY` are not Rails aliases. If either is
@@ -560,7 +579,7 @@ source code, locals, arguments, or absolute paths. The raw Rails/Rack backtrace
560
579
  option is separate and remains off by default. Run
561
580
  `make -C examples run-issue-diagnostics` for a complete inspectable payload.
562
581
  Rails, Rack, and Sidekiq issue capture reuse this same graph. See the shared
563
- [exception-chain contract](../../docs/exception-chain-evidence.md).
582
+ [exception-chain contract](../../README.md#exception-chains).
564
583
 
565
584
  ## Metrics
566
585
 
@@ -580,7 +599,7 @@ client.metric(
580
599
  )
581
600
  ```
582
601
 
583
- Supported metric kinds are `counter`, `gauge`, and `histogram`. Counters and histograms require `delta` or `cumulative` temporality and non-negative values; gauges require `instant` temporality and may be negative. An optional `description` gives people and investigation tools the stable meaning of the measurement. Keep it generic, single-line, between 1 and 1,024 Unicode scalar values, and free of identifiers, personal data, or changing values. It is not a query dimension. Keep metadata low-cardinality and primitive. This SDK does not automatically collect Ruby runtime, Rack, Rails, or database metrics yet.
602
+ Supported metric kinds are `counter`, `gauge`, and `histogram`. Counters and histograms require `delta` or `cumulative` temporality and non-negative values; gauges require `instant` temporality and may be negative. An optional `description` gives people and investigation tools the stable meaning of the measurement. Keep it generic, single-line, between 1 and 1,024 Unicode scalar values, and free of identifiers, personal data, or changing values. It is not a query dimension. Keep metadata low-cardinality and primitive. The Rails integration records request duration with `LOGBREW_CAPTURE_REQUEST_METRICS=true`. This SDK does not collect Ruby runtime, Rack, or database metrics automatically.
584
603
 
585
604
  ## Product And Network Timelines
586
605
 
@@ -621,7 +640,7 @@ The helpers return normal `action` attributes, so they work with the existing qu
621
640
 
622
641
  ## Support Ticket Draft Diagnostics
623
642
 
624
- Use `LogBrew::SupportTicketDraft.create` when a developer or support agent explicitly asks for a local JSON payload for the planned LogBrew support-ticket routes. The helper validates the public source/category contract, normalizes W3C trace IDs, redacts diagnostics, and returns a plain Ruby hash:
643
+ Use `LogBrew::SupportTicketDraft.create` to build the JSON body for a LogBrew support ticket. The helper validates the source and category, normalizes W3C trace IDs, redacts diagnostics, and returns a plain Ruby hash:
625
644
 
626
645
  ```ruby
627
646
  draft = LogBrew::SupportTicketDraft.create(
@@ -642,7 +661,7 @@ draft = LogBrew::SupportTicketDraft.create(
642
661
  puts JSON.generate(draft)
643
662
  ```
644
663
 
645
- This helper is local-only. It does not send data, open a ticket, call backend support-ticket routes, use account/session API credentials, or infer backend ownership. Diagnostics are bounded to JSON-like values; token-like keys and strings are redacted, HTTP URLs keep only the path, local filesystem paths are replaced, exceptions keep only the class name, and unsupported Ruby objects are omitted.
664
+ The helper sends nothing. To open the ticket, send it to `POST /api/support/tickets` or run `logbrew support create`. See [Report a problem](https://docs.logbrew.co/guides/report-a-problem). Diagnostics are bounded to JSON-like values; token-like keys and strings are redacted, HTTP URLs keep only the path, local filesystem paths are replaced, exceptions keep only the class name, and unsupported Ruby objects are omitted.
646
665
 
647
666
  ## HTTP Delivery
648
667
 
@@ -724,7 +743,9 @@ client.shutdown
724
743
 
725
744
  The worker starts only after accepted queue work exists, then wakes when the queue reaches `flush_threshold` or `flush_interval` expires. The defaults are 1 second and 100 events, so a single event is readable in about a second while bursts still share one request. Restart-hydrated persistent work wakes it immediately. Automatic and manual sends share the existing serialized flush, immutable failed prefix, accepted-prefix acknowledgement, batch bounds, and persistence format; no second queue or transport path is created.
726
745
 
727
- Retryable network, `408`, and `5xx` failures retain the exact failed body and use capped equal-jitter backoff. Authentication (`401`/`403`), quota (`429`), validation (`400`/`422`), and other non-retryable responses pause automatic sends without dropping queued work. `recover_automatic_delivery` performs one explicit synchronous flush through the owned transport and resumes scheduling only after success. Calling `flush(transport)` directly provides the same explicit recovery boundary. `stop_automatic_delivery` joins the worker without draining or discarding work; a later manual flush remains available.
746
+ Retryable network, `408`, and `5xx` failures retain the exact failed body and use capped equal-jitter backoff. Authentication (`401`/`403`), quota (`429`, described below), validation (`400`/`422`), and other non-retryable responses pause automatic sends without dropping queued work. A paused delivery resends the same batch on its own as a probe: the first probe waits up to `retry_max_delay`, each failed probe doubles the wait up to 5 minutes (or `retry_max_delay` when it is longer), and the first accepted probe resumes normal delivery. During the pause `delivery_health` reports the `paused` state, the reason, and the probe delay in `retry_delay_ms`. A persistent queue failure does not probe and waits for explicit recovery. `recover_automatic_delivery` performs one explicit synchronous flush through the owned transport at once and resumes scheduling only after success. Calling `flush(transport)` directly provides the same explicit recovery boundary. `stop_automatic_delivery` joins the worker without draining or discarding work; a later manual flush remains available.
747
+
748
+ A `429` response with `code: "usage_limit_exceeded"` in its JSON body pauses with the `quota` reason, even when it includes `Retry-After`. Any other `429` with a readable `Retry-After` value (delta-seconds or an HTTP date; a past date counts as zero) or with `code: "rate_limited"` starts a timed wait instead: the client waits for the `Retry-After` delay, or its usual retry backoff when the header is missing, kept between 1 second and 1 hour plus up to 10 percent of random jitter, and capped at 1 hour. The failed batch stays first in the queue and is sent again unchanged when the wait ends, without any application call, while new events keep queueing within the usual limits. During the wait `delivery_health` reports the `retrying` state with `retry_delay_ms`, not a pause. A `429` with neither pauses as before. `HttpTransport` reads at most 4 KiB of a `429` body only to find `code` and never keeps or reports it. A custom transport can request the same handling by returning `LogBrew::TransportResponse.new(429, 1, retry_after: seconds, code: code)`. `flush` still raises `transport_error` for any `429`.
728
749
 
729
750
  `delivery_health` returns an immutable, JSON-serializable `LogBrew::DeliveryHealth` snapshot. Its fixed fields are lifecycle state, queued event/byte counts, dropped count, in-flight state, bounded outcome/failure/flush counters, pause reason, and current retry delay. It never contains event data, event IDs, API keys, endpoints, headers, response bodies, filesystem paths, process or thread IDs, exception messages, or server text.
730
751
 
@@ -879,6 +900,12 @@ is omitted unless `include_exception_backtrace: true` is set; sanitized
879
900
  structured frames remain available either way. Events queue by default; pass
880
901
  `transport:` plus `flush_on_response: true` when each response should flush.
881
902
 
903
+ Inside a request, `LogBrew.set_user("user_123")` adds the user to every event
904
+ of that request. `LogBrew.add_breadcrumb(category: "checkout", level: "info",
905
+ message: "Cart loaded")` adds a breadcrumb to the request's next issue. An issue
906
+ keeps the newest 64 breadcrumbs. Breadcrumbs you pass to `client.issue` replace
907
+ them.
908
+
882
909
  ## Rails Error Subscriber
883
910
 
884
911
  The automatic Rails integration already subscribes to handled Rails errors.
@@ -925,10 +952,11 @@ unhandled request exceptions are not captured twice.
925
952
  - Queues default to 1,000 events and 4 MiB of compact serialized event data; `pending_event_bytes`, `dropped_events`, and `on_event_dropped` expose pressure locally. `TransportResponse#attempts` and `#batches` expose request work.
926
953
  - `metric(...)` queues explicit, application-owned metric events with name, kind, value, unit, temporality, and low-cardinality metadata validation.
927
954
  - `LogBrew::ProductTimeline` builds explicit, application-owned product action and network milestone timeline events with primitive metadata and query/hash-free routes.
928
- - `LogBrew::SupportTicketDraft.create` builds explicit, local-only support-ticket create payload drafts with redacted diagnostics and no backend route calls.
955
+ - `LogBrew::SupportTicketDraft.create` builds a redacted support-ticket body and sends nothing.
929
956
  - `LogBrew::IssueDiagnostics` builds typed exception identity, mechanism/handled state, basename-only structured frames, and bounded ordered breadcrumbs without raw exception internals.
930
957
  - `LogBrew::HttpTransport` sends queued batches through Ruby's standard `Net::HTTP` with configurable endpoint, headers, timeout, and app-owned HTTP client support.
931
958
  - `LogBrew::RackMiddleware` captures Rack request spans and unhandled app exceptions without requiring Rails or Rack at runtime.
959
+ - `LogBrew.set_user` and `LogBrew.add_breadcrumb` add the user and breadcrumbs to the events of the current request.
932
960
  - `LogBrew::RailsErrorSubscriber` captures handled/manual Rails error reports without requiring Rails at runtime.
933
961
  - `LogBrew::Rails` automatically installs privacy-bounded Rails request spans, handled-error issues, per-process delivery, health access, and idempotent shutdown when the canonical server key is configured.
934
962
  - `shutdown(transport)` flushes queued events and rejects later writes.
@@ -26,6 +26,10 @@ module LogBrew
26
26
  STATES = %w[idle running retrying paused stopped closing closed].freeze
27
27
  OUTCOMES = %w[none empty accepted retryable_failure terminal_failure stopped].freeze
28
28
  PAUSE_REASONS = %w[authentication quota validation nonretryable].freeze
29
+ RATE_LIMIT_MIN_WAIT = 1.0
30
+ RATE_LIMIT_MAX_WAIT = 3600.0
31
+ PAUSE_PROBE_MAX_WAIT = 300.0
32
+ STORAGE_ERROR_CODES = %w[persistent_queue_error persistence_commit_error].freeze
29
33
 
30
34
  attr_reader :transport
31
35
 
@@ -66,6 +70,14 @@ module LogBrew
66
70
  end
67
71
  private_class_method :validate_positive_integer
68
72
 
73
+ # Doubles from retry_max_delay with each consecutive failure up to 5 minutes, or up to
74
+ # retry_max_delay when it is longer, then keeps half to all of that ceiling as jitter.
75
+ def self.pause_probe_delay(retry_max_delay, failures, jitter = Random.rand)
76
+ maximum = [retry_max_delay, PAUSE_PROBE_MAX_WAIT].max
77
+ ceiling = [retry_max_delay * (2.0**[failures - 1, 0].max), maximum].min
78
+ (ceiling / 2.0) + (ceiling / 2.0 * jitter)
79
+ end
80
+
69
81
  def initialize(
70
82
  client:,
71
83
  transport:,
@@ -132,8 +144,10 @@ module LogBrew
132
144
  if @observed_queue_count.zero?
133
145
  @wake_requested = false
134
146
  @next_interval_deadline = nil
135
- @retry_deadline = nil
136
- @retry_delay = nil
147
+ unless @state == "paused"
148
+ @retry_deadline = nil
149
+ @retry_delay = nil
150
+ end
137
151
  end
138
152
  @condition.signal
139
153
  end
@@ -184,8 +198,7 @@ module LogBrew
184
198
  @pause_reason = previous.fetch(1)
185
199
  @wake_requested = false
186
200
  @next_interval_deadline = nil
187
- @retry_delay = nil
188
- @retry_deadline = nil
201
+ schedule_pause_probe(error)
189
202
  elsif previous.fetch(0) == "stopped"
190
203
  @state = "stopped"
191
204
  @wake_requested = false
@@ -263,7 +276,7 @@ module LogBrew
263
276
  @state = "retrying"
264
277
  @last_outcome = "retryable_failure"
265
278
  @pause_reason = nil
266
- @retry_delay = bounded_retry_delay
279
+ @retry_delay = failure_retry_delay(error)
267
280
  @retry_deadline = monotonic_time + @retry_delay
268
281
  ensure_worker if @observed_queue_count.positive?
269
282
  @condition.signal
@@ -373,12 +386,12 @@ module LogBrew
373
386
  now = monotonic_time
374
387
  retry_ready = !@retry_deadline.nil? && now >= @retry_deadline
375
388
  interval_ready = !@next_interval_deadline.nil? && now >= @next_interval_deadline
376
- if @state != "paused" && (@wake_requested || retry_ready || interval_ready)
389
+ if retry_ready || (@state != "paused" && (@wake_requested || interval_ready))
377
390
  @wake_requested = false
378
391
  @retry_deadline = nil
379
392
  @retry_delay = nil if retry_ready
380
393
  @next_interval_deadline = nil
381
- @state = retry_ready ? "retrying" : "running"
394
+ @state = retry_ready ? "retrying" : "running" unless @state == "paused"
382
395
  @in_flight = true
383
396
  return @generation
384
397
  end
@@ -406,18 +419,26 @@ module LogBrew
406
419
  @next_interval_deadline = nil
407
420
  if retryable_failure?(error)
408
421
  @pause_reason = nil
409
- @retry_delay = bounded_retry_delay
422
+ @retry_delay = failure_retry_delay(error)
410
423
  @retry_deadline = monotonic_time + @retry_delay
411
424
  @state = "retrying"
412
425
  @condition.signal
413
426
  else
414
427
  @pause_reason = pause_reason(error)
415
- @retry_delay = nil
416
- @retry_deadline = nil
417
428
  @state = "paused"
429
+ schedule_pause_probe(error)
418
430
  end
419
431
  end
420
432
 
433
+ # A paused delivery resends its batch on its own; a storage failure waits for explicit recovery,
434
+ # because another send could lose or repeat persisted events.
435
+ def schedule_pause_probe(error)
436
+ storage = error.is_a?(SdkError) && STORAGE_ERROR_CODES.include?(error.code)
437
+ @retry_delay = storage ? nil : self.class.pause_probe_delay(@retry_max_delay, @consecutive_failures)
438
+ @retry_deadline = @retry_delay.nil? ? nil : monotonic_time + @retry_delay
439
+ @condition.signal
440
+ end
441
+
421
442
  def schedule_pending_work
422
443
  if @observed_queue_count.zero?
423
444
  @wake_requested = false
@@ -455,6 +476,15 @@ module LogBrew
455
476
  "nonretryable"
456
477
  end
457
478
 
479
+ # A rate limit waits for Retry-After, or the usual backoff, kept within 1 s and 1 h plus up to 10% jitter.
480
+ def failure_retry_delay(error)
481
+ wait = error.respond_to?(:automatic_rate_limit) ? error.automatic_rate_limit : nil
482
+ return bounded_retry_delay if wait.nil?
483
+
484
+ delay = (wait.is_a?(Numeric) ? wait.to_f : bounded_retry_delay).clamp(RATE_LIMIT_MIN_WAIT, RATE_LIMIT_MAX_WAIT)
485
+ [delay + (Random.rand * delay * 0.1), RATE_LIMIT_MAX_WAIT].min
486
+ end
487
+
458
488
  def bounded_retry_delay
459
489
  exponent = [[@consecutive_failures - 1, 0].max, 30].min
460
490
  cap = [@retry_base_delay * (2**exponent), @retry_max_delay].min
@@ -244,7 +244,9 @@ module LogBrew
244
244
  end
245
245
 
246
246
  def normalize_host(host)
247
- value = host.to_s.strip.downcase.sub(/\.+\z/, "")
247
+ value = host.to_s.strip.downcase
248
+ last_label_end = value.rindex(/[^.]/)
249
+ value = last_label_end.nil? ? "" : value[0..last_label_end]
248
250
  return nil if value.empty? || value.bytesize > 253
249
251
  return nil if value.match?(/\A[0-9.]+\z/)
250
252
  return nil unless value.match?(/\A[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\z/)
@@ -24,6 +24,7 @@ module LogBrew
24
24
  MAX_BREADCRUMB_DATA_FIELDS = 8
25
25
  MAX_BREADCRUMB_DATA_STRING = 256
26
26
  MAX_COORDINATE = 2_147_483_647
27
+ MAX_BACKTRACE_LINE = MAX_FRAME_FILENAME + MAX_FRAME_FUNCTION + 64
27
28
 
28
29
  MACHINE_NAME = /\A[A-Za-z][A-Za-z0-9_.:-]{0,63}\z/.freeze
29
30
  DATA_KEY = /\A[A-Za-z][A-Za-z0-9_.-]{0,63}\z/.freeze
@@ -611,7 +612,7 @@ module LogBrew
611
612
  end
612
613
 
613
614
  def frame_from_backtrace_line(line)
614
- return nil unless line.is_a?(String) && line.valid_encoding?
615
+ return nil unless line.is_a?(String) && line.valid_encoding? && line.length <= MAX_BACKTRACE_LINE
615
616
 
616
617
  match = line.match(/\A(.+):(\d+)(?::in [`'](.+?)[`'])?\z/)
617
618
  return nil unless match
@@ -21,7 +21,7 @@ module LogBrew
21
21
  ATTRIBUTES = %i[
22
22
  enabled api_key service_name app_environment rails_version release endpoint
23
23
  request_timeout flush_interval flush_threshold capture_exception_messages
24
- capture_rails_logs include_exception_backtrace
24
+ capture_rails_logs capture_request_metrics include_exception_backtrace
25
25
  ].freeze
26
26
  private_constant :ATTRIBUTES
27
27
  attr_reader(*ATTRIBUTES.drop(1).reject { |name| name.to_s.start_with?("capture_", "include_") })
@@ -89,6 +89,7 @@ module LogBrew
89
89
  false
90
90
  ),
91
91
  capture_rails_logs: boolean_value(environment, "LOGBREW_CAPTURE_RAILS_LOGS", false),
92
+ capture_request_metrics: boolean_value(environment, "LOGBREW_CAPTURE_REQUEST_METRICS", false),
92
93
  include_exception_backtrace: boolean_value(
93
94
  environment,
94
95
  "LOGBREW_INCLUDE_EXCEPTION_BACKTRACE",
@@ -111,6 +112,7 @@ module LogBrew
111
112
  flush_threshold: DEFAULT_FLUSH_THRESHOLD,
112
113
  capture_exception_messages: false,
113
114
  capture_rails_logs: false,
115
+ capture_request_metrics: false,
114
116
  include_exception_backtrace: false
115
117
  )
116
118
  end
@@ -221,6 +223,10 @@ module LogBrew
221
223
  @capture_rails_logs
222
224
  end
223
225
 
226
+ def capture_request_metrics?
227
+ @capture_request_metrics
228
+ end
229
+
224
230
  def include_exception_backtrace?
225
231
  @include_exception_backtrace
226
232
  end
@@ -382,6 +388,7 @@ module LogBrew
382
388
  # Adds one bounded, trace-aware LogBrew sink without replacing the app logger.
383
389
  module ApplicationLogCapture
384
390
  MAX_MESSAGE_CHARACTERS = 2_048
391
+ MAX_BREADCRUMB_CHARACTERS = 512
385
392
  SINK_IVAR = :@logbrew_rails_log_sink
386
393
  ROOT_IVAR = :@logbrew_rails_application_root
387
394
  GUARD_KEY = :logbrew_rails_log_capture
@@ -391,7 +398,7 @@ module LogBrew
391
398
  LOGGER_WRAPPER_PATH = %r{/active_support/(?:broadcast_logger|tagged_logging|logger(?:_silence|_thread_safe_level)?)\.rb\z}
392
399
  GEM_ROOTS = (defined?(::Gem) ? ::Gem.path : []).map { |root| "#{File.expand_path(root)}#{File::SEPARATOR}" }.freeze
393
400
  LEVELS = LogBrew::Logger::SEVERITY_TO_LOGBREW_LEVEL
394
- private_constant :MAX_MESSAGE_CHARACTERS, :SINK_IVAR, :ROOT_IVAR, :GUARD_KEY, :ORIGIN_KEY,
401
+ private_constant :MAX_MESSAGE_CHARACTERS, :MAX_BREADCRUMB_CHARACTERS, :SINK_IVAR, :ROOT_IVAR, :GUARD_KEY, :ORIGIN_KEY,
395
402
  :LIBRARY_ROOT, :LOGGER_PATH, :LOGGER_WRAPPER_PATH, :GEM_ROOTS, :LEVELS
396
403
 
397
404
  class Sink < ::Logger
@@ -486,14 +493,22 @@ module LogBrew
486
493
  "rubySeverity" => ::Logger::SEV_LABEL[severity.to_i] || "ANY",
487
494
  "messageState" => truncated ? "truncated" : "captured"
488
495
  )
496
+ level = LEVELS.fetch(severity.to_i, severity.to_i >= ::Logger::FATAL ? "critical" : "info")
489
497
  client.log(
490
498
  "ruby_rails_log_#{SecureRandom.hex(8)}",
491
499
  Time.now.utc.iso8601(6),
492
500
  message: text[0, MAX_MESSAGE_CHARACTERS],
493
- level: LEVELS.fetch(severity.to_i, severity.to_i >= ::Logger::FATAL ? "critical" : "info"),
501
+ level: level,
494
502
  logger: "rails",
495
503
  metadata: metadata
496
504
  )
505
+ LogBrew.add_breadcrumb(
506
+ category: "logging",
507
+ type: "debug",
508
+ level: level,
509
+ message: text.gsub(/[[:cntrl:]]/, " ")[0, MAX_BREADCRUMB_CHARACTERS],
510
+ data: { "logger" => "rails" }
511
+ )
497
512
  rescue StandardError => error
498
513
  runtime.report_error("application_log_capture", error)
499
514
  ensure
@@ -574,7 +589,7 @@ module LogBrew
574
589
  result = Trace.with_context(@context) { yield }
575
590
  finish
576
591
  result
577
- rescue Exception => error # rubocop:disable Lint/RescueException
592
+ rescue Exception => error
578
593
  finish(error)
579
594
  raise
580
595
  end
@@ -691,7 +706,7 @@ module LogBrew
691
706
  @logbrew_perform_operation = operation
692
707
  begin
693
708
  Trace.with_context(operation.context) { super }
694
- rescue Exception => error # rubocop:disable Lint/RescueException
709
+ rescue Exception => error
695
710
  operation.finish(error)
696
711
  operation.capture_terminal_issue(error)
697
712
  raise
@@ -772,19 +787,44 @@ module LogBrew
772
787
  # Internal Rack adapter that replaces concrete request paths with Rails
773
788
  # route templates while reusing the core request/error lifecycle.
774
789
  class RailsRackMiddleware < LogBrew::RackMiddleware
790
+ def initialize(app, capture_request_metrics: false, **options)
791
+ super(app, **options)
792
+ @capture_request_metrics = capture_request_metrics
793
+ end
794
+
775
795
  private
776
796
 
777
- def capture_request_span(*arguments)
797
+ def capture_request_span(env, status_code, elapsed_ms, status, timestamp)
778
798
  super.tap do
779
- RequestOperations.snapshot[1].sort_by(&:last).each do |duration_ms, kind, name, metadata, error, timestamp|
799
+ RequestOperations.snapshot[1].sort_by(&:last).each do |duration_ms, kind, name, metadata, error, operation_timestamp|
780
800
  LogBrew::OperationTracing.capture_span(
781
801
  @client, kind, name, LogBrew::OperationTracing.child_context, nil,
782
- { duration_ms: duration_ms, timestamp: timestamp, source: "rails.active_support", system: kind == "database" ? "active_record" : "rails", operation: name, metadata: metadata, on_error: @on_error }, error
802
+ { duration_ms: duration_ms, timestamp: operation_timestamp, source: "rails.active_support", system: kind == "database" ? "active_record" : "rails", operation: name, metadata: metadata, on_error: @on_error }, error
783
803
  )
784
804
  end
805
+ capture_request_metric(env, status_code, elapsed_ms) if @capture_request_metrics
785
806
  end
786
807
  end
787
808
 
809
+ def capture_request_metric(env, status_code, elapsed_ms)
810
+ @client.metric(
811
+ next_event_id("metric"),
812
+ logbrew_timestamp(6),
813
+ name: "http.server.duration",
814
+ description: "Duration of one completed server request.",
815
+ kind: "histogram",
816
+ value: elapsed_ms,
817
+ unit: "ms",
818
+ temporality: "delta",
819
+ metadata: @metadata.merge(
820
+ "method" => request_method(env),
821
+ "routeTemplate" => route_template(env),
822
+ "statusCode" => status_code,
823
+ "statusCodeClass" => "#{status_code.to_i / 100}xx"
824
+ )
825
+ )
826
+ end
827
+
788
828
  def exception_mechanism_type
789
829
  "rails.middleware"
790
830
  end
@@ -918,6 +958,7 @@ module LogBrew
918
958
  metadata: @runtime.metadata,
919
959
  include_exception_message: @runtime.configuration.capture_exception_messages?,
920
960
  include_exception_backtrace: @runtime.configuration.include_exception_backtrace?,
961
+ capture_request_metrics: @runtime.configuration.capture_request_metrics?,
921
962
  on_error: ->(error) { @runtime.report_error("request_capture", error) }
922
963
  )
923
964
  @adapter_client = active_client
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LogBrew
4
+ # The user and breadcrumbs of one request. LogBrew::RackMiddleware opens a
5
+ # fresh scope for each request, so one request's state never reaches another.
6
+ module RequestScope
7
+ KEY = :logbrew_request_scope
8
+ State = Struct.new(:subject, :breadcrumbs, :truncated)
9
+ private_constant :KEY, :State
10
+
11
+ module_function
12
+
13
+ def open
14
+ previous = Thread.current[KEY]
15
+ Thread.current[KEY] = State.new(nil, [], false)
16
+ yield
17
+ ensure
18
+ Thread.current[KEY] = previous
19
+ end
20
+
21
+ def set_user(id, kind)
22
+ subject = TelemetryContext.create.with_subject(id: id, kind: kind).build
23
+ state = Thread.current[KEY]
24
+ return false if state.nil?
25
+
26
+ state.subject = subject
27
+ true
28
+ end
29
+
30
+ def add_breadcrumb(**breadcrumb)
31
+ state = Thread.current[KEY]
32
+ return false if state.nil?
33
+
34
+ state.breadcrumbs << IssueDiagnostics.breadcrumb(timestamp: Time.now.utc.iso8601(3), **breadcrumb)
35
+ if state.breadcrumbs.length > IssueDiagnostics::MAX_BREADCRUMBS
36
+ state.breadcrumbs.shift
37
+ state.truncated = true
38
+ end
39
+ true
40
+ rescue SdkError
41
+ false
42
+ end
43
+
44
+ def subject_context
45
+ Thread.current[KEY]&.subject
46
+ end
47
+
48
+ def with_breadcrumbs(issue)
49
+ state = Thread.current[KEY]
50
+ return issue if state.nil? || state.breadcrumbs.empty? || issue.key?("breadcrumbs")
51
+
52
+ issue["breadcrumbs"] = state.breadcrumbs.map(&:dup)
53
+ issue["breadcrumbsTruncated"] = true if state.truncated
54
+ issue
55
+ end
56
+ end
57
+
58
+ # Attach an opaque, app-owned user ID to every event of the current request.
59
+ # Pass an ID, never an email address or a name. Outside a request the call
60
+ # does nothing and returns false. An invalid ID raises SdkError.
61
+ def self.set_user(id, kind: "user")
62
+ RequestScope.set_user(id, kind)
63
+ end
64
+
65
+ # Record one breadcrumb for the issue of the current request. Outside a
66
+ # request, or for an invalid breadcrumb, the call does nothing and returns false.
67
+ def self.add_breadcrumb(category:, type: nil, level: nil, message: nil, data: nil)
68
+ RequestScope.add_breadcrumb(category: category, type: type, level: level, message: message, data: data)
69
+ end
70
+ end
@@ -31,7 +31,7 @@ module LogBrew
31
31
  result = yield
32
32
  finish
33
33
  result
34
- rescue Exception => error # rubocop:disable Lint/RescueException
34
+ rescue Exception => error
35
35
  finish(error: error, terminal_failure: terminal_failure)
36
36
  raise
37
37
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module LogBrew
4
- VERSION = "0.1.17"
4
+ VERSION = "0.1.20"
5
5
  end
@@ -75,7 +75,7 @@ module LogBrew
75
75
  result = nil
76
76
  begin
77
77
  result = yield
78
- rescue Exception => error # rubocop:disable Lint/RescueException
78
+ rescue Exception => error
79
79
  application_error = error
80
80
  ensure
81
81
  finish_work_boundary(application_error)
data/lib/logbrew.rb CHANGED
@@ -80,6 +80,7 @@ module LogBrew
80
80
  require_relative "logbrew/telemetry_resource"
81
81
  require_relative "logbrew/telemetry_context"
82
82
  require_relative "logbrew/telemetry"
83
+ require_relative "logbrew/request_scope"
83
84
 
84
85
  require_relative "logbrew/event_batcher"
85
86
  require_relative "logbrew/persistent_event_store"
@@ -100,21 +101,31 @@ module LogBrew
100
101
  end
101
102
 
102
103
  class TransportResponse
103
- attr_reader :status_code, :attempts, :batches
104
+ attr_reader :status_code, :attempts, :batches, :retry_after, :code
104
105
 
105
- def initialize(status_code, attempts, batches = 1)
106
+ # For a 429, +retry_after+ is the Retry-After delay in seconds and +code+ is the
107
+ # JSON body's code string; either may be nil.
108
+ def initialize(status_code, attempts, batches = 1, retry_after: nil, code: nil)
106
109
  @status_code = status_code
107
110
  @attempts = attempts
108
111
  @batches = batches
112
+ @retry_after = retry_after
113
+ @code = code
114
+ end
115
+
116
+ # A 429 waits on its own when it has Retry-After or code "rate_limited", unless the usage limit was hit.
117
+ def timed_rate_limit?
118
+ status_code == 429 && code != "usage_limit_exceeded" && (!retry_after.nil? || code == "rate_limited")
109
119
  end
110
120
  end
111
121
 
112
122
  class DeliveryFailure < SdkError
113
- attr_reader :automatic_pause_reason
123
+ attr_reader :automatic_pause_reason, :automatic_rate_limit
114
124
 
115
- def initialize(code, message, automatic_retryable: false, automatic_pause_reason: nil)
125
+ def initialize(code, message, automatic_retryable: false, automatic_pause_reason: nil, automatic_rate_limit: nil)
116
126
  @automatic_retryable = automatic_retryable
117
127
  @automatic_pause_reason = automatic_pause_reason
128
+ @automatic_rate_limit = automatic_rate_limit
118
129
  super(code, message)
119
130
  end
120
131
 
@@ -148,7 +159,9 @@ module LogBrew
148
159
  raise response if response.is_a?(TransportError)
149
160
  raise response if response.is_a?(SdkError)
150
161
 
151
- status_code = response.is_a?(TransportResponse) ? response.status_code : response.to_i
162
+ return TransportResponse.new(response.status_code, 1, retry_after: response.retry_after, code: response.code) if response.is_a?(TransportResponse)
163
+
164
+ status_code = response.to_i
152
165
  TransportResponse.new(status_code.zero? ? 202 : status_code, 1)
153
166
  end
154
167
  end
@@ -156,6 +169,8 @@ module LogBrew
156
169
  class HttpTransport
157
170
  DEFAULT_ENDPOINT = "https://api.logbrew.co/v1/events"
158
171
  DEFAULT_TIMEOUT = 10
172
+ MAX_ERROR_BODY_BYTES = 4096
173
+ MAX_RATE_LIMIT_WAIT = 3600
159
174
 
160
175
  attr_reader :endpoint, :headers, :timeout, :http_client
161
176
 
@@ -176,18 +191,49 @@ module LogBrew
176
191
  @headers.each { |name, value| request[name] = value }
177
192
  request.body = body
178
193
 
179
- response = HttpClientTracing.suppress do
180
- @http_client ? @http_client.request(request) : request_with_default_client(request)
194
+ response, error_body = HttpClientTracing.suppress do
195
+ @http_client ? [@http_client.request(request), nil] : request_with_default_client(request)
181
196
  end
182
- TransportResponse.new(response.code.to_i, 1)
197
+ status_code = response.code.to_i
198
+ return TransportResponse.new(status_code, 1) unless status_code == 429
199
+
200
+ TransportResponse.new(
201
+ status_code,
202
+ 1,
203
+ retry_after: self.class.parse_retry_after(response.get_fields("retry-after")),
204
+ code: error_code(error_body || response.body)
205
+ )
183
206
  rescue TransportError
184
207
  raise
185
208
  rescue IOError, SystemCallError, SocketError, Timeout::Error, EOFError, Net::OpenTimeout, Net::ReadTimeout => error
186
209
  raise TransportError.network("http transport failed: #{error.message}")
187
210
  end
188
211
 
212
+ # Reads one Retry-After value as seconds: delta-seconds or an HTTP date, where a past date is 0.
213
+ # Missing, empty, repeated, or unreadable values return nil.
214
+ def self.parse_retry_after(values, now = Time.now)
215
+ return nil unless values.is_a?(Array) && values.length == 1
216
+
217
+ value = values.first.to_s.strip
218
+ return [value.to_i, MAX_RATE_LIMIT_WAIT].min if value.match?(/\A\d+\z/)
219
+
220
+ (Time.httpdate(value) - now).clamp(0, MAX_RATE_LIMIT_WAIT)
221
+ rescue ArgumentError
222
+ nil
223
+ end
224
+
189
225
  private
190
226
 
227
+ # Finds the JSON code of a 429 body of at most 4 KiB; the body is never kept.
228
+ def error_code(body)
229
+ return nil if body.nil? || body.bytesize > MAX_ERROR_BODY_BYTES
230
+
231
+ parsed = JSON.parse(body)
232
+ parsed.is_a?(Hash) && parsed["code"].is_a?(String) ? parsed["code"] : nil
233
+ rescue JSON::ParserError
234
+ nil
235
+ end
236
+
191
237
  def request_path
192
238
  path = @endpoint.path.empty? ? "/" : @endpoint.path
193
239
  return path if @endpoint.query.nil? || @endpoint.query.empty?
@@ -201,7 +247,26 @@ module LogBrew
201
247
  http.open_timeout = @timeout
202
248
  http.read_timeout = @timeout
203
249
  http.write_timeout = @timeout if http.respond_to?(:write_timeout=)
204
- http.start { |client| client.request(request) }
250
+ http.start do |client|
251
+ catch(:logbrew_rate_limited) do
252
+ response = client.request(request) do |received|
253
+ throw :logbrew_rate_limited, [received, bounded_body(received)] if received.code == "429"
254
+ end
255
+ [response, nil]
256
+ end
257
+ end
258
+ end
259
+
260
+ # Leaves the request after at most 4 KiB plus one byte, so a larger 429 body is never read.
261
+ def bounded_body(response)
262
+ body = +""
263
+ catch(:logbrew_body_limit) do
264
+ response.read_body do |chunk|
265
+ body << chunk
266
+ throw :logbrew_body_limit if body.bytesize > MAX_ERROR_BODY_BYTES
267
+ end
268
+ end
269
+ body
205
270
  end
206
271
 
207
272
  def validate_endpoint(endpoint)
@@ -414,16 +479,18 @@ module LogBrew
414
479
  end
415
480
 
416
481
  def call(env)
417
- started_at = monotonic_time
418
- started_timestamp, timestamp_error = request_timestamp
419
- response = begin
420
- @app.call(env)
421
- rescue StandardError => error
422
- capture_request(env, exception_status_code(error), started_at, started_timestamp, timestamp_error, error)
423
- raise
482
+ RequestScope.open do
483
+ started_at = monotonic_time
484
+ started_timestamp, timestamp_error = request_timestamp
485
+ response = begin
486
+ @app.call(env)
487
+ rescue StandardError => error
488
+ capture_request(env, exception_status_code(error), started_at, started_timestamp, timestamp_error, error)
489
+ raise
490
+ end
491
+ capture_request(env, rack_status(response), started_at, started_timestamp, timestamp_error)
492
+ response
424
493
  end
425
- capture_request(env, rack_status(response), started_at, started_timestamp, timestamp_error)
426
- response
427
494
  end
428
495
 
429
496
  private
@@ -837,10 +904,13 @@ module LogBrew
837
904
  DEFAULT_AUTOMATIC_RETRY_BASE_DELAY = 0.25
838
905
  DEFAULT_AUTOMATIC_RETRY_MAX_DELAY = 30.0
839
906
 
907
+ SERVER_API_KEY_VARIABLE = "LOGBREW_SERVER_API_KEY"
908
+
909
+ # A nil or blank api_key reads LOGBREW_SERVER_API_KEY.
840
910
  def self.create(
841
- api_key:,
842
911
  sdk_name:,
843
912
  sdk_version:,
913
+ api_key: nil,
844
914
  max_retries: 2,
845
915
  max_queue_size: BoundedEventQueue::DEFAULT_MAX_SIZE,
846
916
  max_queue_bytes: BoundedEventQueue::DEFAULT_MAX_BYTES,
@@ -851,7 +921,7 @@ module LogBrew
851
921
  context: nil,
852
922
  capture_runtime_context: true
853
923
  )
854
- Validation.require_non_empty("api_key", api_key)
924
+ api_key = resolve_server_api_key(api_key)
855
925
  Validation.require_non_empty("sdk_name", sdk_name)
856
926
  Validation.require_non_empty("sdk_version", sdk_version)
857
927
  raise SdkError.new("validation_error", "max_retries must be non-negative") if max_retries.negative?
@@ -887,10 +957,10 @@ module LogBrew
887
957
  end
888
958
 
889
959
  def self.create_automatic(
890
- api_key:,
891
960
  sdk_name:,
892
961
  sdk_version:,
893
962
  transport:,
963
+ api_key: nil,
894
964
  flush_interval: DEFAULT_AUTOMATIC_FLUSH_INTERVAL,
895
965
  flush_threshold: DEFAULT_AUTOMATIC_FLUSH_THRESHOLD,
896
966
  retry_base_delay: DEFAULT_AUTOMATIC_RETRY_BASE_DELAY,
@@ -923,6 +993,12 @@ module LogBrew
923
993
  client
924
994
  end
925
995
 
996
+ def self.resolve_server_api_key(api_key)
997
+ [api_key, ENV.fetch(SERVER_API_KEY_VARIABLE, nil)].find { |key| key.is_a?(String) && !key.strip.empty? } ||
998
+ raise(SdkError.new("configuration_error", "set #{SERVER_API_KEY_VARIABLE} or pass api_key"))
999
+ end
1000
+ private_class_method :resolve_server_api_key
1001
+
926
1002
  def initialize(
927
1003
  api_key:,
928
1004
  sdk:,
@@ -1036,7 +1112,7 @@ module LogBrew
1036
1112
  end
1037
1113
 
1038
1114
  def issue(id, timestamp, attributes)
1039
- push_event("issue", id, timestamp, validate_issue(attributes), event_context(attributes))
1115
+ push_event("issue", id, timestamp, RequestScope.with_breadcrumbs(validate_issue(attributes)), event_context(attributes))
1040
1116
  end
1041
1117
 
1042
1118
  def log(id, timestamp, attributes)
@@ -1114,6 +1190,8 @@ module LogBrew
1114
1190
  Validation.require_non_empty("event id", id)
1115
1191
  Validation.require_timestamp(timestamp)
1116
1192
  ambient_context = Telemetry.current_context
1193
+ user_context = RequestScope.subject_context
1194
+ ambient_context = TelemetryContext.merge(user_context, ambient_context) unless user_context.nil?
1117
1195
  active_trace = defined?(LogBrew::Trace) ? LogBrew::Trace.current : nil
1118
1196
  ambient_context = TelemetryContext.with_trace(ambient_context, active_trace) unless active_trace.nil?
1119
1197
  merged_context = TelemetryContext.merge(
@@ -1213,6 +1291,15 @@ module LogBrew
1213
1291
  )
1214
1292
  end
1215
1293
 
1294
+ if response.respond_to?(:timed_rate_limit?) && response.timed_rate_limit?
1295
+ raise DeliveryFailure.new(
1296
+ "transport_error",
1297
+ "unexpected transport status 429",
1298
+ automatic_retryable: true,
1299
+ automatic_rate_limit: response.retry_after || :backoff
1300
+ )
1301
+ end
1302
+
1216
1303
  pause_reason = case response.status_code
1217
1304
  when 429 then "quota"
1218
1305
  when 400, 422 then "validation"
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: logbrew-sdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.17
4
+ version: 0.1.20
5
5
  platform: ruby
6
6
  authors:
7
7
  - LogBrew
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-26 00:00:00.000000000 Z
11
+ date: 2026-12-04 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: Public LogBrew Ruby SDK with typed issue diagnostics, automatic Rails
14
14
  request/error capture, and standard-library delivery.
@@ -41,6 +41,7 @@ files:
41
41
  - lib/logbrew/queue_carrier.rb
42
42
  - lib/logbrew/rails.rb
43
43
  - lib/logbrew/rails_integration.rb
44
+ - lib/logbrew/request_scope.rb
44
45
  - lib/logbrew/sidekiq.rb
45
46
  - lib/logbrew/span_events.rb
46
47
  - lib/logbrew/support_ticket.rb
@@ -52,11 +53,12 @@ files:
52
53
  - lib/logbrew/traceparent.rb
53
54
  - lib/logbrew/version.rb
54
55
  - lib/logbrew/worker_lifecycle.rb
55
- homepage: https://github.com/LogBrewCo/sdk
56
+ homepage: https://logbrew.co
56
57
  licenses:
57
58
  - MIT
58
59
  metadata:
59
60
  source_code_uri: https://github.com/LogBrewCo/sdk
61
+ documentation_uri: https://docs.logbrew.co
60
62
  post_install_message:
61
63
  rdoc_options: []
62
64
  require_paths: