UNPKG

autotel

Version:
59 lines (57 loc) 1.7 kB
import * as nodeAsyncHooks from "node:async_hooks"; //#region src/operation-context.ts /** * Operation context tracking using AsyncLocalStorage * * This module provides a way to track operation names across async boundaries * so they can be automatically captured in events events. * * We cannot read span attributes from OpenTelemetry's API (it's write-only), * so we maintain our own async context storage. */ /** * AsyncLocalStorage instance for tracking operation context */ const operationStorage = new nodeAsyncHooks.AsyncLocalStorage(); /** * Get the current operation context (if any) * * @returns The current operation context, or undefined if not in an operation * * @example * ```typescript * const ctx = getOperationContext(); * if (ctx) { * console.log('Current operation:', ctx.name); * } * ``` */ function getOperationContext() { return operationStorage.getStore(); } /** * Run a function within an operation context * * This sets the operation name for the duration of the function execution, * including all async operations spawned from it. * * @param name - The operation name to set * @param fn - The function to execute within the context * @returns The result of the function * * @example * ```typescript * const result = await runInOperationContext('user.create', async () => { * // Any events.trackEvent() calls here will automatically capture * // 'operation.name': 'user.create' * await createUser(); * return 'success'; * }); * ``` */ function runInOperationContext(name, fn) { return operationStorage.run({ name }, fn); } //#endregion export { runInOperationContext as n, getOperationContext as t }; //# sourceMappingURL=operation-context-CKBoA4Qy.js.map