|
| 1 | +import type { Context } from '@opentelemetry/api'; |
| 2 | +import * as api from '@opentelemetry/api'; |
| 3 | +import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; |
| 4 | +import type { Carrier, Hub } from '@sentry/core'; |
| 5 | +import { ensureHubOnCarrier, getCurrentHub, getHubFromCarrier } from '@sentry/core'; |
| 6 | + |
| 7 | +export const OTEL_CONTEXT_HUB_KEY = api.createContextKey('sentry_hub'); |
| 8 | + |
| 9 | +function createNewHub(parent: Hub | undefined): Hub { |
| 10 | + const carrier: Carrier = {}; |
| 11 | + ensureHubOnCarrier(carrier, parent); |
| 12 | + return getHubFromCarrier(carrier); |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * This is a custom ContextManager for OpenTelemetry, which extends the default AsyncLocalStorageContextManager. |
| 17 | + * It ensures that we create a new hub per context, so that the OTEL Context & the Sentry Hub are always in sync. |
| 18 | + * |
| 19 | + * Note that we currently only support AsyncHooks with this, |
| 20 | + * but since this should work for Node 14+ anyhow that should be good enough. |
| 21 | + */ |
| 22 | +export class SentryContextManager extends AsyncLocalStorageContextManager { |
| 23 | + /** |
| 24 | + * Overwrite with() of the original AsyncLocalStorageContextManager |
| 25 | + * to ensure we also create a new hub per context. |
| 26 | + */ |
| 27 | + public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>( |
| 28 | + context: Context, |
| 29 | + fn: F, |
| 30 | + thisArg?: ThisParameterType<F>, |
| 31 | + ...args: A |
| 32 | + ): ReturnType<F> { |
| 33 | + const existingHub = getCurrentHub(); |
| 34 | + const newHub = createNewHub(existingHub); |
| 35 | + |
| 36 | + return super.with(context.setValue(OTEL_CONTEXT_HUB_KEY, newHub), fn, thisArg, ...args); |
| 37 | + } |
| 38 | +} |
0 commit comments