perf: remove unneeded class indirection for dynamic pool in worker
[poolifier.git] / src / worker / thread-worker.ts
1 import type { MessagePort } from 'node:worker_threads'
2 import { isMainThread, parentPort } from 'node:worker_threads'
3 import type { MessageValue } from '../utility-types'
4 import { AbstractWorker } from './abstract-worker'
5 import type { WorkerOptions } from './worker-options'
6
7 /**
8 * A thread worker used by a poolifier `ThreadPool`.
9 *
10 * When this worker is inactive for more than the given `maxInactiveTime`,
11 * it will send a termination request to its main thread.
12 *
13 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
14 * but the minimum number of workers will be guaranteed.
15 *
16 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
17 * @typeParam Response - Type of response the worker sends back to the main thread. This can only be serializable data.
18 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
19 * @since 0.0.1
20 */
21 export class ThreadWorker<
22 Data = unknown,
23 Response = unknown
24 > extends AbstractWorker<MessagePort, Data, Response> {
25 /**
26 * Constructs a new poolifier thread worker.
27 *
28 * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
29 * @param opts - Options for the worker.
30 */
31 public constructor (fn: (data: Data) => Response, opts: WorkerOptions = {}) {
32 super('worker-thread-pool:poolifier', isMainThread, fn, parentPort, opts)
33 }
34
35 /** {@inheritDoc} */
36 protected sendToMainWorker (message: MessageValue<Response>): void {
37 this.getMainWorker().postMessage(message)
38 }
39 }