Skip to content
Merged
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
Expand Up @@ -12,7 +12,6 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^1.30.1",
"@opentelemetry/core": "^1.30.1",
"@opentelemetry/instrumentation": "^0.57.1",
"@opentelemetry/instrumentation-http": "^0.57.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^1.30.1",
"@opentelemetry/core": "^1.30.1",
"@opentelemetry/instrumentation": "^0.57.2",
"@opentelemetry/instrumentation-http": "^0.57.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
"@sentry/node-core": "latest || *",
"@sentry/opentelemetry": "latest || *",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^1.30.1",
"@opentelemetry/core": "^1.30.1",
"@opentelemetry/instrumentation": "^0.57.1",
"@opentelemetry/instrumentation-http": "^0.57.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^2.6.0",
"@opentelemetry/core": "^2.6.0",
"@opentelemetry/instrumentation": "^0.214.0",
"@opentelemetry/instrumentation-http": "^0.214.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^2.6.0",
"@opentelemetry/core": "^2.6.0",
"@opentelemetry/instrumentation": "^0.214.0",
"@opentelemetry/instrumentation-http": "^0.214.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
"@sentry/node-core": "latest || *",
"@sentry/opentelemetry": "latest || *",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^2.6.0",
"@opentelemetry/core": "^2.6.0",
"@opentelemetry/instrumentation": "^0.214.0",
"@opentelemetry/instrumentation-http": "^0.214.0",
Expand Down
1 change: 0 additions & 1 deletion dev-packages/node-core-integration-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"@nestjs/core": "^11",
"@nestjs/platform-express": "^11",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/context-async-hooks": "^2.6.1",
"@opentelemetry/core": "^2.6.1",
"@opentelemetry/instrumentation": "^0.214.0",
"@opentelemetry/instrumentation-http": "0.214.0",
Expand Down
5 changes: 2 additions & 3 deletions packages/node-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
Unlike the `@sentry/node` SDK, this SDK comes with no OpenTelemetry auto-instrumentation out of the box. It requires the following OpenTelemetry dependencies and supports both v1 and v2 of OpenTelemetry:

- `@opentelemetry/api`
- `@opentelemetry/context-async-hooks`
- `@opentelemetry/core`
- `@opentelemetry/instrumentation`
- `@opentelemetry/resources`
Expand All @@ -23,10 +22,10 @@ Unlike the `@sentry/node` SDK, this SDK comes with no OpenTelemetry auto-instrum
## Installation

```bash
npm install @sentry/node-core @sentry/opentelemetry @opentelemetry/api @opentelemetry/core @opentelemetry/context-async-hooks @opentelemetry/instrumentation @opentelemetry/resources @opentelemetry/sdk-trace-base @opentelemetry/semantic-conventions
npm install @sentry/node-core @sentry/opentelemetry @opentelemetry/api @opentelemetry/core @opentelemetry/instrumentation @opentelemetry/resources @opentelemetry/sdk-trace-base @opentelemetry/semantic-conventions

# Or yarn
yarn add @sentry/node-core @sentry/opentelemetry @opentelemetry/api @opentelemetry/core @opentelemetry/context-async-hooks @opentelemetry/instrumentation @opentelemetry/resources @opentelemetry/sdk-trace-base @opentelemetry/semantic-conventions
yarn add @sentry/node-core @sentry/opentelemetry @opentelemetry/api @opentelemetry/core @opentelemetry/instrumentation @opentelemetry/resources @opentelemetry/sdk-trace-base @opentelemetry/semantic-conventions
```

