All files / tracker/promise implementation.ts

98.73% Statements 78/79
95.91% Branches 47/49
100% Functions 16/16
98.68% Lines 75/76

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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489      6x 6x 6x                                                                                                                                                                               6x 94x 94x   94x   94x   32x           9x 3x     6x 6x                   212x 212x   212x 169x 169x 63x 63x             149x 110x 110x 110x 110x     7x     39x 39x 39x       149x       149x   149x   113x   113x 36x     113x 113x   113x 113x 105x   113x 106x   113x 113x     36x   36x 22x     36x 36x   36x 36x 35x   36x 36x   36x 36x       149x 106x     149x                                                                                                                                                                                                                                                                                       6x 21x   21x   21x   18x             13x       48x                                                                                                                                                                               6x 48x   48x   48x   76x             10x     4x     5x       121x                          
import type { Writable } from 'type-fest';
 
import type { Logger } from '../../logger/definition.ts';
import { OFF_LOGGER } from '../../logger/off-logger.ts';
import { withPrefix } from '../../logger/prefixed-logger.ts';
import { createEventNotifier } from '../../notifier/implementation.ts';
import type { PromiseHolder, PromiseSettledEvent, PromiseTracker, PromiseVault } from './definition.ts';
 
/**
 * Creates a new promise tracker for monitoring promises and coordinating async operations.
 *
 * The tracker maintains an internal set of unsettled promises and provides centralized waiting, real-time event
 * notifications, and detailed timing metrics. It's designed for scenarios where you need to coordinate multiple
 * unrelated promises or monitor promise performance across different parts of an application.
 *
 * Each tracker instance is independent and manages its own set of promises. The tracker automatically handles cleanup
 * when promises settle and provides comprehensive logging when a logger is configured.
 *
 * @example Basic tracker creation
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 *
 * // Create a tracker without logging
 * const tracker = trackPromises();
 *
 * // Track some operations
 * const result1 = tracker.track(fetchData(), 'fetch-operation');
 * const result2 = tracker.track(() => processData(), 'process-operation');
 *
 * // Wait for all to complete
 * await tracker.wait();
 * ```
 *
 * @example Tracker with logging
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 *
 * const logger = ;
 * const tracker = trackPromises({ logger: new ConsoleLogger('debug') });
 *
 * // All tracking operations will be logged with 'promise' prefix
 * tracker.track(apiCall(), 'api-request');
 * // Logs: "promise: tracking a promise with label api-request"
 * // Later: "promise: promise with label api-request resolved in 150ms"
 * ```
 *
 * @example Server shutdown coordination
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 * import { withTimeout } from 'emitnlog/utils';
 *
 * const shutdownTracker = trackPromises({ logger: serverLogger });
 *
 * // Track cleanup operations
 * shutdownTracker.track(database.close(), 'db-close');
 * shutdownTracker.track(cache.flush(), 'cache-flush');
 * shutdownTracker.track(server.close(), 'server-close');
 *
 * // Wait with timeout for graceful shutdown
 * try {
 *   await withTimeout(shutdownTracker.wait(), 30000);
 *   console.log('Graceful shutdown completed');
 * } catch {
 *   console.log('Shutdown timeout - forcing exit');
 * }
 * ```
 *
 * @example Performance monitoring
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 *
 * const performanceTracker = trackPromises({ logger: metricsLogger });
 *
 * // Monitor performance across different operations
 * performanceTracker.onSettled((event) => {
 *   const status = event.rejected ? 'FAILED' : 'SUCCESS';
 *   metricsCollector.record({ operation: event.label, duration: event.duration, status: status });
 * });
 *
 * // Track various operations
 * performanceTracker.track(userService.authenticate(token), 'auth');
 * performanceTracker.track(dataService.fetchProfile(userId), 'profile');
 * ```
 *
 * @param options Configuration options for the tracker
 * @param options.logger Optional logger for internal tracker operations. If not provided, logging is disabled. The
 *   logger will be prefixed with 'promise' for easy identification.
 * @returns A new PromiseTracker instance
 */
