JSONValue can not be used by custom defined interfaces (#201)
[poolifier.git] / src / pools / thread / fixed.ts
index bfd6f016d0d4f08525d1c19435d4a138e2a404a0..a61c10b2346c8a44c4094605dfe6aa25787b8f09 100644 (file)
@@ -1,5 +1,5 @@
 import { isMainThread, MessageChannel, SHARE_ENV, Worker } from 'worker_threads'
-import type { Draft, JSONValue, MessageValue } from '../../utility-types'
+import type { Draft, MessageValue } from '../../utility-types'
 import type { PoolOptions } from '../abstract-pool'
 import { AbstractPool } from '../abstract-pool'
 
@@ -15,15 +15,15 @@ export type ThreadWorkerWithMessageChannel = Worker & Draft<MessageChannel>
  *
  * This pool selects the threads 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 [Alessandro Pio Ardizio](https://github.com/pioardi)
  * @since 0.0.1
  */
 export class FixedThreadPool<
-  Data extends JSONValue = JSONValue,
-  Response extends JSONValue = JSONValue
+  Data = unknown,
+  Response = unknown
 > extends AbstractPool<ThreadWorkerWithMessageChannel, Data, Response> {
   /**
    * Constructs a new poolifier fixed thread pool.
@@ -47,6 +47,7 @@ export class FixedThreadPool<
   protected async destroyWorker (
     worker: ThreadWorkerWithMessageChannel
   ): Promise<void> {
+    this.sendToWorker(worker, { kill: 1 })
     await worker.terminate()
   }
 
@@ -57,18 +58,18 @@ export class FixedThreadPool<
     worker.postMessage(message)
   }
 
-  protected registerWorkerMessageListener (
-    port: ThreadWorkerWithMessageChannel,
-    listener: (message: MessageValue<Response>) => void
+  protected registerWorkerMessageListener<Message extends Data | Response> (
+    messageChannel: ThreadWorkerWithMessageChannel,
+    listener: (message: MessageValue<Message>) => void
   ): void {
-    port.port2?.on('message', listener)
+    messageChannel.port2?.on('message', listener)
   }
 
-  protected unregisterWorkerMessageListener (
-    port: ThreadWorkerWithMessageChannel,
-    listener: (message: MessageValue<Response>) => void
+  protected unregisterWorkerMessageListener<Message extends Data | Response> (
+    messageChannel: ThreadWorkerWithMessageChannel,
+    listener: (message: MessageValue<Message>) => void
   ): void {
-    port.port2?.removeListener('message', listener)
+    messageChannel.port2?.removeListener('message', listener)
   }
 
   protected createWorker (): ThreadWorkerWithMessageChannel {