Skip to content

Conversation

dagyu
Copy link

@dagyu dagyu commented Aug 31, 2025

This PR introduces a new optional function checkIfShouldTrace to ElysiaOpenTelemetryOptions.
It allows users to filter out specific requests (e.g., /health, /metrics) that are typically not useful to trace, reducing noise and overhead in telemetry data.


Changes

  • Extended ElysiaOpenTelemetryOptions with a new property:

    • checkIfShouldTrace?: (req: Request) => boolean
  • Wrapped the tracing logic in a conditional that evaluates this function before starting a span.


Updated Interface

export interface ElysiaOpenTelemetryOptions extends OpenTeleMetryOptions {
  contextManager?: ContextManager
  /**
   * Optional function to determine whether a given request should be traced.
   *
   * @param req - The incoming request object to evaluate.
   * @returns A boolean indicating whether tracing should be enabled for this request.
   */
  checkIfShouldTrace?: (req: Request) => boolean
}

Example Usage

import { Elysia } from 'elysia'
import { OpenTelemetryPlugin } from './otel-plugin'

const app = new Elysia().use(
  OpenTelemetryPlugin({
    checkIfShouldTrace: (req) => {
      // Skip tracing for health and metrics endpoints
      const url = new URL(req.url)
      return !['/health', '/metrics'].includes(url.pathname)
    }
  })
)

Benefits

  • Allows developers to avoid tracing "noise" endpoints like /health, /metrics, or static assets.
  • Improves performance and reduces unnecessary trace storage.

Summary by CodeRabbit

  • New Features
    • Added per-request tracing control to the OpenTelemetry integration via a new option that lets you decide whether to enable tracing for each request. When disabled for a request, tracing is skipped to reduce overhead.
  • Documentation
    • Documented the new per-request tracing option with inline comments for easier adoption.

Copy link

coderabbitai bot commented Aug 31, 2025

Walkthrough

Introduces a per-request tracing gate to the OpenTelemetry integration by adding an optional checkIfShouldTrace(req) option. The opentelemetry wrapper now conditionally applies tracing based on this predicate, returning the original handler unwrapped when the check returns false. JSDoc added for the new option.

Changes

Cohort / File(s) Summary of Edits
Per-request tracing control
src/index.ts
- Added checkIfShouldTrace?: (req: Request) => boolean to ElysiaOpenTelemetryOptions
- Updated opentelemetry to destructure the new option
- Wrapped request handling to bypass tracing when checkIfShouldTrace(req) is false
- Added JSDoc for the new option

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant S as Server Route Handler
  participant OT as OpenTelemetry Wrapper
  participant P as checkIfShouldTrace(req)

  C->>S: HTTP Request
  activate S
  S->>OT: Invoke wrapped handler
  activate OT
  OT->>P: Evaluate predicate
  alt Should trace
    OT->>OT: Start span
    OT->>S: Call original handler (traced)
    S-->>OT: Response/Result
    OT->>OT: End span
    OT-->>C: Response
  else Skip tracing
    OT-->>S: Return original handler (no tracing)
    S-->>C: Response
  end
  deactivate OT
  deactivate S
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my ears at every trace,
But now I choose, case by case.
If burrow’s quiet, I hop on through—
No spans today, just morning dew.
When carrots glow with signal light,
I trace the trail, nibble bright.
Logs by moon, hops by byte. 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/index.ts (1)

61-67: Clarify default behavior in JSDoc and constraints

State explicitly that when omitted, all requests are traced (default true). Also note that the predicate should be fast and must not consume the request body, as it runs before parsing.

Apply this doc tweak:

 /**
  * Optional function to determine whether a given request should be traced.
  *
  * @param req - The incoming request object to evaluate.
- * @returns A boolean indicating whether tracing should be enabled for this request.
+ * @returns A boolean indicating whether tracing should be enabled for this request.
+ *          If not provided, tracing is enabled for all requests by default.
+ *          Keep this check lightweight and avoid consuming the request body.
  */
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cd52234 and f711020.

📒 Files selected for processing (1)
  • src/index.ts (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/index.ts (1)
test/test-setup.ts (1)
  • req (37-38)
🔇 Additional comments (1)
src/index.ts (1)

223-225: Option plumbed correctly

Destructuring checkIfShouldTrace into the plugin factory signature looks good.

Comment on lines +276 to +287
return new Elysia({
name: '@elysia/opentelemetry'
})
.wrap((fn, request) => {
const shouldTrace = checkIfShouldTrace
? checkIfShouldTrace(request)
: true

if (!shouldTrace) {
return fn
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Suppress downstream auto-instrumentation when tracing is disabled + harden predicate call

Returning fn skips the root “request” span, but downstream auto-instrumentations (fetch/http, db, etc.) may still create spans, producing noise for routes you intended to exclude. Suppress instrumentation in the context for the request when shouldTrace is false. Also guard the predicate to avoid crashing the request if it throws; fail-open to tracing for debuggability.

Apply within this hunk:

-        .wrap((fn, request) => {
-            const shouldTrace = checkIfShouldTrace
-                ? checkIfShouldTrace(request)
-                : true
+        .wrap((fn, request) => {
+            let shouldTrace = true
+            if (checkIfShouldTrace) {
+                try {
+                    shouldTrace = !!checkIfShouldTrace(request)
+                } catch {
+                    // Fail-open: keep tracing enabled if predicate throws
+                    shouldTrace = true
+                }
+            }
 
-            if (!shouldTrace) {
-                return fn
-            }
+            if (!shouldTrace) {
+                // Prevent any spans from being created for this request
+                const suppressed = suppressInstrumentation(otelContext.active())
+                return otelContext.bind(suppressed, fn)
+            }

And add the required import at the top of the file:

+import { suppressInstrumentation } from '@opentelemetry/core'

If @opentelemetry/core isn’t already a runtime dependency, add it to dependencies (not just via transitive SDK).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return new Elysia({
name: '@elysia/opentelemetry'
})
.wrap((fn, request) => {
const shouldTrace = checkIfShouldTrace
? checkIfShouldTrace(request)
: true
if (!shouldTrace) {
return fn
}
// Add at the top of src/index.ts
import { suppressInstrumentation } from '@opentelemetry/core'
return new Elysia({
name: '@elysia/opentelemetry'
})
.wrap((fn, request) => {
// Harden the predicate call
let shouldTrace = true
if (checkIfShouldTrace) {
try {
shouldTrace = !!checkIfShouldTrace(request)
} catch {
// Fail-open: keep tracing enabled if predicate throws
shouldTrace = true
}
}
// If tracing is disabled, suppress all downstream instrumentation
if (!shouldTrace) {
const suppressed = suppressInstrumentation(otelContext.active())
return otelContext.bind(suppressed, fn)
}
// …rest of the original handler…
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant