Merge branch 'master' into worker-info
[poolifier.git] / src / worker / thread-worker.ts
1 import {
2 type MessagePort,
3 isMainThread,
4 parentPort,
5 threadId
6 } from 'node:worker_threads'
7 import type { MessageValue } from '../utility-types'
8 import { AbstractWorker } from './abstract-worker'
9 import type { WorkerOptions } from './worker-options'
10 import type { TaskFunctions, WorkerFunction } from './worker-functions'
11
12 /**
13 * A thread worker used by a poolifier `ThreadPool`.
14 *
15 * When this worker is inactive for more than the given `maxInactiveTime`,
16 * it will send a termination request to its main thread.
17 *
18 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
19 * but the minimum number of workers will be guaranteed.
20 *
21 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
22 * @typeParam Response - Type of response the worker sends back to the main thread. This can only be structured-cloneable data.
23 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
24 * @since 0.0.1
25 */
26 export class ThreadWorker<
27 Data = unknown,
28 Response = unknown
29 > extends AbstractWorker<MessagePort, Data, Response> {
30 /**
31 * Constructs a new poolifier thread worker.
32 *
33 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
34 * @param opts - Options for the worker.
35 */
36 public constructor (
37 taskFunctions:
38 | WorkerFunction<Data, Response>
39 | TaskFunctions<Data, Response>,
40 opts: WorkerOptions = {}
41 ) {
42 super(
43 'worker-thread-pool:poolifier',
44 isMainThread,
45 taskFunctions,
46 parentPort as MessagePort,
47 opts
48 )
49 if (!this.isMain) {
50 this.sendToMainWorker({ workerId: this.id, started: true })
51 }
52 }
53
54 protected get id (): number {
55 return threadId
56 }
57
58 /** @inheritDoc */
59 protected sendToMainWorker (message: MessageValue<Response>): void {
60 console.log('sending message to main worker(thread)', message)
61 this.getMainWorker().postMessage(message)
62 }
63 }