Skip to content

About

DebugBundle Ruby SDK

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

debugbundle

Patch 2.1.4 preserves application hook redaction under optional-evidence limits and complete validation. Public capture APIs and event schemas remain compatible.

Ruby SDK for DebugBundle.

Use this gem to capture Ruby backend exceptions, request metadata, structured logs, runtime context, probe data, and browser relay traffic. It supports a singleton facade plus instance clients for Rack, Rails, Sidekiq, and explicit Ruby instrumentation.

The source test matrix covers Ruby 3.1 through 4.0. Rails 7.x remains an installed-base lane; the current Rails 8.1 lane exercises the relay and Rack middleware on Ruby 4.0. make compat runs the Rack, Rails, and Sidekiq Docker lanes, including Rails 8.1.

Version 2.0 changes capture and hook timing. Existing installed 1.5.x applications continue to use their pinned gem until upgraded. Review the migration guide before upgrading.

make sdk-safety-perf runs a Docker-backed host-safety budget with 10,000 filtered INFO calls, 1,000 accepted ERROR calls with and without custom privacy fields, and 10,000 concurrent ERROR calls against a full queue while transport is held. It also bounds 200 enriched exceptions and 1,000 recovery observations. CI and the release workflow run this gate before publication. These bounded synthetic checks supplement, but do not replace, installed runtime and workload qualification.

Mandatory privacy checks reuse at most 256 field-name decisions and 256 unchanged scalar strings of at most 128 bytes within each projection. Returned values remain independently owned. Every value and repeated key still counts against the existing resource budgets; both caches are discarded before the next event or policy.

Installation

gem install debugbundle

Or add it to your Gemfile and run bundle install:

gem "debugbundle"

Initialize

Initialize once at application startup with DEBUGBUNDLE_PROJECT_TOKEN set in the server environment. Initialization arms best-effort process exception capture. Add framework and logger adapters below.

require "debugbundle"

DebugBundle.init(
  project_token: ENV["DEBUGBUNDLE_PROJECT_TOKEN"],
  environment: "production",
  service: "api"
)

Integrations

Rails, Rack, Sidekiq, Ruby Logger, Semantic Logger and browser relay handlers are supported.

Capture setup details

DebugBundle.init(...) arms best-effort process exception capture automatically through at_exit and thread exception hooks. These hooks wake the sender without waiting for delivery; shutdown exceptions can be lost if the process exits before the sender finishes. Automatic delivery runs on one background sender thread when the configured batch size or flush interval is reached. Remote configuration uses a separate bounded poller so a slow fetch cannot hold delivery. An explicit flush waits for the sender for at most five seconds and reports whether delivery completed. Call it during a controlled shutdown window when delivery is required. A forked child starts fresh workers on its first SDK use and drops inherited parent events, context, and probes while retaining the parent's capture restrictions until remote configuration refreshes.

Framework Integrations

Surface Integration
Rack DebugBundle::Rack::Middleware
Rails Railtie bootstrap, Rack middleware, and auto-mounted relay route
Sidekiq DebugBundle::Sidekiq::ServerMiddleware
Ruby Logger DebugBundle.capture_logger(logger)
Semantic Logger DebugBundle.capture_semantic_logger
Browser relay DebugBundle::Relay::Handler or DebugBundle::Rack::RelayMiddleware

Browser Relay

Ruby backends can receive browser events at POST /debugbundle/browser through the relay handler.

Rails applications can let the Railtie append that route automatically, or override it with:

  • config.debugbundle.relay_enabled = false to disable automatic mounting
  • config.debugbundle.relay_path = "/debugbundle/browser" to change the mounted path
  • config.debugbundle.relay_allowed_origins = ["https://app.example.com"] to pin allowed origins
  • config.debugbundle.relay_rate_limit_per_minute = 120 to adjust per-IP rate limiting
  • config.debugbundle.relay_rate_limit_store = Rails.cache to share rate limiting across processes
  • config.debugbundle.relay_handler = custom_handler to supply a custom relay handler

Rack applications can mount the same handler explicitly:

relay_handler = DebugBundle::Relay::Handler.new(
  project_mode: :connected,
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  endpoint: "https://api.debugbundle.com/v1/events",
  allowed_origins: ["https://app.example.com"]
)

use DebugBundle::Rack::RelayMiddleware, handler: relay_handler

