refactor: renable standard JS linter rules
[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.js'
8 import { AbstractWorker } from './abstract-worker.js'
9 import type { WorkerOptions } from './worker-options.js'
10 import type { TaskFunction, TaskFunctions } from './task-functions.js'
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 * Message port used to communicate with the main worker.
32 */
33 private port?: MessagePort
34
35 /**
36 * Constructs a new poolifier thread worker.
37 *
38 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
39 * @param opts - Options for the worker.
40 */
41 public constructor (
42 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
43 opts: WorkerOptions = {}
44 ) {
45 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
46 super(isMainThread, parentPort!, taskFunctions, opts)
47 }
48
49 /** @inheritDoc */
50 protected handleReadyMessage (message: MessageValue<Data>): void {
51 if (
52 message.workerId === this.id &&
53 message.ready === false &&
54 message.port != null
55 ) {
56 try {
57 this.port = message.port
58 this.port.on('message', this.messageListener.bind(this))
59 this.sendToMainWorker({
60 ready: true,
61 taskFunctionNames: this.listTaskFunctionNames()
62 })
63 } catch {
64 this.sendToMainWorker({
65 ready: false,
66 taskFunctionNames: this.listTaskFunctionNames()
67 })
68 }
69 }
70 }
71
72 /** @inheritDoc */
73 protected handleKillMessage (message: MessageValue<Data>): void {
74 super.handleKillMessage(message)
75 this.port?.unref()
76 this.port?.close()
77 }
78
79 /** @inheritDoc */
80 protected get id (): number {
81 return threadId
82 }
83
84 /** @inheritDoc */
85 protected readonly sendToMainWorker = (
86 message: MessageValue<Response>
87 ): void => {
88 this.port?.postMessage({ ...message, workerId: this.id })
89 }
90
91 /**
92 * @inheritDoc
93 * @override
94 */
95 protected handleError (error: Error | string): string {
96 return error as string
97 }
98 }