build: switch default to ESM
[poolifier.git] / src / worker / thread-worker.ts
CommitLineData
f59e1027
JB
1import {
2 type MessagePort,
3 isMainThread,
4 parentPort,
5 threadId
6} from 'node:worker_threads'
d35e5717
JB
7import type { MessageValue } from '../utility-types.js'
8import { AbstractWorker } from './abstract-worker.js'
9import type { WorkerOptions } from './worker-options.js'
10import type { TaskFunction, TaskFunctions } from './task-functions.js'
a32e02ba 11
a32e02ba 12/**
729c563d 13 * A thread worker used by a poolifier `ThreadPool`.
4ade5f1f 14 *
729c563d
S
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 *
e102732c
JB
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.
4ade5f1f 23 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
a32e02ba 24 * @since 0.0.1
25 */
d3c8a1a8 26export class ThreadWorker<
deb85c12
JB
27 Data = unknown,
28 Response = unknown
d3c8a1a8 29> extends AbstractWorker<MessagePort, Data, Response> {
85aeb3f3 30 /**
2761efb4 31 * Message port used to communicate with the main worker.
85aeb3f3 32 */
9b5c72ff 33 private port?: MessagePort
49890030 34
729c563d
S
35 /**
36 * Constructs a new poolifier thread worker.
37 *
82888165 38 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
38e795c1 39 * @param opts - Options for the worker.
729c563d 40 */
d4aeae5a 41 public constructor (
82ea6492 42 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
d4aeae5a
JB
43 opts: WorkerOptions = {}
44 ) {
9b5c72ff 45 super(isMainThread, parentPort as MessagePort, taskFunctions, opts)
f59e1027
JB
46 }
47
85aeb3f3
JB
48 /** @inheritDoc */
49 protected handleReadyMessage (message: MessageValue<Data>): void {
50 if (
51 message.workerId === this.id &&
f05ed93c 52 message.ready === false &&
85aeb3f3
JB
53 message.port != null
54 ) {
f05ed93c
JB
55 try {
56 this.port = message.port
57 this.port.on('message', this.messageListener.bind(this))
a5d15204
JB
58 this.sendToMainWorker({
59 ready: true,
895b5341 60 taskFunctionNames: this.listTaskFunctionNames()
a5d15204 61 })
f05ed93c 62 } catch {
a5d15204
JB
63 this.sendToMainWorker({
64 ready: false,
895b5341 65 taskFunctionNames: this.listTaskFunctionNames()
a5d15204 66 })
f05ed93c 67 }
85aeb3f3
JB
68 }
69 }
70
984dc9c8 71 /** @inheritDoc */
d655027b 72 protected handleKillMessage (message: MessageValue<Data>): void {
984dc9c8
JB
73 super.handleKillMessage(message)
74 this.port?.unref()
75 this.port?.close()
76 }
77
85aeb3f3 78 /** @inheritDoc */
f59e1027
JB
79 protected get id (): number {
80 return threadId
106744f7 81 }
7784f548 82
afc003b2 83 /** @inheritDoc */
803f948f
JB
84 protected readonly sendToMainWorker = (
85 message: MessageValue<Response>
86 ): void => {
9b5c72ff 87 this.port?.postMessage({ ...message, workerId: this.id })
7784f548 88 }
985d0e79 89
34d8846f
JB
90 /**
91 * @inheritDoc
92 * @override
93 */
646bced2
JB
94 protected handleError (error: Error | string): string {
95 return error as string
985d0e79 96 }
a32e02ba 97}