Relay behavior:

  • same-origin is the safe default when you do not set explicit allowed origins
  • use explicit allowed origins when the frontend and backend live on different hosts
  • requests must use Content-Type: application/json
  • request bodies are capped at 256 KB
  • per-IP rate limiting defaults to 60 requests per minute
  • browser-supplied DebugBundle credentials are stripped before delivery, preserving credential isolation
  • browser service, environment, and correlation fields are preserved unless you explicitly override them in the relay handler
  • local-only mode writes validated browser events to .debugbundle/local/events
  • connected durable mode writes validated browser events to .debugbundle/local/browser-relay-spool before forwarding to the configured endpoint
  • set relay_durable_write: false when you intentionally want connected forwarding without the local spool write
  • to disable the relay entirely, leave the route unmounted or set relay_enabled = false
  • a missing token means connected forwarding cannot succeed; treat that as a server config error and leave the route disabled until the server-side token is fixed

Manual capture and logging

require "logger"

DebugBundle.capture_logger(Logger.new($stdout))

begin
  perform_checkout
rescue => error
  DebugBundle.capture_exception(error, context: { order_id: 123 })
end

DebugBundle.capture_message("worker started", level: :info)
DebugBundle.flush

First-event verification

Use an explicit setup event in a development or staging application, then confirm the matching service and environment in a received event or incident. Initialization, a healthy status and an empty queue are not delivery receipts. Keep the application running long enough for delivery; use bounded flushing only in tests or controlled teardown, never in a request handler.

Use an explicit test message or exception during setup:

require "debugbundle"

DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "debugbundle-first-event",
  environment: "staging"
)

DebugBundle.capture_message("debugbundle first-event verification", level: :error)
DebugBundle.flush
puts [DebugBundle.status, DebugBundle.last_event_at].inspect

Then confirm the event through your mock ingestion endpoint, a staging project, or the DebugBundle CLI verification flow.

This repository also ships a clean-install app-driven smoke harness that validates the built gem and the published gem path:

make smoke
make smoke-published VERSION=1.5.0

make smoke builds the gem, installs it into a fresh RubyGems home, drives a Rack request plus a browser relay batch through the public SDK surface, validates event envelope shape, and confirms the mock ingestion endpoint receives the expected service, environment, SDK metadata, and correlation fields. For version 2.0, it also forks the installed client and verifies exactly one child event without replaying the parent's buffered event.

For connected delivery, confirm the event in DebugBundle and inspect its incident with the CLI. For local-file delivery, run debugbundle process followed by debugbundle inspect <incident-id>. A local file or mock endpoint receipt proves only that destination; it does not prove cloud acceptance.

Configuration

Configuration sources and precedence:

  1. Explicit arguments passed to DebugBundle.init(...), DebugBundle::Client.new(...), or DebugBundle::Relay::Handler.new(...).
  2. Rails config.debugbundle.* values when the Railtie wires the default client or relay route.
  3. Environment variables only when your application chooses to pass them into those explicit Ruby calls. The gem does not auto-read arbitrary config env vars on its own.
  4. Remote probe directives and capture policy returned by GET /v1/sdk/config after a connected client initializes.

Capture-policy fields are server-owned and must not be supplied in local SDK config. The Ruby SDK enforces the server response locally after initialization.

Option Default Purpose
project_token required for connected capture Write-only DebugBundle project token used by server-side transport.
service ruby-service Service name used in event envelopes.
environment development Runtime environment.
endpoint https://api.debugbundle.com/v1/events Connected ingestion endpoint.
enabled true Disable all capture without removing instrumentation.
project_mode connected connected or local_only.
local_events_dir .debugbundle/local/events Local event file destination.
spool_dir .debugbundle/local/browser-relay-spool Relay durable spool destination.
redact_fields [] Additional broad segment-matched sensitive field names merged with built-in redaction defaults. Rails filter_parameters are added automatically.
redact_exact_fields [] Additional exact-match sensitive field names (ASCII case-insensitive whole-key, query-parameter, and non-identifier text assignment matching with punctuation significant). Shares a 128-key combined ceiling with redact_fields.
batch_size 25 Wake the background sender when this many events are buffered.
flush_interval 5 Flush interval in seconds.
sample_rate 1.0 Fraction of events kept before transport.
log_level warning Minimum captured log severity.
relay_enabled true Enable relay handling when using the Rails helper surface.
relay_rate_limit_per_minute 60 Per-IP rate limit for browser relay requests.
relay_durable_write true Write relay batches to the local spool before connected forwarding.
max_probe_labels 50 Max distinct probe labels kept in memory.
max_probe_entries_per_label 10 Max entries retained per probe label.
probe_flush_on_error true Attach probe buffers to captured exceptions.
probes_poll_interval 60 Remote config poll interval in seconds.