export const trackPromises = (options?: PromiseTrackerOptions): PromiseTracker => {
  const promises = new Set<Promise<unknown>>();
  const logger = withPrefix(options?.logger ?? OFF_LOGGER, 'promise', { fallbackPrefix: 'emitnlog.promise-tracker' });
 
  const onSettledNotifier = createEventNotifier<PromiseSettledEvent>();
 
  return {
    get size() {
      return promises.size;
    },
 
    onSettled: onSettledNotifier.onEvent,
 
    wait: async () => {
      if (!promises.size) {
        return;
      }
 
      logger.d`waiting for ${promises.size} promises to settle`;
      await Promise.allSettled(promises);
    },
 
    track: <T>(
      first: string | Promise<T> | (() => Promise<T>),
      second?: Promise<T> | (() => Promise<T>),
      idMap?: Map<string, Promise<unknown>>,
      keep?: boolean,
      forgetOnRejection?: boolean,
    ): Promise<T> => {
      const label = typeof first === 'string' ? first : undefined;
      const promise = typeof first === 'string' ? (second as Promise<T> | (() => Promise<T>)) : first;
 
      if (label !== undefined && idMap) {
        const existing = idMap.get(label);
        if (existing) {
          logger.d`returning existing promise for label '${label}'`;
          return existing as Promise<T>;
        }
      }
 
      let trackedPromise: Promise<T>;
 
      let start: number;
      if (typeof promise === 'function') {
        logger.d`tracking a promise supplier${label ? ` with label '${label}'` : ''}`;
        start = performance.now();
        try {
          trackedPromise = promise();
        } catch (error) {
          // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
          trackedPromise = Promise.reject(error);
        }
      } else {
        logger.d`tracking a promise${label ? ` with label '${label}'` : ''}`;
        start = performance.now();
        trackedPromise = promise;
      }
 
      // Completely paranoid...
      Iif (!(trackedPromise as { then?: unknown } | undefined)?.then) {
        trackedPromise = Promise.resolve(trackedPromise);
      }
 
      promises.add(trackedPromise);
 
      const finalPromise = trackedPromise.then(
        (result) => {
          promises.delete(trackedPromise);
 
          if (label !== undefined && idMap && !keep) {
            idMap.delete(label);
          }
 
          const duration = performance.now() - start;
          logger.d`promise${label ? ` with label '${label}'` : ''} resolved in ${duration}ms`;
 
          const event: Writable<PromiseSettledEvent> = { duration };
          if (label !== undefined) {
            event.label = label;
          }
          if (result !== undefined) {
            event.result = result;
          }
          onSettledNotifier.notify(event);
          return result;
        },
        (error: unknown) => {
          promises.delete(trackedPromise);
 
          if (label !== undefined && idMap && (!keep || forgetOnRejection)) {
            idMap.delete(label);
          }
 
          const duration = performance.now() - start;
          logger.d`promise${label ? ` with label '${label}'` : ''} rejected in ${duration}ms`;
 
          const event: Writable<PromiseSettledEvent> = { duration, rejected: true };
          if (label !== undefined) {
            event.label = label;
          }
          Eif (error !== undefined) {
            event.result = error;
          }
          onSettledNotifier.notify(event);
          throw error;
        },
      );
 
      if (label !== undefined && idMap) {
        idMap.set(label, finalPromise);
      }
 
      return finalPromise;
    },
  };
};
 
