All files / tracker/node/invocation async-local-storage-stack.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 1/1
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 271x         1x                                 1x 7x 7x    
import { AsyncLocalStorage } from 'node:async_hooks';
 
import type { Logger } from '../../../logger/definition.ts';
import type { InvocationKey } from '../../invocation/definition.ts';
import type { InvocationStack } from '../../invocation/stack/definition.ts';
import { createThreadSafeInvocationStack } from '../../invocation/stack/implementation.ts';
 
/**
 * Creates a thread-safe invocation stack backed by NodeJS's `AsyncLocalStorage`.
 *
 * @example
 *
 * ```ts
 * const stack = createAsyncLocalStorageInvocationStack({ logger });
 * const tracker = createInvocationTracker({ stack });
 * const fetchUser = tracker.track('fetchUser', fetchUserFn);
 * await fetchUser('123');
 * ```
 *
 * @param options - The options to use to create the stack.
 * @returns A thread-safe `InvocationStack` for Node.js environments.
 */
export const createAsyncLocalStorageInvocationStack = (options?: { readonly logger: Logger }): InvocationStack => {
  const asyncLocal = new AsyncLocalStorage<InvocationKey[]>();
  return createThreadSafeInvocationStack(asyncLocal, options);
};