Evidence in 2.1.0

Version 2.1.0 adds structured exception evidence and explicit recovery. Enrichment requires a valid capability descriptor from the destination on an existing config/ingestion response. No extra discovery request is made. Unknown paths keep ordinary exception capture. The optional evidence_capabilities: { version: 1, features: [...] } pin asserts that every receiver, relay, spool/local processor and reader on that path has been qualified; it does not upgrade any receiver. capture_exception_evidence: false disables the new exception fields independently.

capture_recovery_observations defaults to false. With destination proof and the option enabled, report application-observed outcomes inside an operation:

require "securerandom"

client = DebugBundle::Client.new(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  capture_recovery_observations: true
)

client.with_operation_context(kind: "job", name: "asset.prepare", limit_ms: 5000) do
  begin
    prepare_asset
  rescue => error
    failure_ref = SecureRandom.uuid
    attempt_id = SecureRandom.uuid
    client.capture_exception(error, context: { failure_ref: failure_ref })
    client.capture_recovery(failure_ref: failure_ref, attempt_id: attempt_id, state: "attempt_started")
    result = application_recovery
    client.capture_recovery(failure_ref: failure_ref, attempt_id: attempt_id, state: "attempt_completed")
    client.capture_recovery(
      failure_ref: failure_ref, attempt_id: attempt_id,
      state: result.usable? ? "recovery_observed" : "failure_persisted"
    )
  end
end

The application owns recovery and its success check. attempt_completed and a successful HTTP status do not establish recovery. attempt_failed records a failed attempt. Observations need no subsequent exception and do not open or resolve incidents. Use fresh UUID-v4 failure, attempt and scope IDs. For reporting outside the active operation, provide the same explicit evidence_scope at failure capture and in each observation. Page scopes additionally require the same nonblank session correlation; the string "0" is valid. Recovery accepts a Hash or keyword fields; scope/context Hash keys may be strings or symbols.

Operations retain only bounded kind/name/elapsed/known-limit and correlation metadata. They preserve the block's return value and exceptions. Rack/Rails request and Sidekiq job capture runs inside its owned scope; other Fibers/threads do not inherit it. Completed scopes and process resets revoke ownership. Graphs use retained scalar exception snapshots, with no additional custom rendering or source/local-variable inspection. Ruby's linear cause path has at most five nodes and 32 frames per node, within a combined 32 KiB evidence budget. Fatal hooks use at most two nodes, eight frames per node and 4 KiB of total new evidence; delivery remains best-effort at process exit. Original sanitised stacks remain. Engine metadata is preserved under payload.runtime.framework_extras.

Diagnostic metadata and pending events share 64 KiB, at most 50 failure windows, five attempts and 20 observations per window, and a five-minute capture window. Policy capture_diagnostic_context: false and the minimal preset disable recovery. Canonical before_send replacements may change identity and event type; the SDK reapplies privacy, policy, path proof and bounded ownership. An acknowledged capability downgrade may retry an original exception once without optional evidence, using the same identity and no second hook invocation.

Hook replacements pass the complete vendored canonical schema and its conditional frontend identity checks before and after mandatory privacy. Invalid replacements fall back to the protected original; explicit nil still drops an event. Existing queue-pressure aggregate reason and level fields remain supported.

Outgoing requests stay within the receiver's 256 KiB body limit, counting actual escaped UTF-8 JSON. The sender keeps ordered byte-sized batches and schedules remaining work on its existing worker. Acknowledgement indices apply to each submitted chunk. Oversized optional evidence is removed first; a valid hook replacement that still cannot fit is withheld without restoring pre-hook content. Invalid or throwing hooks retain the established safe-original fallback. Flush remains a bounded, best-effort wait; queued tails can continue after it returns. Local file transport keeps its existing bounded ownership and file semantics; the HTTP body limit does not narrow admissible local captures.

Native HTTP config/ACK replies request identity encoding and retain at most 256 KiB before JSON parsing. Existing native connect/read timeouts remain five seconds; relay chunks and downgrade retries share one five-second monotonic budget, passed to native response reads and remaining connect/read timeouts. A body deadline is checked between streamed chunks. Native DNS/socket waits remain advisory. Explicit flush still waits at most five seconds. close stops this process's sender, discards queued work and retains active-send accounting until completion. A forked child follows the existing fresh-worker contract. dispose permanently retires a client across process generations; singleton DebugBundle.init disposes its superseded client. Reinstall explicitly configured logger/integration bindings for a replacement client. Independently constructed clients remain available for applications that intentionally own multiple projects.

