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

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 @@ -136,6 +136,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
182 changes: 182 additions & 0 deletions packages/core/src/tracing/bindScopeToEmitter.ts
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);
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.

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;
}
};
Comment thread
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];
}
1 change: 1 addition & 0 deletions packages/core/src/tracing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export {
startNewTrace,
SUPPRESS_TRACING_KEY,
} from './trace';
export { bindScopeToEmitter } from './bindScopeToEmitter';
export {
getDynamicSamplingContextFromClient,
getDynamicSamplingContextFromSpan,
Expand Down
Loading
Loading