8057d6f343caddda5091954cd1ed80e96f2e4b79
[poolifier.git] / src / worker / thread-worker.ts
1 import {
2 isMainThread,
3 type MessagePort,
4 parentPort,
5 threadId,
6 } from 'node:worker_threads'
7
8 import type { MessageValue } from '../utility-types.js'
9 import { AbstractWorker } from './abstract-worker.js'
10 import type { TaskFunction, TaskFunctions } from './task-functions.js'
11 import type { WorkerOptions } from './worker-options.js'
12
13 /**
14 * A thread worker used by a poolifier `ThreadPool`.
15 *
16 * When this worker is inactive for more than the given `maxInactiveTime`,
17 * it will send a termination request to its main thread.
18 *
19 * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
20 * but the minimum number of workers will be guaranteed.
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 * Message port used to communicate with the main worker.
32 */
33 private port?: MessagePort
34
35 /**
36 * Constructs a new poolifier thread worker.
37 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38 * @param opts - Options for the worker.
39 */
40 public constructor (
41 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
42 opts: WorkerOptions = {}
43 ) {
44 super(isMainThread, parentPort, taskFunctions, opts)
45 }
46
47 /** @inheritDoc */
48 protected handleReadyMessage (message: MessageValue<Data>): void {
49 if (
50 message.workerId === this.id &&
51 message.ready === false &&
52 message.port != null
53 ) {
54 try {
55 this.port = message.port
56 this.port.on('message', this.messageListener.bind(this))
57 this.sendToMainWorker({
58 ready: true,
59 taskFunctionsProperties: this.listTaskFunctionsProperties(),
60 })
61 } catch {
62 this.sendToMainWorker({
63 ready: false,
64 taskFunctionsProperties: this.listTaskFunctionsProperties(),
65 })
66 }
67 }
68 }
69
70 /** @inheritDoc */
71 protected handleKillMessage (message: MessageValue<Data>): void {
72 super.handleKillMessage(message)
73 this.port?.unref()
74 this.port?.close()
75 }
76
77 /** @inheritDoc */
78 protected get id (): number {
79 return threadId
80 }
81
82 /** @inheritDoc */
83 protected readonly sendToMainWorker = (
84 message: MessageValue<Response>
85 ): void => {
86 this.port?.postMessage({
87 ...message,
88 workerId: this.id,
89 } satisfies MessageValue<Response>)
90 }
91
92 /**
93 * @inheritDoc
94 */
95 protected handleError (error: Error | string): string {
96 return error as string
97 }
98 }