Rack and Rails browser relays preserve validated evidence and server-owned credentials. Downstream chunks account for server metadata expansion; a durable spool is marked delivered only when every chunk has a complete canonical acknowledgement. Legacy custom transport success remains compatible and cannot create a delivered marker. Installed/runtime qualification passed before publication.

Automatic capture and application filtering

capture_logger(logger) respects the logger level, Rails silence and disabled output. Lazy message blocks are evaluated by the native logger: zero times when suppressed and once when accepted. Native return values and application block exceptions are preserved. DebugBundle applies its own configured minimum capture level after the logger accepts a message.

Install Examples by Mode

Connected mode

require "debugbundle"

DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "checkout-api",
  environment: "production",
  endpoint: "https://api.debugbundle.com/v1/events"
)

Local-only mode

require "debugbundle"

DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "checkout-api",
  environment: "development",
  project_mode: :local_only,
  local_events_dir: ".debugbundle/local/events"
)

Rack middleware

require "debugbundle"
require "rack"

client = DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "checkout-api",
  environment: "production"
)

app = Rack::Builder.new do
  use DebugBundle::Rack::Middleware, client: client

  run lambda { |_env|
    [200, { "Content-Type" => "text/plain" }, ["ok"]]
  }
end

Rails initializer

# config/initializers/debugbundle.rb
require "debugbundle"

DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "checkout-api",
  environment: Rails.env
)

Rails.application.configure do
  config.debugbundle.relay_allowed_origins = ["https://app.example.com"]
end

Sidekiq server middleware

require "debugbundle"

DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "checkout-worker",
  environment: ENV.fetch("APP_ENV", "production")
)

Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add(DebugBundle::Sidekiq::ServerMiddleware, client: DebugBundle.client)
  end
end

Logger integration

require "debugbundle"
require "logger"

DebugBundle.init(
  project_token: ENV.fetch("DEBUGBUNDLE_PROJECT_TOKEN"),
  service: "checkout-api"
)

logger = Logger.new($stdout)
DebugBundle.capture_logger(logger)

Runtime and Framework Support

Surface Minimum compatibility version Recommended production version Installed-base compatibility lane Rolling CI lane Out of scope
Ruby runtime 3.1 current maintained Ruby 3.4.x patch line 3.1 and 3.2 remain supported for installed-base coverage 3.1, 3.2, 3.3, 3.4 3.0 and older
Rails 7.0 latest 7.1 patch line 7.0 compatibility support 7.0 and 7.1 6.x and older
Rack 2.2 latest 3.x patch line 2.2 compatibility support 2.2 and 3.x 2.1 and older
Sidekiq 7.x latest 8.x patch line 7.x compatibility support 7.x and 8.x 6.x and older

Post-V1 integrations remain out of scope here: Resque, Delayed Job, GoodJob, Sneakers, Shoryuken, Sinatra, Hanami, and deep ActiveRecord or SQL auto-instrumentation.

Dependency Alignment

debugbundle ships as one gem in V1, so there is no multi-package version-alignment surface like an npm family rule or Maven BOM.

  • Pin one debugbundle version across your Ruby web app and worker repos when you want identical SDK behavior everywhere.
  • Keep Rack, Rails, and Sidekiq inside the supported lanes above.
  • Do not mix unsupported framework majors into examples or deployment templates.

Remote Probes

Probe buffers stay local and flush on captured exceptions by default. Paid-tier projects can also activate probes for immediate probe_event shipping through the polled remote config.

For one-off request diagnostics, the Ruby SDK also accepts signed trigger tokens:

  • header: X-DebugBundle-Probe-Trigger: dbundle_probe_...
  • query parameter: ?_debug_probe=dbundle_probe_...

Matching probes still stay in the local ring buffer, but the triggered request also emits standalone probe_event records immediately when the token is valid.

Safety Defaults

  • SDK failures are isolated from host application failures.
  • Sensitive values are redacted before buffering or transport.
  • Rails filter_parameters are merged into redaction automatically.
  • Duplicate event storms are suppressed locally.
  • Request headers use an allowlist by default.
  • Local file writes use owner-only permissions.
  • development, local, and test environments write local event files by default.
  • Browser relay requests cannot smuggle server-side credentials.

Service Naming

Use distinct service names when one DebugBundle project receives events from multiple deployables:

  • Browser frontend: checkout-web
  • Rails or Rack API: checkout-api
  • Sidekiq worker: checkout-worker

