|
| 1 | +import type { Carrier, Hub, RunWithAsyncContextOptions } from '@sentry/core'; |
| 2 | +import { ensureHubOnCarrier, getHubFromCarrier, setAsyncContextStrategy } from '@sentry/core'; |
| 3 | +import { GLOBAL_OBJ, logger } from '@sentry/utils'; |
| 4 | + |
| 5 | +interface AsyncLocalStorage<T> { |
| 6 | + getStore(): T | undefined; |
| 7 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 8 | + run<R, TArgs extends any[]>(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; |
| 9 | +} |
| 10 | + |
| 11 | +// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any |
| 12 | +const MaybeGlobalAsyncLocalStorage = (GLOBAL_OBJ as any).AsyncLocalStorage; |
| 13 | + |
| 14 | +/** |
| 15 | + * Sets the async context strategy to use AsyncLocalStorage which should be available in the edge runtime. |
| 16 | + */ |
| 17 | +export function setAsyncLocalStorageAsyncContextStrategy(): void { |
| 18 | + if (!MaybeGlobalAsyncLocalStorage) { |
| 19 | + __DEBUG_BUILD__ && |
| 20 | + logger.warn( |
| 21 | + "Tried to register AsyncLocalStorage async context strategy in a runtime that doesn't support AsyncLocalStorage.", |
| 22 | + ); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + const asyncStorage: AsyncLocalStorage<Hub> = new MaybeGlobalAsyncLocalStorage(); |
| 27 | + |
| 28 | + function getCurrentHub(): Hub | undefined { |
| 29 | + return asyncStorage.getStore(); |
| 30 | + } |
| 31 | + |
| 32 | + function createNewHub(parent: Hub | undefined): Hub { |
| 33 | + const carrier: Carrier = {}; |
| 34 | + ensureHubOnCarrier(carrier, parent); |
| 35 | + return getHubFromCarrier(carrier); |
| 36 | + } |
| 37 | + |
| 38 | + function runWithAsyncContext<T>(callback: () => T, options: RunWithAsyncContextOptions): T { |
| 39 | + const existingHub = getCurrentHub(); |
| 40 | + |
| 41 | + if (existingHub && options?.reuseExisting) { |
| 42 | + // We're already in an async context, so we don't need to create a new one |
| 43 | + // just call the callback with the current hub |
| 44 | + return callback(); |
| 45 | + } |
| 46 | + |
| 47 | + const newHub = createNewHub(existingHub); |
| 48 | + |
| 49 | + return asyncStorage.run(newHub, () => { |
| 50 | + return callback(); |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext }); |
| 55 | +} |
0 commit comments