All files / src/utils/node process-lifecycle.ts

90% Statements 54/60
81.25% Branches 26/32
100% Functions 11/11
90% Lines 54/60

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                                                                                      3x 20x 15x     5x 5x       5x       5x       5x       5x     3x 20x 1x     19x       19x 8x     19x                                                                                                                                                                                                                   3x                     15x 14x 14x   14x   14x 14x 14x   9x 9x 9x     5x 5x   5x 5x                                                                           3x                         10x 10x   10x 10x 7x 7x     10x               10x                         3x           50x 7x       5x 5x 5x       2x 2x 2x             50x 50x 50x 50x                 3x                                            
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
 
import type { Logger } from '../../logger/definition.ts';
import { withLogger } from '../../logger/off-logger.ts';
import { withPrefix } from '../../logger/prefixed-logger.ts';
import type { Closer, SyncClosable } from '../common/closable.ts';
import { asClosable, createCloser, safeClose } from '../common/closable.ts';
import { exhaustiveCheck } from '../common/exhaustive-check.ts';
 
/**
 * Indicates whether the current module is the main entry point of the running process.
 *
 * The first argument `moduleReference` is used to detect if the module invoking this method is the entry point of the
 * process. The possible values are:
 *
 * - `import.meta.url` in ESM
 * - `__filename` or `module.filename` in CommonJS
 * - `undefined` if the application bundles the dependencies (or, at least, emitnlog)
 *
 * If it is not possible to know during development time how the code is distributed, use the following approach to
 * determine the value of the argument:
 *
 * ```ts
 * const moduleReference =
 *   typeof __filename === 'string'
 *     ? __filename
 *     : typeof import.meta === 'object' && import.meta.url
 *       ? import.meta.url
 *       : undefined;
 * ```
 *
 * @example
 *
 * ```ts
 * if (isProcessMain(import.meta.url)) {
 *   void main();
 * }
 * ```
 *
 * @param moduleReference `import.meta.url`, `__filename`, `module.filename`, or `undefined` as described above.
 * @returns `true` when the current file started the process, otherwise `false`.
 */
export const isProcessMain = (moduleReference: string | URL | undefined) => {
  if (testScope.processMain === true) {
    return true;
  }
 
  const scriptPath = toPath(process.argv[1]);
  Iif (!scriptPath) {
    return false;
  }
 
  Iif (toPath(moduleReference) === scriptPath) {
    return true;
  }
 
  Iif (typeof __filename === 'string' && toPath(__filename) === scriptPath) {
    return true;
  }
 
  Iif (typeof import.meta === 'object' && toPath(import.meta.url) === scriptPath) {
    return true;
  }
 
  return false;
};
 
const toPath = (value: string | URL | undefined): string | undefined => {
  if (!value) {
    return undefined;
  }
 
  Iif (typeof value !== 'string') {
    value = value.toString();
  }
 
  if (value.includes('://')) {
    value = fileURLToPath(value);
  }
 
  return resolve(value);
};
 
/**
 * The input object passed to the `main` function of {@link runProcessMain}.
 */
export type ProcessMainInput = {
  /**
   * The start of the process.
   */
  readonly start: Date;
 
  /**
   * A `Closer` instance that can be used to register cleanup operations.
   */
  readonly closer: Closer;
 
  /**
   * A logger instance, either the one passed via the `options` parameter or the `OFF_LOGGER`.
   *
   * This logger is closed when the process ends.
   */
  readonly logger: Logger;
};
 
