Enhancement on main readme
[poolifier.git] / src / pools / cluster / fixed.ts
index 0d8021ebf08f0011142a442cbc21175def17db87..4ec81c07bab66b0ebad1cb3eed371ea568989ef0 100644 (file)
@@ -1,5 +1,5 @@
 import { fork, isMaster, setupMaster, Worker } from 'cluster'
-import type { JSONValue, MessageValue } from '../../utility-types'
+import type { MessageValue } from '../../utility-types'
 import type { PoolOptions } from '../abstract-pool'
 import { AbstractPool } from '../abstract-pool'
 
@@ -23,15 +23,15 @@ export interface ClusterPoolOptions extends PoolOptions<Worker> {
  *
  * This pool selects the workers in a round robin fashion.
  *
- * @template Data Type of data sent to the worker.
- * @template Response Type of response of execution.
+ * @template Data Type of data sent to the worker. This can only be serializable data.
+ * @template Response Type of response of execution. This can only be serializable data.
  *
  * @author [Christopher Quadflieg](https://github.com/Shinigami92)
  * @since 2.0.0
  */
 export class FixedClusterPool<
-  Data extends JSONValue = JSONValue,
-  Response extends JSONValue = JSONValue
+  Data = unknown,
+  Response = unknown
 > extends AbstractPool<Worker, Data, Response> {
   /**
    * Constructs a new poolifier fixed cluster pool.
@@ -58,27 +58,22 @@ export class FixedClusterPool<
     return isMaster
   }
 
-  protected destroyWorker (worker: Worker): void {
+  /** @inheritdoc */
+  public destroyWorker (worker: Worker): void {
+    this.sendToWorker(worker, { kill: 1 })
     worker.kill()
-    // FIXME: The tests are currently failing, so these must be changed first
   }
 
   protected sendToWorker (worker: Worker, message: MessageValue<Data>): void {
     worker.send(message)
   }
 
-  protected registerWorkerMessageListener (
-    port: Worker,
-    listener: (message: MessageValue<Response>) => void
+  /** @inheritdoc */
+  public registerWorkerMessageListener<Message extends Data | Response> (
+    worker: Worker,
+    listener: (message: MessageValue<Message>) => void
   ): void {
-    port.on('message', listener)
-  }
-
-  protected unregisterWorkerMessageListener (
-    port: Worker,
-    listener: (message: MessageValue<Response>) => void
-  ): void {
-    port.removeListener('message', listener)
+    worker.on('message', listener)
   }
 
   protected createWorker (): Worker {
@@ -86,8 +81,9 @@ export class FixedClusterPool<
   }
 
   protected afterWorkerSetup (worker: Worker): void {
-    // we will attach a listener for every task,
+    // 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)
+    this.registerWorkerMessageListener(worker, super.workerListener())
   }
 }