dc628bed08fa4b23f29724f88f41484b0097afef
[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 * 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:
42 | WorkerFunction<Data, Response>
43 | TaskFunctions<Data, Response>,
44 opts: WorkerOptions = {}
45 ) {
46 super(
47 'worker-thread-pool:poolifier',
48 isMainThread,
49 parentPort as MessagePort,
50 taskFunctions,
51 opts
52 )
53 }
54
55 /** @inheritDoc */
56 protected handleReadyMessage (message: MessageValue<Data>): void {
57 if (
58 !this.isMain &&
59 message.workerId === this.id &&
60 message.ready != null &&
61 message.port != null
62 ) {
63 this.port = message.port
64 this.port.on('message', this.messageListener.bind(this))
65 this.sendToMainWorker({ ready: true, workerId: this.id })
66 }
67 }
68
69 /** @inheritDoc */
70 protected handleKillMessage (message: MessageValue<Data>): void {
71 super.handleKillMessage(message)
72 this.port?.unref()
73 this.port?.close()
74 }
75
76 /** @inheritDoc */
77 protected get id (): number {
78 return threadId
79 }
80
81 /** @inheritDoc */
82 protected sendToMainWorker (message: MessageValue<Response>): void {
83 this.port.postMessage(message)
84 }
85
86 /** @inheritDoc */
87 protected handleError (e: Error | string): string {
88 return e as string
89 }
90 }