The Ruby relay preserves the browser-provided service name and environment by default. Only override relay-level service or environment when you intentionally want the backend relay host to rewrite browser event identity.

Safe Startup and Status

The SDK never raises host-facing exceptions because of missing config, bad transport responses, or malformed remote config payloads.

  • DebugBundle.init(project_token: "") leaves capture disabled and DebugBundle.status reports :degraded
  • DebugBundle.init(enabled: false) keeps the SDK as a no-op and DebugBundle.status reports :disconnected
  • DebugBundle.last_event_at stays nil until a successful flush completes
  • DebugBundle.flush is a no-op when the SDK has no buffered events, no transport, or is still waiting out a retry window

Status meanings:

  • :healthy — idle or the last flush succeeded
  • :degraded — missing token or a temporary rate-limit window is preventing immediate delivery
  • :disconnected — the SDK is disabled or repeated transport failures exhausted the connection path

The release rule here is fail-safe, not fail-open: connected mode with a missing token must never pretend capture is healthy.

Examples

Development

The project defaults to Docker-backed commands:

make bundle-install
make test
make compat
make lint
make build
make smoke

CI validates RSpec, RuboCop, compatibility lanes, gem build, and the clean-install smoke harness.

Release

The repository ships a GitHub Actions release workflow at .github/workflows/release.yml.

  • Push a v* tag or run the workflow manually with a version input.
  • Configure the RUBYGEMS_API_KEY repository secret before enabling publish.
  • The workflow runs lint, tests, the full make compat framework/runtime matrix, gem build, make smoke, RubyGems publish, and make smoke-published VERSION=<tag> before creating the GitHub release.

Documentation

License

Apache-2.0. See LICENSE.

Delivery acknowledgement and retry limits

The built-in HTTP transport requires the canonical ingestion acknowledgement (accepted, rejected, and errors). Empty responses, unrelated JSON, malformed counts, or invalid rejection indices retain the full batch with backoff. Valid acknowledgements remove accepted and terminally rejected events and retry only the indexed retryable rejections; an all-rejected batch does not advance lastEventAt.

File transports and explicitly supplied custom/legacy transports retain their documented bodyless success fallback. A custom transport that returns acknowledgement fields must return the complete canonical shape. Retry hints (delay seconds or HTTP dates) are bounded to five minutes and measured from response receipt, including partial/protocol acknowledgements and retryable server failures. Without a server hint, existing retry timing is preserved. Failures remain contained within the SDK's existing delivery path.

Probe checkpoint guidance

Application instrumentation supplies probe labels and bounded data. Deploy a new checkpoint before activating it. Remote activation affects future matching calls when policy permits; it does not inject code or recover unretained measurements. Built-in runtime/error/device collectors keep their documented SDK settings.

Use fixed labels and allowlisted technical states: media.preview.checkpoint (stage/input kind/attempt), auth.session.checkpoint (observed session presence and result), job.dependency.checkpoint (named dependency/attempt/result), or cache.preview.checkpoint (hit/miss/coarse age bucket). Omit customer identifiers, tokens/cookies, cache keys, URLs and raw payloads. HTTP 200 or attempt completion alone does not establish semantic recovery.

Empty probe data means no matching retained observation for the selected sample window. It does not confirm activation delivery to every SDK or execution of a label. Check the deployed SDK/wrapper version, instrumentation, scope, expiry, policy, sampling and delivery receipts. See the probe recipes.

Acceptance-credential privacy

The SDK scrubs standalone dbundle_invite_, dbundle_org_invite_ and dbundle_org_transfer_ acceptance secrets before SDK-owned retention or transmission. See the shared qualification record. Existing installations receive this protection when upgraded to a version that includes it.

Maintainer performance checks

make evidence-performance compares the same exception/recovery calls with evidence disabled and enabled, including a full warning queue. It reports capture time, allocated Ruby objects and retained bytes, and verifies original-error priority and the existing queue/diagnostic ceilings. Setup and cleanup are excluded; the existing sdk-safety-perf timing limits remain unchanged.

Hook size limits

A hook replacement whose optional exception evidence exceeds the combined 32 KiB UTF-8 JSON budget keeps its replacement message and other primary fields. The SDK omits the oversized optional evidence and its typed reference, recording context.evidence_limits. Ordinary custom context remains intact. A size limit must not restore text removed by the hook; an otherwise valid replacement that cannot fit later ownership or transport limits is withheld. Malformed returns and throwing hooks retain the established protected-original fallback.

About

DebugBundle Ruby SDK

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages