All files / tracker/invocation implementation.ts

96.52% Statements 139/144
93.05% Branches 67/72
100% Functions 20/20
96.42% Lines 135/140

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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335      5x 5x 5x 5x 5x                         5x                                                                                                               5x     65x 65x   65x 65x 65x 65x   65x 65x   65x 65x   65x       66x 64x 64x   64x 64x                   3x 3x       70x   70x           70x 1x     69x 74x 74x 74x   74x   74x             74x   74x   74x 74x   74x 12x     74x 53x     74x 15x     74x 74x     74x 69x   69x 15x     69x   69x 12x     69x 53x     69x 15x     69x 69x     74x 5x   5x 1x     5x   5x       5x       5x       5x 5x     74x 74x     74x 74x 74x   4x 4x 4x 4x   4x     70x 54x 54x 54x 54x   54x     16x   15x 15x 15x 15x   15x     1x 1x 1x 1x   1x         69x 69x       65x     5x   5x 73x             5x 70x   5x 74x 10x     74x 9x     74x 59x     15x 15x   15x 35x 35x 31x 31x     35x 33x 33x       15x 15x 25x     5x   5x 5x   5x 10x 5x 5x 54x 54x 54x              
import type { Writable } from 'type-fest';
 
import type { Logger } from '../../logger/definition.ts';
import { OFF_LOGGER } from '../../logger/off-logger.ts';
import { appendPrefix, withPrefix } from '../../logger/prefixed-logger.ts';
import { createEventNotifier } from '../../notifier/implementation.ts';
import { generateRandomString } from '../../utils/common/generate-random-string.ts';
import { isNotNullable } from '../../utils/common/is-not-nullable.ts';
import type {
  CompletedStage,
  ErroredStage,
  Invocation,
  InvocationAtStage,
  InvocationKey,
  InvocationTracker,
  InvocationTrackerOptions,
  Tag,
  Tags,
} from './definition.ts';
import type { InvocationStack } from './stack/definition.ts';
import { createBasicInvocationStack, createThreadSafeInvocationStack } from './stack/implementation.ts';
 
/**
 * Creates an invocation tracker that monitors and notifies about operation invocations.
 *
 * Each tracker assigns a unique tracker ID and supports multiple listeners for invocations:
 *
 * - `onInvoked`: all invocations regardless of the stage
 * - `onStarted`: before invocation
 * - `onCompleted`: after successful invocation (sync or async)
 * - `onErrored`: after an error is thrown or a promise is rejected
 *
 * Tags can be used to provide contextual metadata for invocations and can be specified in two places:
 *
 * - Globally, when creating the tracker: `createInvocationTracker({ tags })`
 * - Per-invocation, when calling `track`: `tracker.track('op', fn, { tags })`
 *
 * Tags can be defined either as:
 *
 * - An array: `[{ name: 'foo', value: 'bar' }]`
 * - A record: `{ foo: 'bar' }`
 *
 * During invocation, the two sources of tags are merged. If the same tag name appears in both sources, their values are
 * de-duplicated. The merged result is sorted by name and value and stored as an array.
 *
 * Although the original tag sources (arrays, records, or tag objects) can be mutated during execution, the merged tags
 * are captured and fixed at invocation start. This ensures consistency across the `started`, `completed`, and `errored`
 * stages of a single invocation.
 *
 * @example
 *
 * ```ts
 * const tracker = createInvocationTracker({ tags: { service: 'auth' } });
 *
 * tracker.onCompleted((invocation) => {
 *   console.log(`${invocation.key.operation} completed in ${invocation.duration}ms`);
 *
 *   // [{ name: 'feature', value: 'signup' }, { name: 'service', value: 'auth' }]
 *   console.log(invocation.tags);
 * });
 *
 * const wrapped = tracker.track('saveUser', saveUserFn, { tags: [{ name: 'feature', value: 'signup' }] });
 * await wrapped({ name: 'Jane' });
 * ```
 *
 * @example
 *
 * ```ts
 * // Creates a tracker for the operations 'fetchUser' and 'fetchAccount'.
 * const tracker = createInvocationTracker<'fetchUser', 'fetchAccount'>();
 * const fetchUser = tracker.track('fetchUser', fetchUserFn);
 * const fetchAccount = tracker.track('fetchAccount', fetchUserFn);
 * ```
 *
 * @param options Optional configuration for the tracker. @returns A new `InvocationTracker` instance.
 */
export const createInvocationTracker = <TOperation extends string = string>(
  options?: InvocationTrackerOptions,
): InvocationTracker<TOperation> => {
  const trackerId = generateRandomString();
  const logger = options?.logger ?? OFF_LOGGER;
 
  const invokedNotifier = createEventNotifier<Invocation<TOperation>>();
  const startedNotifier = createEventNotifier<InvocationAtStage<'started', TOperation>>();
  const completedNotifier = createEventNotifier<InvocationAtStage<'completed', TOperation>>();
  const erroredNotifier = createEventNotifier<InvocationAtStage<'errored', TOperation>>();
 
  const trackerLogger = withPrefix(logger, '', { fallbackPrefix: `emitnlog.invocation-tracker.${trackerId}` });
  const stack = options?.stack ?? stackFactory({ logger: trackerLogger });
 
  let closed = false;
  let counter = -1;
 
  const tracker: InvocationTracker<TOperation> = {
    id: trackerId,
 
    close: () => {
      if (!closed) {
        trackerLogger.d`closing tracker`;
        closed = true;
 
        invokedNotifier.close();
        stack.close();
      }
    },
 
    onInvoked: invokedNotifier.onEvent,
    onStarted: startedNotifier.onEvent,
    onCompleted: completedNotifier.onEvent,
    onErrored: erroredNotifier.onEvent,
 
    isTracked: (value) => {
      const id = toTrackedTrackerId(value);
      return id === trackerId ? 'this' : id ? 'other' : false;
    },
 
    track: (operation, fn, opt) => {
      const trackedLogger = appendPrefix(trackerLogger, `operation.${operation}`);
 
      Iif (closed) {
        trackedLogger.d`the tracker is closed`;
        return fn;
      }
 
      // tags do not affect this by design.
      if (toTrackedTrackerId(fn) === trackerId) {
        return fn;
      }
 
      const trackedFn = (...args: Parameters<typeof fn>) => {
        const argsLength = (args as unknown[]).length;
        const index = ++counter;
        const invocationLogger = appendPrefix(trackedLogger, String(index));
 
        const parentKey = stack.peek();
 
        const key: InvocationKey<TOperation> = {
          id: `${trackerId}.${operation}.${index}`,
          trackerId,
          operation,
          index,
        };
 
        stack.push(key);
 
        const mergedTags = mergeTags(options?.tags, opt?.tags);
 
        const notifyStarted = () => {
          const invocation: Writable<InvocationAtStage<'started', TOperation>> = { key, stage: { type: 'started' } };
 
          if (parentKey) {
            invocation.parentKey = parentKey;
          }
 
          if (argsLength) {
            invocation.args = args;
          }
 
          if (mergedTags?.length) {
            invocation.tags = mergedTags;
          }
 
          invokedNotifier.notify(invocation);
          startedNotifier.notify(invocation);
        };
 
        const notifyCompleted = (duration: number, promiseLike: boolean, result: unknown) => {
          const stage: Writable<CompletedStage> = { type: 'completed', duration, result };
 
          if (promiseLike) {
            stage.promiseLike = true;
          }
 
          const invocation: Writable<InvocationAtStage<'completed', TOperation>> = { key, stage };
 
          if (parentKey) {
            invocation.parentKey = parentKey;
          }
 
          if (argsLength) {
            invocation.args = args;
          }
 
          if (mergedTags?.length) {
            invocation.tags = mergedTags;
          }
 
          invokedNotifier.notify(invocation);
          completedNotifier.notify(invocation);
        };
 
        const notifyErrored = (duration: number, promiseLike: boolean, error: unknown) => {
          const stage: Writable<ErroredStage> = { type: 'errored', duration, error };
 
          if (promiseLike) {
            stage.promiseLike = true;
          }
 
          const invocation: Writable<InvocationAtStage<'errored', TOperation>> = { key, stage };
 
          Iif (parentKey) {
            invocation.parentKey = parentKey;
          }
 
          Iif (argsLength) {
            invocation.args = args;
          }
 
          Iif (mergedTags?.length) {
            invocation.tags = mergedTags;
          }
 
          invokedNotifier.notify(invocation);
          erroredNotifier.notify(invocation);
        };
 
        invocationLogger.args(args).i`starting with ${argsLength} args`;
        notifyStarted();
 
        let result: unknown;
        const start = performance.now();
        try {
          result = fn(...args);
        } catch (error) {
          const duration = performance.now() - start;
          stack.pop();
          invocationLogger.args(error).e`an error was thrown '${error}'`;
          notifyErrored(duration, false, error);
 
          throw error;
        }
 
        if (!isPromiseLike(result)) {
          const duration = performance.now() - start;
          stack.pop();
          invocationLogger.i`completed`;
          notifyCompleted(duration, false, result);
 
          return result;
        }
 
        return result.then(
          (r) => {
            const duration = performance.now() - start;
            stack.pop();
            invocationLogger.i`resolved`;
            notifyCompleted(duration, true, r);
 
            return r;
          },
          (error: unknown) => {
            const duration = performance.now() - start;
            stack.pop();
            invocationLogger.args(error).e`rejected`;
            notifyErrored(duration, true, error);
 
            throw error;
          },
        );
      };
 
      trackedFn[trackedSymbol] = trackerId;
      return trackedFn as unknown as typeof fn;
    },
  };
 
  return tracker;
};
 
