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 | 5x 5x 5x 5x 46x 46x 46x 46x 32x 7x 2x 5x 5x 91x 91x 91x 47x 47x 20x 20x 71x 32x 32x 32x 32x 2x 39x 39x 39x 71x 71x 71x 61x 61x 23x 61x 61x 61x 61x 53x 61x 55x 61x 61x 10x 10x 4x 10x 10x 10x 10x 9x 10x 10x 10x 10x 71x 27x 71x 5x 21x 21x 21x 18x 13x 48x | 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 } 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>>, ): Promise<T> => { const label = typeof first === 'string' ? first : undefined; const promise = typeof first === 'string' ? (second as Promise<T> | (() => Promise<T>)) : first; if (label && 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 && idMap) { 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 && idMap) { 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 && idMap) { idMap.set(label, finalPromise); } return finalPromise; }, }; }; /** * Creates a new promise holder for caching async operations and preventing duplicate execution. * * The promise holder maintains a cache of ongoing operations identified by unique IDs. When the same operation is * requested multiple times (same ID), 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:** * * - **PromiseHolder**: Caches operations by ID to prevent duplicates, ideal for deduplication * - **PromiseTracker**: Coordinates multiple different operations, ideal for shutdown/monitoring scenarios * * @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), }; }; type PromiseTrackerOptions = { readonly logger?: Logger }; |