-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(core): Add bindScopeToEmitter to bind a scope to an event emitter
#21594
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
mydea
wants to merge
5
commits into
develop
Choose a base branch
from
feat/bind-scope-to-emitter
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a5b70bc
feat(core): Add `bindScopeToEmitter` to bind a scope to an event emitter
mydea 9fcbe97
ref(browser): Exclude bindScopeToEmitter from CDN bundles
mydea c098917
fix(core): Track multiple registrations of the same listener in bindS…
mydea 5f01351
tweak
mydea 60891cf
fix(core): Reuse one wrapper per listener in bindScopeToEmitter
mydea 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
8 changes: 8 additions & 0 deletions
8
dev-packages/browser-integration-tests/suites/tracing/bindScopeToEmitter/init.js
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,8 @@ | ||
| import * as Sentry from '@sentry/browser'; | ||
|
|
||
| window.Sentry = Sentry; | ||
|
|
||
| Sentry.init({ | ||
| dsn: 'https://public@dsn.ingest.sentry.io/1337', | ||
| tracesSampleRate: 1, | ||
| }); |
21 changes: 21 additions & 0 deletions
21
dev-packages/browser-integration-tests/suites/tracing/bindScopeToEmitter/subject.js
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,21 @@ | ||
| // A browser-native event target. | ||
| const target = new EventTarget(); | ||
|
|
||
| const parentSpan = Sentry.startInactiveSpan({ name: 'parent' }); | ||
|
|
||
| // Bind + register the listener while `parentSpan` is the active span. | ||
| Sentry.withActiveSpan(parentSpan, () => { | ||
| Sentry.bindScopeToEmitter(target); | ||
|
|
||
| target.addEventListener('data', () => { | ||
| Sentry.startSpan({ name: 'child-bound' }, () => { | ||
| // noop | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| // At this point no span is active. Dispatching should re-enter the bound (parent) scope, | ||
| // so `child-bound` is nested under `parent` rather than starting its own trace. | ||
| target.dispatchEvent(new Event('data')); | ||
|
|
||
| parentSpan.end(); |
32 changes: 32 additions & 0 deletions
32
dev-packages/browser-integration-tests/suites/tracing/bindScopeToEmitter/test.ts
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,32 @@ | ||
| import { expect } from '@playwright/test'; | ||
| import { sentryTest } from '../../../utils/fixtures'; | ||
| import { | ||
| envelopeRequestParser, | ||
| shouldSkipCdnBundleTest, | ||
| shouldSkipTracingTest, | ||
| waitForTransactionRequest, | ||
| } from '../../../utils/helpers'; | ||
|
|
||
| sentryTest('bindScopeToEmitter runs listeners with the bound scope active', async ({ getLocalTestUrl, page }) => { | ||
| // `bindScopeToEmitter` is not exported from the CDN bundles, only from npm. | ||
| if (shouldSkipTracingTest() || shouldSkipCdnBundleTest()) { | ||
| sentryTest.skip(); | ||
| } | ||
|
|
||
| const req = waitForTransactionRequest(page, e => e.transaction === 'parent'); | ||
|
|
||
| const url = await getLocalTestUrl({ testDir: __dirname }); | ||
| await page.goto(url); | ||
|
|
||
| const parentEvent = envelopeRequestParser(await req); | ||
| const parentSpanId = parentEvent.contexts?.trace?.span_id; | ||
| const parentTraceId = parentEvent.contexts?.trace?.trace_id; | ||
| expect(parentSpanId).toMatch(/[a-f\d]{16}/); | ||
|
|
||
| // The listener fired while no span was active, yet `child-bound` is nested under `parent` | ||
| // because the parent scope was bound to the emitter. | ||
| const childBound = parentEvent.spans?.find(s => s.description === 'child-bound'); | ||
| expect(childBound).toBeDefined(); | ||
| expect(childBound?.parent_span_id).toBe(parentSpanId); | ||
| expect(childBound?.trace_id).toBe(parentTraceId); | ||
| }); |
44 changes: 44 additions & 0 deletions
44
dev-packages/node-integration-tests/suites/public-api/bindScopeToEmitter/scenario.ts
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,44 @@ | ||
| import { EventEmitter } from 'node:events'; | ||
| import type { Span } from '@sentry/core'; | ||
| import * as Sentry from '@sentry/node'; | ||
| import { loggingTransport } from '@sentry-internal/node-integration-tests'; | ||
|
|
||
| Sentry.init({ | ||
| dsn: 'https://public@dsn.ingest.sentry.io/1337', | ||
| release: '1.0', | ||
| tracesSampleRate: 1.0, | ||
| integrations: [], | ||
| transport: loggingTransport, | ||
| }); | ||
|
|
||
| const boundEmitter = new EventEmitter(); | ||
| const unboundEmitter = new EventEmitter(); | ||
|
|
||
| let parentSpan: Span; | ||
|
|
||
| Sentry.startSpanManual({ name: 'parent' }, span => { | ||
| parentSpan = span; | ||
|
|
||
| // Bind the current (parent) scope to the emitter. Listeners registered afterwards should run | ||
| // with the parent span active, even when they fire in a different async context. | ||
| Sentry.bindScopeToEmitter(boundEmitter); | ||
|
|
||
| boundEmitter.on('data', () => { | ||
| Sentry.startSpan({ name: 'child-bound' }, () => undefined); | ||
| }); | ||
|
|
||
| // The unbound emitter is the control: its listener should NOT see the parent span. | ||
| unboundEmitter.on('data', () => { | ||
| Sentry.startSpan({ name: 'child-unbound' }, () => undefined); | ||
| }); | ||
| }); | ||
|
|
||
| // Emit from a fresh async context (a timer scheduled at the top level), where the parent span is | ||
| // no longer active. Only the bound emitter should re-enter the parent scope. | ||
| setTimeout(() => { | ||
| unboundEmitter.emit('data'); | ||
| boundEmitter.emit('data'); | ||
| parentSpan.end(); | ||
| // eslint-disable-next-line @typescript-eslint/no-floating-promises | ||
| Sentry.flush(); | ||
| }, 10); |
40 changes: 40 additions & 0 deletions
40
dev-packages/node-integration-tests/suites/public-api/bindScopeToEmitter/test.ts
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,40 @@ | ||
| import type { TransactionEvent } from '@sentry/core'; | ||
| import { afterAll, expect, test } from 'vitest'; | ||
| import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; | ||
|
|
||
| afterAll(() => { | ||
| cleanupChildProcesses(); | ||
| }); | ||
|
|
||
| test('bindScopeToEmitter preserves the active span for listeners firing in a different async context', async () => { | ||
| // Collect both transactions regardless of the order they are flushed in. | ||
| const transactions: Record<string, TransactionEvent> = {}; | ||
| const collect = (event: TransactionEvent): void => { | ||
| transactions[event.transaction as string] = event; | ||
| }; | ||
|
|
||
| await createRunner(__dirname, 'scenario.ts') | ||
| .expect({ transaction: collect }) | ||
| .expect({ transaction: collect }) | ||
| .start() | ||
| .completed(); | ||
|
|
||
| const parent = transactions['parent']; | ||
| const childUnbound = transactions['child-unbound']; | ||
|
|
||
| expect(parent).toBeDefined(); | ||
| expect(childUnbound).toBeDefined(); | ||
|
|
||
| const parentTraceId = parent?.contexts?.trace?.trace_id; | ||
| const parentSpanId = parent?.contexts?.trace?.span_id; | ||
|
|
||
| // The bound emitter's listener ran inside the parent span context -> nested child span. | ||
| const childBound = parent?.spans?.find(span => span.description === 'child-bound'); | ||
| expect(childBound).toBeDefined(); | ||
| expect(childBound?.parent_span_id).toBe(parentSpanId); | ||
| expect(childBound?.trace_id).toBe(parentTraceId); | ||
|
|
||
| // The unbound emitter's listener ran without the parent active -> its own, separate trace. | ||
| expect(childUnbound?.spans).toEqual([]); | ||
| expect(childUnbound?.contexts?.trace?.trace_id).not.toBe(parentTraceId); | ||
| }); |
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,182 @@ | ||
| import { getCurrentScope, withScope } from '../currentScopes'; | ||
| import type { Scope } from '../scope'; | ||
|
|
||
| type BoundListener = (...args: unknown[]) => unknown; | ||
|
|
||
| /** | ||
| * Per-event map from a user-provided listener to its single scope-bound wrapper. We reuse one stable | ||
| * wrapper per listener (rather than minting a new one per registration) and let the underlying | ||
| * emitter/target handle repeat registrations: | ||
| * - Node's `EventEmitter` allows duplicates and counts them, so registering the same wrapper N times | ||
| * fires N times and `removeListener` removes one instance per call — no orphaned wrappers. | ||
| * - the DOM `EventTarget` dedupes by `(type, callback, capture)`, so reusing the wrapper preserves | ||
| * that idempotency; a fresh wrapper per call would defeat it and fire the listener repeatedly. | ||
| */ | ||
| type ListenerPatchMap = Record<string, WeakMap<BoundListener, BoundListener> | undefined>; | ||
|
|
||
| // We patch both Node.js `EventEmitter` registration methods (`on`, `addListener`, ...) and the DOM | ||
| // `EventTarget.addEventListener`, so this works for Node emitters and browser-native event targets. | ||
|
|
||
| /** Listener-registration methods we patch so listeners inherit the bound scope. */ | ||
| const ADD_LISTENER_METHODS = [ | ||
| 'addListener', | ||
| 'on', | ||
| 'once', | ||
| 'prependListener', | ||
| 'prependOnceListener', | ||
| 'addEventListener', | ||
| ] as const; | ||
| /** Listener-removal methods we patch so removals find the scope-bound wrapper. */ | ||
| const REMOVE_LISTENER_METHODS = ['removeListener', 'off', 'removeEventListener'] as const; | ||
|
|
||
| /** Symbol under which the patch map is stashed on a bound emitter. */ | ||
| const SCOPE_BOUND_LISTENERS = Symbol('SentryScopeBoundListeners'); | ||
|
|
||
| /** | ||
| * Minimal structural type for a Node.js-style `EventEmitter` or DOM `EventTarget`. We intentionally | ||
| * avoid importing `node:events` so this stays usable in non-Node environments — objects without any | ||
| * of these methods simply pass through untouched. | ||
| */ | ||
| type EventEmitterLike = Record<string, unknown>; | ||
|
|
||
| // Guards against double-wrapping when a patched `on`/`addListener` delegates to another patched | ||
| // registration method internally. Binding is synchronous, so a module-level flag is safe here. | ||
| let isAddingBoundListener = false; | ||
|
|
||
| /** | ||
| * Binds a scope to the given event emitter, so that any listener added to it runs with that scope | ||
| * (and therefore the active span) active — even if the listener fires later, in a different async | ||
| * context. | ||
| * | ||
| * By default the currently active scope is bound, captured at the time this function is called. | ||
| * Pass an explicit `scope` to bind a different one. | ||
| * | ||
| * This is useful when instrumenting APIs that hand back an event emitter (e.g. a streamed database | ||
| * query) whose `'data'` / `'error'` / `'end'` listeners would otherwise lose the trace context. | ||
| * | ||
| * Works with both Node.js `EventEmitter`s (`on`, `addListener`, ...) and DOM `EventTarget`s | ||
| * (`addEventListener`). Objects exposing none of these methods are returned untouched. | ||
| * | ||
| * The isolation scope is intentionally not captured — it is carried along by the active async | ||
| * context. This mirrors the event-emitter behavior of OpenTelemetry's `ContextManager.bind`. | ||
| */ | ||
| export function bindScopeToEmitter<T extends object>(emitter: T, scope: Scope = getCurrentScope()): T { | ||
| const ee = emitter as EventEmitterLike; | ||
|
|
||
| // Already bound -> nothing to do. | ||
| if (getPatchMap(ee)) { | ||
| return emitter; | ||
| } | ||
|
|
||
| createPatchMap(ee); | ||
|
|
||
| for (const methodName of ADD_LISTENER_METHODS) { | ||
| if (typeof ee[methodName] !== 'function') { | ||
| continue; | ||
| } | ||
| ee[methodName] = patchAddListener(ee, ee[methodName] as BoundListener, scope); | ||
| } | ||
|
|
||
| for (const methodName of REMOVE_LISTENER_METHODS) { | ||
| if (typeof ee[methodName] !== 'function') { | ||
| continue; | ||
| } | ||
| ee[methodName] = patchRemoveListener(ee, ee[methodName] as BoundListener); | ||
| } | ||
|
|
||
| if (typeof ee.removeAllListeners === 'function') { | ||
| ee.removeAllListeners = patchRemoveAllListeners(ee, ee.removeAllListeners as BoundListener); | ||
| } | ||
|
|
||
| return emitter; | ||
| } | ||
|
|
||
| /** Wraps a listener so it runs with the given scope active. */ | ||
| function bindListenerToScope(listener: BoundListener, scope: Scope): BoundListener { | ||
| return function (this: unknown, ...args: unknown[]) { | ||
| return withScope(scope, () => listener.apply(this, args)); | ||
| }; | ||
| } | ||
|
sentry[bot] marked this conversation as resolved.
|
||
|
|
||
| function isBoundListener(listener: unknown): listener is BoundListener { | ||
| return typeof listener === 'function'; | ||
| } | ||
|
|
||
| function patchAddListener(ee: EventEmitterLike, original: BoundListener, scope: Scope): BoundListener { | ||
| return function (this: unknown, ...args: unknown[]) { | ||
| const event = args[0] as string; | ||
| const listener = args[1]; | ||
| // Extra args (e.g. the `options` argument of `addEventListener`) must be forwarded verbatim. | ||
| const rest = args.slice(2); | ||
|
|
||
| // Pass through anything we can't wrap: re-entrant registrations and non-function listeners | ||
| // (e.g. `EventListener` objects passed to `addEventListener`). | ||
| if (isAddingBoundListener || !isBoundListener(listener)) { | ||
| return original.apply(this, args); | ||
| } | ||
|
|
||
| const map = getPatchMap(ee) || createPatchMap(ee); | ||
| let listeners = map[event]; | ||
| if (!listeners) { | ||
| listeners = new WeakMap(); | ||
| map[event] = listeners; | ||
| } | ||
|
|
||
| // Reuse one stable wrapper per listener so repeat registrations are handled correctly by the | ||
| // underlying emitter/target (Node counts duplicates; the DOM dedupes by `(callback, capture)`). | ||
| let boundListener = listeners.get(listener); | ||
| if (!boundListener) { | ||
| boundListener = bindListenerToScope(listener, scope); | ||
| listeners.set(listener, boundListener); | ||
| } | ||
|
|
||
| isAddingBoundListener = true; | ||
| try { | ||
| return original.call(this, event, boundListener, ...rest); | ||
| } finally { | ||
| isAddingBoundListener = false; | ||
| } | ||
| }; | ||
|
cursor[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| function patchRemoveListener(ee: EventEmitterLike, original: BoundListener): BoundListener { | ||
| return function (this: unknown, ...args: unknown[]) { | ||
| const event = args[0] as string; | ||
| const listener = args[1]; | ||
| const rest = args.slice(2); | ||
|
|
||
| const boundListener = isBoundListener(listener) ? getPatchMap(ee)?.[event]?.get(listener) : undefined; | ||
| if (!boundListener) { | ||
| return original.apply(this, args); | ||
| } | ||
| // Pass the same stable wrapper and forward the caller's extra args (e.g. the `capture` option of | ||
| // `removeEventListener`) unchanged, so the emitter/target matches the right registration itself. | ||
| return original.call(this, event, boundListener, ...rest); | ||
| }; | ||
| } | ||
|
|
||
| function patchRemoveAllListeners(ee: EventEmitterLike, original: BoundListener): BoundListener { | ||
| return function (this: unknown, ...args: unknown[]) { | ||
| const map = getPatchMap(ee); | ||
| if (map) { | ||
| if (args.length === 0) { | ||
| // `removeAllListeners()` with no event clears everything -> reset the map. | ||
| createPatchMap(ee); | ||
| } else { | ||
| const event = args[0] as string; | ||
| map[event] = undefined; | ||
| } | ||
| } | ||
| return original.apply(this, args); | ||
| }; | ||
| } | ||
|
|
||
| function createPatchMap(ee: EventEmitterLike): ListenerPatchMap { | ||
| const map = Object.create(null) as ListenerPatchMap; | ||
| (ee as Record<symbol, ListenerPatchMap>)[SCOPE_BOUND_LISTENERS] = map; | ||
| return map; | ||
| } | ||
|
|
||
| function getPatchMap(ee: EventEmitterLike): ListenerPatchMap | undefined { | ||
| return (ee as Record<symbol, ListenerPatchMap | undefined>)[SCOPE_BOUND_LISTENERS]; | ||
| } | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.