/**
 * Creates a new promise holder for transiently caching ongoing async operations to preventing duplicate execution.
 *
 * The Promise Holder is a Promise Tracker that maintains a cache of ongoing operations identified by unique IDs,
 * automatically clearing the cache when the operation completes. When an operation identified by the same ID is
 * requested multiple times in a short period of time, the holder returns the cached promise instead of executing the
 * operation again. This is particularly useful for expensive operations like API calls, database queries, or file
 * system operations that might be requested simultaneously from different parts of an application.
 *
 * Each holder instance is independent and manages its own operation cache. The cache is automatically cleaned up when
 * operations complete, and comprehensive logging is provided when a logger is configured.
 *
 * **Key differences from PromiseTracker:**
 *
 * - **PromiseTracker**: Coordinates multiple different operations, ideal for shutdown/monitoring scenarios
 * - **PromiseHolder**: Caches ongoing operations by ID to prevent duplicates, ideal for deduplication
 *
 * @example Basic API call caching
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const apiHolder = holdPromises();
 *
 * // Multiple simultaneous requests for the same user
 * const getUserData = (userId: string) => {
 *   return apiHolder.track(`user-${userId}`, () => fetchUserFromAPI(userId));
 * };
 *
 * // All these calls will share the same promise/result
 * const [user1, user2, user3] = await Promise.all([getUserData('123'), getUserData('123'), getUserData('123')]);
 * // Only one API call was made
 * ```
 *
 * @example Database query deduplication with logging
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 * import { ConsoleLogger } from 'emitnlog/logger';
 *
 * const queryHolder = holdPromises({ logger: new ConsoleLogger('debug') });
 *
 * // Cache expensive queries
 * const getProductById = (id: number) => {
 *   return queryHolder.track(`product-${id}`, async () => {
 *     console.log(`Executing query for product ${id}`);
 *     return await db.query('SELECT * FROM products WHERE id = ?', [id]);
 *   });
 * };
 *
 * // Multiple components requesting the same product
 * const product = await getProductById(456);
 * const sameProduct = await getProductById(456); // Uses cached result, no duplicate query
 * ```
 *
 * @example Configuration loading with graceful degradation
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 * import { withTimeout } from 'emitnlog/utils';
 *
 * const configHolder = holdPromises({ logger: appLogger });
 *
 * const loadConfig = (environment: string) => {
 *   return configHolder.track(`config-${environment}`, async () => {
 *     try {
 *       // Try to load from remote first
 *       return await withTimeout(fetchRemoteConfig(environment), 5000);
 *     } catch (error) {
 *       appLogger.w`Failed to load remote config, using local fallback: ${error}`;
 *       return loadLocalConfig(environment);
 *     }
 *   });
 * };
 *
 * // Multiple services requesting config simultaneously
 * const [config1, config2] = await Promise.all([loadConfig('production'), loadConfig('production')]);
 * // Only one config load attempt (remote + fallback if needed)
 * ```
 *
 * @example File processing with monitoring
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const fileHolder = holdPromises({ logger: fileLogger });
 *
 * // Monitor file processing performance
 * fileHolder.onSettled((event) => {
 *   const status = event.rejected ? 'FAILED' : 'SUCCESS';
 *   console.log(`File ${event.label}: ${event.duration}ms - ${status}`);
 * });
 *
 * const processFile = (filename: string) => {
 *   return fileHolder.track(`file-${filename}`, async () => {
 *     const content = await fs.readFile(filename, 'utf8');
 *     return await processLargeFile(content);
 *   });
 * };
 *
 * // Multiple requests for the same file processing
 * const [result1, result2] = await Promise.all([
 *   processFile('data.json'),
 *   processFile('data.json'), // Cached - no duplicate file processing
 * ]);
 * ```
 *
 * @example Cache inspection and conditional logic
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const operationHolder = holdPromises();
 *
 * const performExpensiveOperation = async (id: string) => {
 *   if (operationHolder.has(id)) {
 *     console.log(`Operation ${id} already in progress...`);
 *   } else {
 *     console.log(`Starting operation ${id}...`);
 *   }
 *
 *   return operationHolder.track(id, () => expensiveAsyncOperation());
 * };
 *
 * // Start operation
 * performExpensiveOperation('task-1');
 * // Will show "already in progress" message
 * performExpensiveOperation('task-1');
 * ```
 *
 * @param options Configuration options for the holder
 * @param options.logger Optional logger for internal operations. If not provided, logging is disabled. The logger will
 *   be prefixed with 'promise' for easy identification of holder-related logs.
 * @returns A new PromiseHolder instance
 */
