Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
});
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);
Comment on lines +7 to +8

@Lms24 Lms24 Jun 19, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

q: how does this interop with parentSpanIsAlwaysRootSpan in the browser SDK? I'd guess that unless said option is explicitly disabled, it would not attach an inner child span of child-bound to child-bound but to parent, correct? This is a bit ... weird IMHO but I think we can still justify it with the absence of async context in browser.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yeah, this does not affect this at all, it just makes sure that the active scope is the same in everything emitted by the emitter - what is picked as span will behave the same as if you'd wrap the emitter manually with withScope(scope) :)


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();
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);
});
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);
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);
});
1 change: 1 addition & 0 deletions packages/astro/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export {
spotlightIntegration,
startInactiveSpan,
startNewTrace,
bindScopeToEmitter,
suppressTracing,
startSession,
startSpan,
Expand Down
1 change: 1 addition & 0 deletions packages/aws-serverless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export {
startInactiveSpan,
startSpanManual,
startNewTrace,
bindScopeToEmitter,
suppressTracing,
withActiveSpan,
getRootSpan,
Expand Down
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export {
startSpanManual,
withActiveSpan,
startNewTrace,
bindScopeToEmitter,
getSpanDescendants,
setMeasurement,
getSpanStatusFromHttpCode,
Expand Down
1 change: 1 addition & 0 deletions packages/bun/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export {
startInactiveSpan,
startSpanManual,
startNewTrace,
bindScopeToEmitter,
suppressTracing,
withActiveSpan,
getRootSpan,
Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export {
startInactiveSpan,
startSpanManual,
startNewTrace,
bindScopeToEmitter,
suppressTracing,
withActiveSpan,
getSpanDescendants,
Expand Down
205 changes: 205 additions & 0 deletions packages/core/src/tracing/bindScopeToEmitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
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 = Map<string, WeakMap<BoundListener, BoundListener>>;

// 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>;

// Tracks the scope-bound wrapper currently being registered. Node's `once`/`prependOnceListener`
// synchronously re-enter `on`/`prependListener`, passing an internal "once wrapper" whose `.listener`
// is our wrapper; that re-entry must not be wrapped again. We scope the guard to that exact wrapper
// rather than using a blanket flag for the whole registration, so unrelated listeners added in the same
// synchronous window — e.g. from a Node `newListener` handler, or on another bound emitter — are still
// wrapped and keep their scope. Binding is synchronous, so a module-level value (with save/restore for
// nesting) is safe here.
let registeringWrapper: BoundListener | undefined;

// True when `listener` is the wrapper we're mid-registering, or a Node once-wrapper around it (Node sets
// `.listener` on the once-wrapper to the function we passed). These are the only re-entrant adds to skip.
function isReentrantWrapperRegistration(listener: BoundListener): boolean {
return (
registeringWrapper !== undefined &&
(listener === registeringWrapper || (listener as { listener?: unknown }).listener === registeringWrapper)
);
}

/**
* 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;
Comment on lines +77 to +78

@Lms24 Lms24 Jun 19, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m/q: i guess there's no good way to further narrow the type than object? No strong opinions since EventEmitterLike is typed defensively anyway, just wondering if we can/should be a bit more specific

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

not sure if it is worth it, could lead to weird ts issues 🤔 this should work, and I guess there is no specific shape an event emitter must have that we could type here?


// Already bound -> nothing to do.
if (getPatchMap(ee)) {
return emitter;
}

createPatchMap(ee);
Comment thread
cursor[bot] marked this conversation as resolved.

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));
};
Comment thread
sentry[bot] marked this conversation as resolved.
}
Comment thread
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 what we must not wrap: non-function listeners (e.g. `EventListener` objects passed to
// `addEventListener`) and the re-entrant once-wrapper registration. Anything else is wrapped, even
// when added synchronously mid-registration.
if (!isBoundListener(listener) || isReentrantWrapperRegistration(listener)) {
return original.apply(this, args);
}

const map = getPatchMap(ee) || createPatchMap(ee);
let listeners = map.get(event);
if (!listeners) {
listeners = new WeakMap();
map.set(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);
}

const previous = registeringWrapper;
registeringWrapper = boundListener;
try {
return original.call(this, event, boundListener, ...rest);
} finally {
registeringWrapper = previous;
}
};
Comment thread
cursor[bot] marked this conversation as resolved.
}

// Unlike `patchRemoveAllListeners`, this intentionally leaves the map entry in place: Node counts
// duplicate registrations, so the same wrapper may still be registered after removing one instance,
// and later `removeListener` calls need the mapping to find it. The entry is in a `WeakMap` keyed by
// the user listener, so it is GC'd once the user drops their reference — no manual cleanup needed.
function patchRemoveListener(ee: EventEmitterLike, original: BoundListener): BoundListener {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m: In patchRemoveAllListeners we are removing the event from the map. In this function we keep the map as is, is this difference intended?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added comments to explain this, here is the AI summary of why this is expected:

es, that difference is intentional and load-bearing — it's not an oversight.

The map is Map<event, WeakMap<userListener, boundWrapper>> (outer keyed by event-name string, inner keyed weakly by the user's listener).

Why patchRemoveListener must keep the entry: the whole design reuses one stable wrapper per listener (patchAddListener, lines 125–131), and Node's EventEmitter allows and counts
duplicate registrations. So a single user listener can be registered multiple times, all sharing the same wrapper B:

ee.on('data', fn); // registers wrapper B (map[data][fn] = B)
ee.on('data', fn); // registers B again — Node now has 2 copies of B
ee.removeListener('data', fn); // removes ONE copy of B

If removeListener deleted map[data][fn] here, the second still-registered copy of B would become orphaned: the next removeListener('data', fn) would no longer find B in the map, fall
through to original.apply(this, args) with the raw fn (line 149–150), and fail to match/remove the wrapper. So the mapping has to survive a single removal because other registrations of
the same wrapper may still be live.

Why patchRemoveAllListeners can delete it: removeAllListeners(event) tears down every listener for that event in one shot, so no registration referencing those wrappers remains. The map
entry is then unambiguously stale, and deleting it is safe — and a genuine cleanup, because the outer map is a plain Map keyed by event-name strings, which would otherwise accumulate
those keys forever. (The no-arg case resets the whole map, lines 162–164.)

Why leaving stale inner entries after removeListener isn't a leak: the inner structure is a WeakMap keyed by the user's listener, so once the user drops their reference to fn, the entry
is GC'd on its own. There's nothing to manually clean up there, and reusing the same wrapper if fn is re-added later is actually desirable (it preserves DOM EventTarget's (type,
callback, capture) dedup, per the comment on lines 6–14).

So: keep-on-single-remove (correctness, due to possible duplicates) vs. delete-on-remove-all (safe cleanup of the strong outer map) is the right asymmetry.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok if there is a good reason for it (and now it's also documented). It's fine. Just wanted to make sure it's not an oversight.

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)?.get(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);
};
}

// Safe to drop map entries here (unlike `patchRemoveListener`): this removes *every* listener for the
// event at once, so no registration referencing those wrappers remains. It also reclaims keys from the
// strong outer `Map` (keyed by event-name strings), which would otherwise accumulate indefinitely.
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.delete(event);
}
}
return original.apply(this, args);
};
}

function createPatchMap(ee: EventEmitterLike): ListenerPatchMap {
const map: ListenerPatchMap = new Map();
(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];
}
Loading
Loading