autotel
Version:
Write Once, Observe Anywhere
72 lines (70 loc) • 2.03 kB
JavaScript
const require_chunk = require('./chunk-C_NdSu1c.cjs');
let node_async_hooks = require("node:async_hooks");
node_async_hooks = require_chunk.__toESM(node_async_hooks, 1);
//#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 node_async_hooks.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
Object.defineProperty(exports, 'getOperationContext', {
enumerable: true,
get: function () {
return getOperationContext;
}
});
Object.defineProperty(exports, 'runInOperationContext', {
enumerable: true,
get: function () {
return runInOperationContext;
}
});
//# sourceMappingURL=operation-context-D6LDf4W_.cjs.map