build(deps-dev): bump @types/node
[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 { TaskFunction, TaskFunctions } from './task-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 * Message port used to communicate with the main worker.
32 */
33 private port!: MessagePort
34 /**
35 * Constructs a new poolifier thread worker.
36 *
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(
45 'poolifier:thread-worker',
46 isMainThread,
47 parentPort as MessagePort,
48 taskFunctions,
49 opts
50 )
51 }
52
53 /** @inheritDoc */
54 protected handleReadyMessage (message: MessageValue<Data>): void {
55 if (
56 message.workerId === this.id &&
57 message.ready === false &&
58 message.port != null
59 ) {
60 try {
61 this.port = message.port
62 this.port.on('message', this.messageListener.bind(this))
63 this.sendToMainWorker({
64 ready: true,
65 taskFunctionNames: this.listTaskFunctionNames()
66 })
67 } catch {
68 this.sendToMainWorker({
69 ready: false,
70 taskFunctionNames: this.listTaskFunctionNames()
71 })
72 }
73 }
74 }
75
76 /** @inheritDoc */
77 protected handleKillMessage (message: MessageValue<Data>): void {
78 super.handleKillMessage(message)
79 this.port?.unref()
80 this.port?.close()
81 }
82
83 /** @inheritDoc */
84 protected get id (): number {
85 return threadId
86 }
87
88 /** @inheritDoc */
89 protected sendToMainWorker (message: MessageValue<Response>): void {
90 this.port.postMessage({ ...message, workerId: this.id })
91 }
92
93 /**
94 * @inheritDoc
95 * @override
96 */
97 protected handleError (error: Error | string): string {
98 return error as string
99 }
100 }