const trackedSymbol = Symbol.for('@emitnlog/tracker/tracked');
 
const toTrackedTrackerId = (value: unknown): string | undefined =>
  isNotNullable(value) &&
  typeof value === 'function' &&
  trackedSymbol in value &&
  typeof value[trackedSymbol] === 'string'
    ? value[trackedSymbol]
    : undefined;
 
const isPromiseLike = <T>(value: unknown): value is PromiseLike<T> =>
  isNotNullable(value) && typeof value === 'object' && 'then' in value && typeof value.then === 'function';
 
const mergeTags = (tags1: Tags | undefined, tags2: Tags | undefined): readonly Tag[] | undefined => {
  if (tags1 && typeof tags1 === 'object' && !Array.isArray(tags1)) {
    tags1 = Object.keys(tags1).map((name) => ({ name, value: (tags1 as Record<string, Tag['value']>)[name] }));
  }
 
  if (tags2 && typeof tags2 === 'object' && !Array.isArray(tags2)) {
    tags2 = Object.keys(tags2).map((name) => ({ name, value: (tags2 as Record<string, Tag['value']>)[name] }));
  }
 
  if (!tags1?.length && !tags2?.length) {
    return undefined;
  }
 
  const mergedTags: Tag[] = [];
  const map = new Map<string, Set<Tag['value']>>();
 
  const addTag = (tag: Tag): void => {
    let values = map.get(tag.name);
    if (!values) {
      values = new Set();
      map.set(tag.name, values);
    }
 
    if (!values.has(tag.value)) {
      values.add(tag.value);
      mergedTags.push(tag);
    }
  };
 
  tags1?.forEach(addTag);
  tags2?.forEach(addTag);
  return mergedTags.sort((a, b) => a.name.localeCompare(b.name) || String(a.value).localeCompare(String(b.value)));
};
 
let stackFactory: (options: { readonly logger: Logger }) => InvocationStack = createBasicInvocationStack;
 
void (async () => {
  try {
    // eslint-disable-next-line no-undef
    Eif (typeof process !== 'undefined' && typeof process.versions.node === 'string') {
      const { AsyncLocalStorage } = await import('node:async_hooks');
      const storage = new AsyncLocalStorage<InvocationKey[]>();
      stackFactory = (options) => {
        options.logger.d`creating a thread-safe stack using node:async_hooks`;
        const stack = createThreadSafeInvocationStack(storage, options);
        return stack;
      };
    }
  } catch {
    // Ignore
  }
})();