/**
 * Wraps the main entry point of a NodeJS process with automatic lifecycle management.
 *
 * This helper checks if the current module is the process entry point (via {@link isProcessMain}), and if so, executes
 * the provided async function. Moreover,
 *
 * - If the function "fails" (throws or rejects), the process exits with code `1`.
 * - If a logger is provided via the `options` parameter, it will be used to log the start and end of the process
 *   lifecycle, with the duration of the operation. This logger is closed when the applications exists.
 *
 * If the current module is not the main entry point, this function does nothing. This allows the same module to be
 * safely imported elsewhere without side effects.
 *
 * The specified main method is invoked with an input object with the following properties:
 *
 * - `start`: The start `Date` of the process.
 * - `closer`: A `Closer` instance that can be used to register cleanup operations, immediately before the process exits.
 * - `logger`: A logger instance, either the one passed via the `options` parameter or the `OFF_LOGGER`.
 *
 * The first argument `moduleReference` is used to detect if the module invoking this method is the entry point of the
 * process. The possible values are:
 *
 * - `import.meta.url` in ESM
 * - `__filename` or `module.filename` in CommonJS
 * - `undefined` if the application bundles the dependencies (or, at least, emitnlog)
 *
 * If it is not possible to know during development time how the code is distributed, use the following approach to
 * determine the value of the argument:
 *
 * ```ts
 * const moduleReference =
 *   typeof __filename === 'string'
 *     ? __filename
 *     : typeof import.meta === 'object' && import.meta.url
 *       ? import.meta.url
 *       : undefined;
 * ```
 *
 * @example Simple usage (ESM):
 *
 * ```ts
 * import { runProcessMain } from 'emitnlog/utils';
 *
 * runProcessMain(import.meta.url, async ({ start }) => {
 *   const args = process.argv.slice(2);
 *   console.log(`CLI started at ${start}`);
 *   // ... your application logic
 * });
 * ```
 *
 * @example Simple usage (CommonJS):
 *
 * ```ts
 * import { runProcessMain } from 'emitnlog/utils';
 *
 * runProcessMain(__filename, async ({ start }) => {
 *   // ... your application logic
 * });
 * ```
 *
 * @example With a logger factory for startup logging:
 *
 * ```ts
 * import { createConsoleErrorLogger, withPrefix } from 'emitnlog/logger';
 * import { runProcessMain } from 'emitnlog/utils';
 *
 * runProcessMain(
 *   undefined,
 *   async ({ start, closer, logger }) => {
 *     logger.i`starting HTTP bridge...`;
 *     // ... your application logic
 *   },
 *   { logger: (start) => withPrefix(createConsoleErrorLogger(), `backend-${start.valueOf()}`) },
 * );
 * ```
 *
 * @param moduleReference `import.meta.url`, `__filename`, `module.filename`, or `undefined` as described above.
 * @param main The async function to execute as the process entry point. Receives an input object as argument as
 *   described above.
 * @param options Optional configuration.
 */
export const runProcessMain = (
  moduleReference: string | URL | undefined,
  main: (input: ProcessMainInput) => Promise<void>,
  options?: {
    /**
     * A logger or a factory function that creates one. If a factory is provided, it receives the same start `Date`
     * passed to the `main` method, to enable timestamp-based logger configuration.
     */
    readonly logger?: Logger | ((start: Date) => Logger);
  },
): void => {
  if (isProcessMain(moduleReference)) {
    const start = new Date();
    const logger = withLogger(typeof options?.logger === 'function' ? options.logger(start) : options?.logger);
 
    const closer = createCloser(logger);
 
    logger.i`starting the process main operation at ${start}`;
    void Promise.resolve()
      .then(() => main({ start, closer, logger }))
      .then(async () => {
        const end = new Date();
        logger.i`the process has closed at ${end} after ${end.valueOf() - start.valueOf()}ms`;
        await safeClose(closer);
      })
      .catch(async (error: unknown) => {
        const end = new Date();
        logger.args(error)
          .e`an error occurred and the process has closed at ${end} after ${end.valueOf() - start.valueOf()}ms`;
        await safeClose(closer);
        process.exit(1);
      });
  }
};
 
// Do not add 'exit':
// - Fires on every normal shutdown
// - Runs after the event loop is drained and Node forbids asynchronous work at that point.
export type ProcessExitSignal = 'SIGINT' | 'SIGTERM' | 'disconnect' | 'uncaughtException' | 'unhandledRejection';
 
export type ProcessExitEvent<S extends ProcessExitSignal = ProcessExitSignal> = S extends
  | 'SIGINT'
  | 'SIGTERM'
  | 'disconnect'
  ? { readonly signal: S; readonly error?: undefined }
  : { readonly signal: S; readonly error: unknown };
 
