feat: restart worker in case of uncaught error
[poolifier.git] / src / pools / cluster / fixed.ts
index 00205449a2f3fc0bee0feb54b7d41bea56b8ad62..89cab8ef0eba31aacbbde03fa4de24d68d9530d6 100644 (file)
@@ -1,8 +1,13 @@
-import { fork, isMaster, setupMaster, Worker } from 'cluster'
+import type { ClusterSettings, Worker } from 'node:cluster'
+import cluster from 'node:cluster'
 import type { MessageValue } from '../../utility-types'
-import type { PoolOptions } from '../abstract-pool'
 import { AbstractPool } from '../abstract-pool'
+import type { PoolOptions } from '../pool'
+import { PoolType } from '../pool'
 
+/**
+ * Options for a poolifier cluster pool.
+ */
 export interface ClusterPoolOptions extends PoolOptions<Worker> {
   /**
    * Key/value pairs to add to worker process environment.
@@ -11,74 +16,102 @@ export interface ClusterPoolOptions extends PoolOptions<Worker> {
    */
   // eslint-disable-next-line @typescript-eslint/no-explicit-any
   env?: any
+  /**
+   * Cluster settings.
+   *
+   * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
+   */
+  settings?: ClusterSettings
 }
 
 /**
- * A cluster pool with a static number of workers, is possible to execute tasks in sync or async mode as you prefer.
+ * A cluster pool with a fixed number of workers.
+ *
+ * It is possible to perform tasks in sync or asynchronous mode as you prefer.
  *
- * This pool will select the worker in a round robin fashion.
+ * This pool selects the workers in a round robin fashion.
  *
+ * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
+ * @typeParam Response - Type of execution response. This can only be serializable data.
  * @author [Christopher Quadflieg](https://github.com/Shinigami92)
  * @since 2.0.0
  */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export class FixedClusterPool<Data = any, Response = any> extends AbstractPool<
-  Worker,
-  Data,
-  Response
-> {
+export class FixedClusterPool<
+  Data = unknown,
+  Response = unknown
+> extends AbstractPool<Worker, Data, Response> {
   /**
-   * @param numWorkers Number of workers for this pool.
-   * @param filePath A file path with implementation of `ClusterWorker` class, relative path is fine.
-   * @param opts An object with possible options for example `errorHandler`, `onlineHandler`. Default: `{ maxTasks: 1000 }`
+   * Constructs a new poolifier fixed cluster pool.
+   *
+   * @param numberOfWorkers - Number of workers for this pool.
+   * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
+   * @param opts - Options for this fixed cluster pool.
    */
   public constructor (
-    numWorkers: number,
+    numberOfWorkers: number,
     filePath: string,
-    public readonly opts: ClusterPoolOptions = { maxTasks: 1000 }
+    public readonly opts: ClusterPoolOptions = {}
   ) {
-    super(numWorkers, filePath, opts)
+    super(numberOfWorkers, filePath, opts)
   }
 
+  /** @inheritDoc */
   protected setupHook (): void {
-    setupMaster({
-      exec: this.filePath
-    })
+    cluster.setupPrimary({ ...this.opts.settings, exec: this.filePath })
   }
 
+  /** @inheritDoc */
   protected isMain (): boolean {
-    return isMaster
+    return cluster.isPrimary
   }
 
+  /** @inheritDoc */
   protected destroyWorker (worker: Worker): void {
+    this.sendToWorker(worker, { kill: 1 })
     worker.kill()
   }
 
+  /** @inheritDoc */
   protected sendToWorker (worker: Worker, message: MessageValue<Data>): void {
     worker.send(message)
   }
 
-  protected registerWorkerMessageListener (
-    port: Worker,
-    listener: (message: MessageValue<Response>) => void
+  /** @inheritDoc */
+  protected registerWorkerMessageListener<Message extends Data | Response>(
+    worker: Worker,
+    listener: (message: MessageValue<Message>) => void
   ): void {
-    port.on('message', listener)
+    worker.on('message', listener)
   }
 
-  protected unregisterWorkerMessageListener (
-    port: Worker,
-    listener: (message: MessageValue<Response>) => void
-  ): void {
-    port.removeListener('message', listener)
+  /** @inheritDoc */
+  protected createWorker (): Worker {
+    return cluster.fork(this.opts.env)
+  }
+
+  /** @inheritDoc */
+  protected afterWorkerSetup (worker: Worker): void {
+    // Listen to worker messages.
+    this.registerWorkerMessageListener(worker, super.workerListener())
+  }
+
+  /** @inheritDoc */
+  public get type (): PoolType {
+    return PoolType.FIXED
+  }
+
+  /** @inheritDoc */
+  public get size (): number {
+    return this.numberOfWorkers
   }
 
-  protected newWorker (): Worker {
-    return fork(this.opts.env)
+  /** @inheritDoc */
+  protected get full (): boolean {
+    return this.workerNodes.length >= this.numberOfWorkers
   }
 
-  protected afterNewWorkerPushed (worker: Worker): void {
-    // we will attach a listener for every task,
-    // when task is completed the listener will be removed but to avoid warnings we are increasing the max listeners size
-    worker.setMaxListeners(this.opts.maxTasks ?? 1000)
+  /** @inheritDoc */
+  protected get busy (): boolean {
+    return this.internalBusy()
   }
 }