## Usage
Expand Down
5 changes: 0 additions & 5 deletions packages/node-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
},
"peerDependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^1.30.1 || ^2.1.0",
"@opentelemetry/core": "^1.30.1 || ^2.1.0",
"@opentelemetry/instrumentation": ">=0.57.1 <1",
"@opentelemetry/resources": "^1.30.1 || ^2.1.0",
Expand All @@ -90,9 +89,6 @@
"@opentelemetry/api": {
"optional": true
},
"@opentelemetry/context-async-hooks": {
"optional": true
},
"@opentelemetry/core": {
"optional": true
},
Expand All @@ -119,7 +115,6 @@
},
"devDependencies": {
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/context-async-hooks": "^2.6.1",
"@opentelemetry/core": "^2.6.1",
"@opentelemetry/exporter-trace-otlp-http": "^0.214.0",
"@opentelemetry/instrumentation": "^0.214.0",
Expand Down
10 changes: 3 additions & 7 deletions packages/node-core/src/otel/contextManager.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
import { wrapContextManagerClass } from '@sentry/opentelemetry';
import { SentryAsyncLocalStorageContextManager } from '@sentry/opentelemetry';

/**
* This is a custom ContextManager for OpenTelemetry, which extends the default AsyncLocalStorageContextManager.
* This is a custom ContextManager for OpenTelemetry & Sentry.
* It ensures that we create a new hub per context, so that the OTEL Context & the Sentry Scopes are always in sync.
*
* Note that we currently only support AsyncHooks with this,
* but since this should work for Node 14+ anyhow that should be good enough.
*/
export const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
export const SentryContextManager = SentryAsyncLocalStorageContextManager;
1 change: 0 additions & 1 deletion packages/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/context-async-hooks": "^2.6.1",
"@opentelemetry/core": "^2.6.1",
"@opentelemetry/instrumentation": "^0.214.0",
"@opentelemetry/instrumentation-amqplib": "0.61.0",
Expand Down
9 changes: 3 additions & 6 deletions packages/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ This is how you can use this in your app:
2. Call `setupEventContextTrace(client)`
3. Add `SentrySampler` as sampler
4. Add `SentrySpanProcessor` as span processor
5. Add a context manager wrapped via `wrapContextManagerClass`
5. Register the Sentry context manager (`SentryAsyncLocalStorageContextManager`, or `wrapContextManagerClass` for a custom base)
6. Add `SentryPropagator` as propagator
7. Setup OTEL-powered async context strategy for Sentry via `setOpenTelemetryContextAsyncContextStrategy()`

Expand All @@ -52,14 +52,13 @@ For example, you could set this up as follows:
```js
import * as Sentry from '@sentry/node';
import {
SentryAsyncLocalStorageContextManager,
SentryPropagator,
SentrySampler,
SentrySpanProcessor,
setupEventContextTrace,
wrapContextManagerClass,
setOpenTelemetryContextAsyncContextStrategy,
} from '@sentry/opentelemetry';
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
import { context, propagation, trace } from '@opentelemetry/api';

function setupSentry() {
Expand All @@ -75,12 +74,10 @@ function setupSentry() {
});
provider.addSpanProcessor(new SentrySpanProcessor());

const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);

// Initialize the provider
trace.setGlobalTracerProvider(provider);
propagation.setGlobalPropagator(new SentryPropagator());
context.setGlobalContextManager(new SentryContextManager());
context.setGlobalContextManager(new SentryAsyncLocalStorageContextManager());

setOpenTelemetryContextAsyncContextStrategy();
}
Expand Down
2 changes: 0 additions & 2 deletions packages/opentelemetry/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,12 @@
},
"peerDependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^1.30.1 || ^2.1.0",
"@opentelemetry/core": "^1.30.1 || ^2.1.0",
"@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.1.0",
"@opentelemetry/semantic-conventions": "^1.39.0"
},
"devDependencies": {
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/context-async-hooks": "^2.6.1",
"@opentelemetry/core": "^2.6.1",
"@opentelemetry/sdk-trace-base": "^2.6.1",
"@opentelemetry/semantic-conventions": "^1.40.0"
Expand Down
214 changes: 214 additions & 0 deletions packages/opentelemetry/src/asyncLocalStorageContextManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* NOTICE from the Sentry authors:
* This implementation follows the behavior of OpenTelemetry’s `@opentelemetry/context-async-hooks`
* package, combining logic that upstream splits across:
* - https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-context-async-hooks/src/AbstractAsyncHooksContextManager.ts
* - https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-context-async-hooks/src/AsyncLocalStorageContextManager.ts
* It is a single-class re-implementation for Sentry (not a verbatim copy of those files).
*/

import type { Context, ContextManager } from '@opentelemetry/api';
import { ROOT_CONTEXT } from '@opentelemetry/api';
import { AsyncLocalStorage } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import { SENTRY_SCOPES_CONTEXT_KEY } from './constants';
import type { AsyncLocalStorageLookup } from './contextManager';
import { buildContextWithSentryScopes } from './utils/buildContextWithSentryScopes';
import { setIsSetup } from './utils/setupCheck';

type ListenerFn = (...args: unknown[]) => unknown;

/**
* Per-event map from user listeners to context-bound listeners.
*/
type PatchMap = Record<string, WeakMap<ListenerFn, ListenerFn>>;

const ADD_LISTENER_METHODS = ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener'] as const;

/**
* OpenTelemetry-compatible context manager using Node.js `AsyncLocalStorage`.
* Semantics match `@opentelemetry/context-async-hooks` (function `bind` + `EventEmitter` patching).
*/
export class SentryAsyncLocalStorageContextManager implements ContextManager {
protected readonly _asyncLocalStorage = new AsyncLocalStorage<Context>();

private readonly _kOtListeners = Symbol('OtListeners');
private _wrapped = false;

public constructor() {
setIsSetup('SentryContextManager');
}

public active(): Context {
return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;
}

public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(
context: Context,
fn: F,
thisArg?: ThisParameterType<F>,
...args: A
): ReturnType<F> {
const ctx2 = buildContextWithSentryScopes(context, this.active());
const cb = thisArg == null ? fn : fn.bind(thisArg);
return this._asyncLocalStorage.run(ctx2, cb as never, ...args);
}

public enable(): this {
return this;
}

public disable(): this {
this._asyncLocalStorage.disable();
return this;
}

public bind<T>(context: Context, target: T): T {
if (target instanceof EventEmitter) {
return this._bindEventEmitter(context, target);
}
if (typeof target === 'function') {
return this._bindFunction(context, target as unknown as ListenerFn) as T;
}
return target;
}

/**
* Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
* This is Sentry-specific.
*/
public getAsyncLocalStorageLookup(): AsyncLocalStorageLookup {
return {
asyncLocalStorage: this._asyncLocalStorage,
contextSymbol: SENTRY_SCOPES_CONTEXT_KEY,
};
}

private _bindFunction(context: Context, target: ListenerFn): ListenerFn {
const managerWith = this.with.bind(this);
const contextWrapper = function (this: never, ...args: unknown[]) {
return managerWith(context, () => target.apply(this, args));
};
Object.defineProperty(contextWrapper, 'length', {
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
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.

I am guessing that this is here to handle the express/connect pattern of treating (er, req, res, next) => {} differently from (req, res, next) => {}, but is it worth considering patching toString() as well, since we do that with our wrapped functions?

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.

hmm I basically just copy-pasted this from the original implementation - can you elaborate what exactly you mean? Can't quite find where we do this today?

return contextWrapper;
}

private _bindEventEmitter<T extends EventEmitter>(context: Context, ee: T): T {
if (this._getPatchMap(ee) !== undefined) {
return ee;
}
this._createPatchMap(ee);

for (const methodName of ADD_LISTENER_METHODS) {
if (ee[methodName] === undefined) continue;
ee[methodName] = this._patchAddListener(
ee,
ee[methodName] as unknown as (...args: unknown[]) => unknown,
context,
);
}
if (typeof ee.removeListener === 'function') {
// oxlint-disable-next-line @typescript-eslint/unbound-method -- patched like upstream OTel context manager
ee.removeListener = this._patchRemoveListener(ee, ee.removeListener as (...args: unknown[]) => unknown);
}
if (typeof ee.off === 'function') {
// oxlint-disable-next-line @typescript-eslint/unbound-method
ee.off = this._patchRemoveListener(ee, ee.off as (...args: unknown[]) => unknown);
}
if (typeof ee.removeAllListeners === 'function') {
ee.removeAllListeners = this._patchRemoveAllListeners(
ee,
// oxlint-disable-next-line @typescript-eslint/unbound-method
ee.removeAllListeners as (...args: unknown[]) => unknown,
);
}
return ee;
}

private _patchRemoveListener(ee: EventEmitter, original: (...args: unknown[]) => unknown) {
// oxlint-disable-next-line @typescript-eslint/no-this-alias
const contextManager = this;
return function (this: unknown, event: string, listener: ListenerFn) {
const events = contextManager._getPatchMap(ee)?.[event];
if (events === undefined) {
return original.call(this, event, listener);
}
const patchedListener = events.get(listener);
return original.call(this, event, patchedListener || listener);
};
}

private _patchRemoveAllListeners(ee: EventEmitter, original: (...args: unknown[]) => unknown) {
// oxlint-disable-next-line @typescript-eslint/no-this-alias
const contextManager = this;
return function (this: unknown, event?: string) {
const map = contextManager._getPatchMap(ee);
if (map !== undefined) {
if (arguments.length === 0) {
contextManager._createPatchMap(ee);
} else if (event !== undefined && map[event] !== undefined) {
// oxlint-disable-next-line @typescript-eslint/no-dynamic-delete -- event-keyed listener map
delete map[event];
}
}
return original.apply(this, arguments);
};
}

private _patchAddListener(ee: EventEmitter, original: (...args: unknown[]) => unknown, context: Context) {
// oxlint-disable-next-line @typescript-eslint/no-this-alias
const contextManager = this;
return function (this: unknown, event: string, listener: ListenerFn) {
if (contextManager._wrapped) {
return original.call(this, event, listener);
}
let map = contextManager._getPatchMap(ee);
if (map === undefined) {
map = contextManager._createPatchMap(ee);
}
let listeners = map[event];
if (listeners === undefined) {
listeners = new WeakMap();
map[event] = listeners;
}
const patchedListener = contextManager.bind(context, listener);
listeners.set(listener, patchedListener);

contextManager._wrapped = true;
try {
return original.call(this, event, patchedListener);
} finally {
contextManager._wrapped = false;
}
};
}

private _createPatchMap(ee: EventEmitter): PatchMap {
const map = Object.create(null) as PatchMap;
(ee as unknown as Record<symbol, PatchMap>)[this._kOtListeners] = map;
return map;
}

private _getPatchMap(ee: EventEmitter): PatchMap | undefined {
return (ee as unknown as Record<symbol, PatchMap | undefined>)[this._kOtListeners];
}
}
Loading
Loading