export type ProcessExitListener<S extends ProcessExitSignal = ProcessExitSignal> = (event: ProcessExitEvent<S>) => void;
 
/**
 * Registers a listener that fires once when the process receives one of the `ProcessExitSignal` signals.
 *
 * All process signal handlers are cleared upon exit. Clients may close the returned closable to proactively unregister
 * then.
 *
 * @example
 *
 * ```ts
 * const subscribe = onProcessExit((event) => application.close(event.error), { logger });
 *
 * // if there is no need to monitor the process signals anymore...
 * subscribe.close();
 * ```
 *
 * @param listener Callback invoked with the exit event when the first configured signal fires.
 * @param options
 * @returns A synchronous closable to proactively unregister the listeners.
 */
export const onProcessExit = (
  listener: ProcessExitListener,
  options?: {
    /**
     * Alternative notifier implementing {@link ProcessNotifier} to replace the `process` instance.
     *
     * @default `process`
     */
    readonly notifier?: ProcessNotifier;
 
    readonly logger?: Logger;
  },
): SyncClosable => {
  const logger = withPrefix(withLogger(options?.logger), '', { fallbackPrefix: 'process-exit' });
  const notificationProcess = options?.notifier ?? process;
 
  let closable: SyncClosable | undefined = undefined;
  const closeAndListen: ProcessExitListener = (event) => {
    closable?.close();
    listener(event);
  };
 
  closable = asClosable(
    onProcessExitSignal('SIGINT', closeAndListen, notificationProcess, logger),
    onProcessExitSignal('SIGTERM', closeAndListen, notificationProcess, logger),
    onProcessExitSignal('disconnect', closeAndListen, notificationProcess, logger),
    onProcessExitSignal('uncaughtException', closeAndListen, notificationProcess, logger),
    onProcessExitSignal('unhandledRejection', closeAndListen, notificationProcess, logger),
  );
 
  return closable;
};
 
/**
 * The subset of the NodeJS `process` interface required by {@link onProcessExit}.
 *
 * Provide a custom implementation (for example, a fake emitter in unit tests) via `options.notifier`.
 */
export type ProcessNotifier = {
  once(eventName: ProcessExitSignal, listener: (...args: unknown[]) => void): void;
  off(eventName: ProcessExitSignal, listener: (...args: unknown[]) => void): void;
};
 
const onProcessExitSignal = (
  signal: ProcessExitSignal,
  listener: ProcessExitListener,
  notifier: ProcessNotifier,
  logger: Logger,
): SyncClosable => {
  const handler = (error: unknown) => {
    switch (signal) {
      case 'SIGINT':
      case 'SIGTERM':
      case 'disconnect':
        logger.d`process exited with signal '${signal}'`;
        listener({ signal });
        break;
 
      case 'uncaughtException':
      case 'unhandledRejection':
        logger.args(error).e`process exited with signal '${signal}' and error '${error}'`;
        listener({ signal, error });
        break;
 
      default:
        exhaustiveCheck(signal);
    }
  };
 
  notifier.once(signal, handler);
  return asClosable(() => {
    logger.t`removing process signal handler for '${signal}'`;
    notifier.off(signal, handler);
  });
};
 
const testScope: {
  /**
   * Forces the value to be returned by {@link isProcessMain}, which is used by {@link runProcessMain}.
   */
  processMain?: boolean | undefined;
} = {};
 
/**
 * Internal export to be used on tests only.
 *
 * @example
 *
 * ```ts
 * import inner from '../src/utils/node/process-lifecycle.ts';
 *
 * beforeEach(() => {
 *   inner[Symbol.for('@emitnlog:test')].processMain = true;
 * });
 *
 * afterEach(() => {
 *   inner[Symbol.for('@emitnlog:test')].processMain = undefined;
 * });
 * ```
 *
 * @internal
 */
export default { [Symbol.for('@emitnlog:test')]: testScope } as const;