Try to fix release publishing on registry
[poolifier.git] / src / pools / abstract-pool.ts
index c3f293e78bc693fba6aea17e36c880968ee58443..f3a8c1c6c9a7bb0a730b6b3b10dcd9a766b64e5e 100644 (file)
@@ -12,6 +12,11 @@ import {
   WorkerChoiceStrategyContext
 } from './selection-strategies'
 
+/**
+ * Callback invoked if the worker has received a message.
+ */
+export type MessageHandler<Worker> = (this: Worker, m: unknown) => void
+
 /**
  * Callback invoked if the worker raised an error.
  */
@@ -31,6 +36,13 @@ export type ExitHandler<Worker> = (this: Worker, code: number) => void
  * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
  */
 export interface IWorker {
+  /**
+   * Register a listener to the message event.
+   *
+   * @param event `'message'`.
+   * @param handler The message handler.
+   */
+  on(event: 'message', handler: MessageHandler<this>): void
   /**
    * Register a listener to the error event.
    *
@@ -65,6 +77,10 @@ export interface IWorker {
  * Options for a poolifier pool.
  */
 export interface PoolOptions<Worker> {
+  /**
+   * A function that will listen for message event on each worker.
+   */
+  messageHandler?: MessageHandler<Worker>
   /**
    * A function that will listen for error event on each worker.
    */
@@ -84,7 +100,7 @@ export interface PoolOptions<Worker> {
   /**
    * Pool events emission.
    *
-   * Default to true.
+   * @default true
    */
   enableEvents?: boolean
 }
@@ -116,7 +132,7 @@ export abstract class AbstractPool<
   /**
    * The promise map.
    *
-   * - `key`: This is the message ID of each submitted task.
+   * - `key`: This is the message Id of each submitted task.
    * - `value`: An object that contains the worker, the resolve function and the reject function.
    *
    * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
@@ -127,7 +143,7 @@ export abstract class AbstractPool<
   > = new Map<number, PromiseWorkerResponseWrapper<Worker, Response>>()
 
   /**
-   * ID of the next message.
+   * Id of the next message.
    */
   protected nextMessageId: number = 0
 
@@ -173,14 +189,14 @@ export abstract class AbstractPool<
       this,
       () => {
         const workerCreated = this.createAndSetupWorker()
-        this.registerWorkerMessageListener(workerCreated, message => {
+        this.registerWorkerMessageListener(workerCreated, async message => {
           const tasksInProgress = this.tasks.get(workerCreated)
           if (
             isKillBehavior(KillBehaviors.HARD, message.kill) ||
             tasksInProgress === 0
           ) {
             // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
-            void this.destroyWorker(workerCreated)
+            await this.destroyWorker(workerCreated)
           }
         })
         return workerCreated
@@ -262,10 +278,9 @@ export abstract class AbstractPool<
   public execute (data: Data): Promise<Response> {
     // Configure worker to handle message with the specified task
     const worker = this.chooseWorker()
-    this.increaseWorkersTask(worker)
-    this.checkAndEmitBusy()
     const messageId = ++this.nextMessageId
     const res = this.internalExecute(worker, messageId)
+    this.checkAndEmitBusy()
     this.sendToWorker(worker, { data: data || ({} as Data), id: messageId })
     return res
   }
@@ -296,7 +311,7 @@ export abstract class AbstractPool<
   protected abstract isMain (): boolean
 
   /**
-   * Increase the number of tasks that the given workers has applied.
+   * Increase the number of tasks that the given worker has applied.
    *
    * @param worker Worker whose tasks are increased.
    */
@@ -305,7 +320,7 @@ export abstract class AbstractPool<
   }
 
   /**
-   * Decrease the number of tasks that the given workers has applied.
+   * Decrease the number of tasks that the given worker has applied.
    *
    * @param worker Worker whose tasks are decreased.
    */
@@ -314,7 +329,7 @@ export abstract class AbstractPool<
   }
 
   /**
-   * Step the number of tasks that the given workers has applied.
+   * Step the number of tasks that the given worker has applied.
    *
    * @param worker Worker whose tasks are set.
    * @param step Worker number of tasks step.
@@ -376,6 +391,7 @@ export abstract class AbstractPool<
     worker: Worker,
     messageId: number
   ): Promise<Response> {
+    this.increaseWorkersTask(worker)
     return new Promise<Response>((resolve, reject) => {
       this.promiseMap.set(messageId, { resolve, reject, worker })
     })
@@ -403,6 +419,7 @@ export abstract class AbstractPool<
   protected createAndSetupWorker (): Worker {
     const worker: Worker = this.createWorker()
 
+    worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
     worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
     worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
     worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)