export const holdPromises = (options?: PromiseTrackerOptions): PromiseHolder => {
  const idMap = new Map<string, Promise<unknown>>();
 
  const tracker = trackPromises(options);
 
  return {
    get size() {
      return idMap.size;
    },
 
    onSettled: tracker.onSettled,
 
    wait: tracker.wait,
 
    has: (id: string) => idMap.has(id),
 
    track: <T>(id: string, supplier: () => Promise<T>): Promise<T> =>
      (
        tracker.track as (
          id: string,
          promise: Promise<T> | (() => Promise<T>),
          idMap: Map<string, Promise<unknown>>,
        ) => Promise<T>
      )(id, supplier, idMap),
  };
};
 
/**
 * Creates a new promise vault for persistent caching of expensive operations.
 *
 * The vault maintains a permanent cache of settled promises until explicitly cleared, making it ideal for expensive
 * operations that don't change frequently such as configuration loading, initialization routines, or API calls for
 * static data.
 *
 * Unlike PromiseHolder which automatically clears cached promises when they settle, PromiseVault retains all cached
 * promises indefinitely until manually cleared via `clear()` or `forget()`. This provides long-term caching for
 * operations that should execute only once per application lifecycle.
 *
 * @example Application initialization
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const initVault = vaultPromises({ logger: appLogger });
 *
 * // These operations happen only once, even across multiple calls
 * const initializeDatabase = () => initVault.track('database', () => setupDatabaseConnection());
 * const loadConfiguration = () => initVault.track('config', () => fetchAppConfiguration());
 *
 * // Later calls return cached results instantly
 * const config = await loadConfiguration(); // Uses cached promise
 * ```
 *
 * @example Configuration with refresh capability
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const configVault = vaultPromises();
 *
 * const getConfig = (env: string) => {
 *   return configVault.track(`config-${env}`, () => fetchConfigFromRemote(env));
 * };
 *
 * // Force refresh when needed
 * configVault.forget('config-production');
 * const freshConfig = await getConfig('production'); // New network call
 * ```
 *
 * @example Automatic retry on failure
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * // Vault that automatically clears failed operations for retry
 * const retryVault = vaultPromises({ logger: apiLogger, forgetOnRejection: true });
 *
 * const fetchData = async (id: string) => {
 *   return retryVault.track(`data-${id}`, async () => {
 *     const response = await fetch(`/api/data/${id}`);
 *     if (!response.ok) {
 *       throw new Error(`Failed to fetch data: ${response.status}`);
 *     }
 *     return response.json();
 *   });
 * };
 *
 * // First attempt fails and is automatically removed from cache
 * try {
 *   await fetchData('123');
 * } catch (error) {
 *   console.log('First attempt failed, will retry');
 * }
 *
 * // Second attempt executes fresh (not cached)
 * const data = await fetchData('123'); // New attempt
 * ```
 *
 * @param options Configuration options for the vault
 * @param options.forgetOnRejection When true, failed operations are automatically removed from the cache, allowing
 *   immediate retries. When false (default), failed operations remain cached and must be manually cleared with
 *   `forget()` to enable retries.
 * @param options.logger Optional logger for internal operations. If not provided, logging is disabled. The logger will
 *   be prefixed with 'promise' for easy identification.
 * @returns A new PromiseVault instance
 */
export const vaultPromises = (options?: PromiseVaultOptions): PromiseVault => {
  const idMap = new Map<string, Promise<unknown>>();
 
  const tracker = trackPromises(options);
 
  return {
    get size() {
      return idMap.size;
    },
 
    onSettled: tracker.onSettled,
 
    wait: tracker.wait,
 
    has: (id: string) => idMap.has(id),
 
    clear: () => {
      idMap.clear();
    },
 
    forget: (id: string) => idMap.delete(id),
 
    track: <T>(id: string, supplier: () => Promise<T>, opt?: { forget?: boolean }): Promise<T> =>
      (
        tracker.track as (
          id: string,
          promise: Promise<T> | (() => Promise<T>),
          idMap: Map<string, Promise<unknown>>,
          keep?: boolean,
          forgetOnRejection?: boolean,
        ) => Promise<T>
      )(id, supplier, idMap, !opt?.forget, options?.forgetOnRejection),
  };
};
 
type PromiseTrackerOptions = { readonly logger?: Logger };
type PromiseVaultOptions = { readonly forgetOnRejection?: boolean } & PromiseTrackerOptions;