-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(server-utils): Add tracingChannel-to-span binding #21641
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e68b15b
feat(server-utils): Add tracingChannel-to-span binding
logaretm 685dbc4
feat: added knobs to enrich span and handler error reporting
logaretm 859d580
feat(server-utils): Return a teardown handle from bindTracingChannelT…
logaretm e34e28a
ref: make exclusive with beforeSpanEnd or captureException
logaretm 08b9cbb
feat(server-utils): Support opting payloads out of bindTracingChannel…
logaretm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import type { TracingChannel, TracingChannelSubscribers } from 'node:diagnostics_channel'; | ||
| import type { AsyncLocalStorage } from 'node:async_hooks'; | ||
| import type { Span } from '@sentry/core'; | ||
| import { _INTERNAL_getTracingChannelBinding, debug, captureException, SPAN_STATUS_ERROR } from '@sentry/core'; | ||
| import { DEBUG_BUILD } from './debug-build'; | ||
|
|
||
| export type TracingChannelPayloadWithSpan<TData extends object> = TData & { | ||
| _sentrySpan?: Span; | ||
| }; | ||
|
|
||
| /* | ||
| * A type patch so that we don't have to handle all subscription types. | ||
| */ | ||
| export interface SentryTracingChannel<TData extends object = object> extends Omit< | ||
| TracingChannel<TData, TracingChannelPayloadWithSpan<TData>>, | ||
| 'subscribe' | 'unsubscribe' | ||
| > { | ||
| subscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void; | ||
| unsubscribe(subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>>): void; | ||
| } | ||
|
|
||
| interface TracingChannelManualBindingOptions { | ||
| /** | ||
| * Whether the span is ended automatically (`auto`, default) or left to the caller (`manual`). | ||
| */ | ||
| lifecycle: 'manual'; | ||
| } | ||
|
|
||
| interface TracingChannelAutoBindingOptions<TData extends object = object> { | ||
| /** | ||
| * Whether the span is ended automatically (`auto`, default) or left to the caller (`manual`). | ||
| */ | ||
| lifecycle?: 'auto' | undefined; | ||
|
|
||
| /** | ||
| * Invoked with the span and the channel context object once the traced operation completes | ||
| * Use it to enrich the span from the result/error (branch on `'error' in data` / `'result' in data`) or to run cleanup. | ||
| */ | ||
| beforeSpanEnd?: (span: Span, data: TracingChannelPayloadWithSpan<TData>) => void; | ||
|
|
||
| /** | ||
| * Whether a thrown error is captured as a Sentry event. The span is always marked with error | ||
| * status regardless. Defaults to `true`. | ||
| * Set `false` for instrumentation that only annotates the span and lets the error be captured at the boundary that owns it (e.g. db spans). | ||
| */ | ||
| captureError?: boolean; | ||
| } | ||
|
|
||
| export type TracingChannelBindingOptions<TData extends object = object> = | ||
| | TracingChannelAutoBindingOptions<TData> | ||
| | TracingChannelManualBindingOptions; | ||
|
|
||
| /** Returned by {@link bindTracingChannelToSpan}: the bound channel plus a teardown handle. */ | ||
| export interface TracingChannelBindingHandle<TData extends object = object> { | ||
| /** The tracing channel with the span bound into async context (and, in `auto` mode, its lifecycle subscribed). */ | ||
| channel: SentryTracingChannel<TData>; | ||
| /** | ||
| * Tears down the binding: unsubscribes the auto lifecycle handlers and unbinds the start store. | ||
| * Idempotent, and a no-op when no async context binding was available. | ||
| */ | ||
| unbind: () => void; | ||
| } | ||
|
|
||
| const NOOP = (): void => {}; | ||
|
|
||
| export function bindTracingChannelToSpan<TData extends object>( | ||
| channel: TracingChannel<TData, TData>, | ||
| getSpan: (data: TracingChannelPayloadWithSpan<TData>) => Span, | ||
| opts?: TracingChannelBindingOptions<TData>, | ||
| ): TracingChannelBindingHandle<TData> { | ||
| const sentryChannel = channel as SentryTracingChannel<TData>; | ||
| const binding = _INTERNAL_getTracingChannelBinding(); | ||
|
|
||
| if (!binding) { | ||
| DEBUG_BUILD && debug.log('[TracingChannel] Could not access async context binding.'); | ||
| return { channel: sentryChannel, unbind: NOOP }; | ||
| } | ||
|
|
||
| const asyncLocalStorage = binding.asyncLocalStorage as AsyncLocalStorage<TData>; | ||
|
|
||
| channel.start.bindStore(asyncLocalStorage, (data: TracingChannelPayloadWithSpan<TData>) => { | ||
| const span = getSpan(data); | ||
| data._sentrySpan = span; | ||
|
|
||
| return binding.getStoreWithActiveSpan(span) as TData; | ||
| }); | ||
|
|
||
| const unbindStore = (): void => { | ||
| channel.start.unbindStore(asyncLocalStorage); | ||
| }; | ||
|
|
||
| if (opts && 'lifecycle' in opts && opts.lifecycle === 'manual') { | ||
| return { channel: sentryChannel, unbind: unbindStore }; | ||
| } | ||
|
|
||
| const beforeSpanEnd = opts?.beforeSpanEnd; | ||
|
|
||
| const subscribers: Partial<TracingChannelSubscribers<TracingChannelPayloadWithSpan<TData>>> = { | ||
| start: NOOP, | ||
| asyncStart: NOOP, | ||
| end(data) { | ||
| // The operation settled synchronously (returned or threw) | ||
| // Presence checks because caller can return `undefined` result or throw a falsy value. | ||
| if ('error' in data || 'result' in data) { | ||
| endBoundSpan(data, beforeSpanEnd); | ||
| } | ||
| }, | ||
| error(data) { | ||
| if (opts?.captureError !== false) { | ||
| captureException(data.error, { | ||
| mechanism: { | ||
| type: 'auto.diagnostic_channels.bind_span', | ||
| handled: false, | ||
| }, | ||
| }); | ||
| } | ||
| data._sentrySpan?.setStatus({ code: SPAN_STATUS_ERROR, message: getErrorMessage(data.error) }); | ||
| }, | ||
| asyncEnd(data) { | ||
| endBoundSpan(data, beforeSpanEnd); | ||
| }, | ||
| }; | ||
|
|
||
| sentryChannel.subscribe(subscribers); | ||
|
|
||
| return { | ||
| channel: sentryChannel, | ||
| unbind: () => { | ||
| sentryChannel.unsubscribe(subscribers); | ||
| unbindStore(); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| function endBoundSpan<TData extends object>( | ||
| data: TracingChannelPayloadWithSpan<TData>, | ||
| beforeSpanEnd: TracingChannelAutoBindingOptions<TData>['beforeSpanEnd'], | ||
| ): void { | ||
| const span = data._sentrySpan; | ||
| if (!span) { | ||
| return; | ||
| } | ||
| beforeSpanEnd?.(span, data); | ||
| span.end(); | ||
| } | ||
|
|
||
| /** Best-effort short message for a span status: an error-like's `message`, otherwise its string form. */ | ||
| function getErrorMessage(error: unknown): string { | ||
| if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string') { | ||
| return error.message; | ||
| } | ||
| return String(error); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sync end closes streaming spans early
Medium Severity
In
autolifecycle mode, theendhandler ends the bound span whenever'result' in data. Orchestrion-style channels (documented for mysql in this repo) can publishendwith aresultthat is only an in-flight handle (e.g. a streamableQueryemitter) while the operation continues with noasyncEnd. The span is ended at synchronousendinstead of when the work actually finishes.Reviewed by Cursor Bugbot for commit 3cb7959. Configure here.