Extract selection strategies to classes (#176)
[poolifier.git] / src / pools / thread / fixed.ts
1 import { isMainThread, MessageChannel, SHARE_ENV, Worker } from 'worker_threads'
2 import type { Draft, MessageValue } from '../../utility-types'
3 import type { PoolOptions } from '../abstract-pool'
4 import { AbstractPool } from '../abstract-pool'
5
6 /**
7 * A thread worker with message channels for communication between main thread and thread worker.
8 */
9 export type ThreadWorkerWithMessageChannel = Worker & Draft<MessageChannel>
10
11 /**
12 * A thread pool with a fixed number of threads.
13 *
14 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
15 *
16 * This pool selects the threads in a round robin fashion.
17 *
18 * @template Data Type of data sent to the worker. This can only be serializable data.
19 * @template Response Type of response of execution. This can only be serializable data.
20 *
21 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
22 * @since 0.0.1
23 */
24 export class FixedThreadPool<
25 Data = unknown,
26 Response = unknown
27 > extends AbstractPool<ThreadWorkerWithMessageChannel, Data, Response> {
28 /**
29 * Constructs a new poolifier fixed thread pool.
30 *
31 * @param numberOfThreads Number of threads for this pool.
32 * @param filePath Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
33 * @param opts Options for this fixed thread pool. Default: `{ maxTasks: 1000 }`
34 */
35 public constructor (
36 numberOfThreads: number,
37 filePath: string,
38 opts: PoolOptions<ThreadWorkerWithMessageChannel> = { maxTasks: 1000 }
39 ) {
40 super(numberOfThreads, filePath, opts)
41 }
42
43 protected isMain (): boolean {
44 return isMainThread
45 }
46
47 /** @inheritdoc */
48 public async destroyWorker (
49 worker: ThreadWorkerWithMessageChannel
50 ): Promise<void> {
51 this.sendToWorker(worker, { kill: 1 })
52 await worker.terminate()
53 }
54
55 protected sendToWorker (
56 worker: ThreadWorkerWithMessageChannel,
57 message: MessageValue<Data>
58 ): void {
59 worker.postMessage(message)
60 }
61
62 /** @inheritdoc */
63 public registerWorkerMessageListener<Message extends Data | Response> (
64 messageChannel: ThreadWorkerWithMessageChannel,
65 listener: (message: MessageValue<Message>) => void
66 ): void {
67 messageChannel.port2?.on('message', listener)
68 }
69
70 protected unregisterWorkerMessageListener<Message extends Data | Response> (
71 messageChannel: ThreadWorkerWithMessageChannel,
72 listener: (message: MessageValue<Message>) => void
73 ): void {
74 messageChannel.port2?.removeListener('message', listener)
75 }
76
77 protected createWorker (): ThreadWorkerWithMessageChannel {
78 return new Worker(this.filePath, {
79 env: SHARE_ENV
80 })
81 }
82
83 protected afterWorkerSetup (worker: ThreadWorkerWithMessageChannel): void {
84 const { port1, port2 } = new MessageChannel()
85 worker.postMessage({ parent: port1 }, [port1])
86 worker.port1 = port1
87 worker.port2 = port2
88 // We will attach a listener for every task,
89 // when task is completed the listener will be removed but to avoid warnings we are increasing the max listeners size
90 worker.port2.setMaxListeners(this.opts.maxTasks ?? 1000)
91 }
92 }