All files / tracker/invocation/stack implementation.ts

100% Statements 36/36
70% Branches 7/10
100% Functions 10/10
100% Lines 34/34

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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110  6x 6x                                                   6x 10x 10x   10x 10x   11x 11x       17x 17x     17x     17x 17x 17x                                             6x       61x 61x 61x   60x 60x       72x 72x 72x       88x 88x       66x 66x 1x 1x     65x 65x 65x 65x        
import type { Logger } from '../../../logger/definition.ts';
import { OFF_LOGGER } from '../../../logger/off-logger.ts';
import { withPrefix } from '../../../logger/prefixed-logger.ts';
import type { InvocationKey } from '../definition.ts';
import type { AsyncStackStorage, InvocationStack } from './definition.ts';
 
/**
 * Creates a basic invocation stack that tracks the nesting of invocation keys without support for multithread
 * scenarios.
 *
 * This stack is used to track parent-child relationships between invocations by pushing the `InvocationKey` of each
 * active function call and removing it after completion.
 *
 * This implementation is not thread-safe and is suitable for environments where each thread or event loop has its own
 * isolated context (e.g., browser, single-threaded Node).
 *
 * @example
 *
 * ```ts
 * const stack = createBasicInvocationStack({ 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 synchronous, in-memory invocation stack.
 */
export const createBasicInvocationStack = (options?: { readonly logger: Logger }): InvocationStack => {
  const logger = withPrefix(options?.logger ?? OFF_LOGGER, 'stack.basic', { fallbackPrefix: 'emitnlog.tracker' });
  const stack: InvocationKey[] = [];
 
  logger.d`creating stack`;
  return {
    close: () => {
      logger.d`closing`;
      stack.length = 0;
    },
 
    push: (key: InvocationKey) => {
      logger.t`pushing key '${key.id}'`;
      stack.push(key);
    },
 
    peek: () => stack.at(-1),
 
    pop: () => {
      const key = stack.pop();
      logger.t`${key ? `popped key '${key.id}'` : 'no key to pop'}`;
      return key;
    },
  };
};
 
/**
 * Creates an invocation stack that uses a asynchronous storage to preserve the correct nesting of invocations across
 * async calls, promises, and timers — making it the recommended implementation in Node.js environments.
 *
 * The stack is automatically scoped per async context, so values pushed in one async task will not leak into others.
 *
 * @example
 *
 * ```ts
 * const storage = ...;
 * const stack = createThreadSafeInvocationStack(storage, { logger });
 * const tracker = createInvocationTracker({ stack });
 * const fetchUser = tracker.track('fetchUser', fetchUserFn);
 * await fetchUser('123');
 * ```
 *
 * @returns A thread-safe `InvocationStack` for Node.js environments.
 */
export const createThreadSafeInvocationStack = (
  storage: AsyncStackStorage,
  options?: { readonly logger: Logger },
): InvocationStack => {
  const logger = withPrefix(options?.logger ?? OFF_LOGGER, 'stack.thread-safe', { fallbackPrefix: 'emitnlog.tracker' });
  logger.d`creating stack`;
  return {
    close: () => {
      logger.d`closing`;
      storage.disable();
    },
 
    push: (key: InvocationKey) => {
      logger.t`pushing key '${key.id}'`;
      const current = storage.getStore() ?? [];
      storage.enterWith([...current, key]);
    },
 
    peek: () => {
      const current = storage.getStore();
      return current?.at(-1);
    },
 
    pop: () => {
      const current = storage.getStore();
      if (!current?.length) {
        logger.t`no key to pop`;
        return undefined;
      }
 
      logger.t`popping key '${current.at(-1)?.id}'`;
      const updated = current.slice(0, -1);
      storage.enterWith(updated);
      return current.at(-1);
    },
  };
};