feat: add worker kill handler success or failure reporting
[poolifier.git] / src / worker / abstract-worker.ts
index 512a822df295d17ba7578302274c4d87e615e9b9..56a7696f0638fabaaccd7eb4100b7d19e358f0cd 100644 (file)
@@ -326,8 +326,30 @@ export abstract class AbstractWorker<
    */
   protected handleKillMessage (message: MessageValue<Data>): void {
     this.stopCheckActive()
-    this.opts.killHandler?.()
-    this.emitDestroy()
+    if (isAsyncFunction(this.opts.killHandler)) {
+      (this.opts.killHandler?.() as Promise<void>)
+        .then(() => {
+          this.sendToMainWorker({ kill: 'success', workerId: this.id })
+          return null
+        })
+        .catch(() => {
+          this.sendToMainWorker({ kill: 'failure', workerId: this.id })
+        })
+        .finally(() => {
+          this.emitDestroy()
+        })
+        .catch(EMPTY_FUNCTION)
+    } else {
+      try {
+        // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
+        this.opts.killHandler?.() as void
+        this.sendToMainWorker({ kill: 'success', workerId: this.id })
+      } catch (error) {
+        this.sendToMainWorker({ kill: 'failure', workerId: this.id })
+      } finally {
+        this.emitDestroy()
+      }
+    }
   }
 
   /**