Merge branch 'master' into multiple-functions
[poolifier.git] / src / worker / abstract-worker.ts
1 import { AsyncResource } from 'node:async_hooks'
2 import type { Worker } from 'node:cluster'
3 import type { MessagePort } from 'node:worker_threads'
4 import {
5 type MessageValue,
6 type TaskFunctions,
7 type WorkerAsyncFunction,
8 type WorkerFunction,
9 type WorkerSyncFunction
10 } from '../utility-types'
11 import { EMPTY_FUNCTION } from '../utils'
12 import type { KillBehavior, WorkerOptions } from './worker-options'
13 import { KillBehaviors } from './worker-options'
14
15 const DEFAULT_FUNCTION_NAME = 'default'
16 const DEFAULT_MAX_INACTIVE_TIME = 60000
17 const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT
18
19 /**
20 * Base class that implements some shared logic for all poolifier workers.
21 *
22 * @typeParam MainWorker - Type of main worker.
23 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data.
24 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data.
25 */
26 export abstract class AbstractWorker<
27 MainWorker extends Worker | MessagePort,
28 Data = unknown,
29 Response = unknown
30 > extends AsyncResource {
31 /**
32 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
33 */
34 protected taskFunctions!: Map<string, WorkerFunction<Data, Response>>
35 /**
36 * Timestamp of the last task processed by this worker.
37 */
38 protected lastTaskTimestamp!: number
39 /**
40 * Handler id of the `aliveInterval` worker alive check.
41 */
42 protected readonly aliveInterval?: NodeJS.Timeout
43 /**
44 * Constructs a new poolifier worker.
45 *
46 * @param type - The type of async event.
47 * @param isMain - Whether this is the main worker or not.
48 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
49 * @param mainWorker - Reference to main worker.
50 * @param opts - Options for the worker.
51 */
52 public constructor (
53 type: string,
54 protected readonly isMain: boolean,
55 taskFunctions:
56 | WorkerFunction<Data, Response>
57 | TaskFunctions<Data, Response>,
58 protected mainWorker: MainWorker | undefined | null,
59 protected readonly opts: WorkerOptions = {
60 /**
61 * The kill behavior option on this worker or its default value.
62 */
63 killBehavior: DEFAULT_KILL_BEHAVIOR,
64 /**
65 * The maximum time to keep this worker alive while idle.
66 * The pool automatically checks and terminates this worker when the time expires.
67 */
68 maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME
69 }
70 ) {
71 super(type)
72 this.checkWorkerOptions(this.opts)
73 this.checkTaskFunctions(taskFunctions)
74 if (!this.isMain) {
75 this.lastTaskTimestamp = performance.now()
76 this.aliveInterval = setInterval(
77 this.checkAlive.bind(this),
78 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
79 )
80 this.checkAlive.bind(this)()
81 }
82
83 this.mainWorker?.on(
84 'message',
85 (message: MessageValue<Data, MainWorker>) => {
86 this.messageListener(message)
87 }
88 )
89 }
90
91 private checkWorkerOptions (opts: WorkerOptions): void {
92 this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
93 this.opts.maxInactiveTime =
94 opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
95 this.opts.async = opts.async ?? false
96 }
97
98 /**
99 * Checks if the `taskFunctions` parameter is passed to the constructor.
100 *
101 * @param taskFunctions - The task function(s) that should be defined.
102 */
103 private checkTaskFunctions (
104 taskFunctions:
105 | WorkerFunction<Data, Response>
106 | TaskFunctions<Data, Response>
107 ): void {
108 if (taskFunctions == null) {
109 throw new Error('taskFunctions parameter is mandatory')
110 }
111 if (
112 typeof taskFunctions !== 'function' &&
113 typeof taskFunctions !== 'object'
114 ) {
115 throw new Error('taskFunctions parameter is not a function or an object')
116 }
117 if (
118 typeof taskFunctions === 'object' &&
119 taskFunctions.constructor !== Object &&
120 Object.prototype.toString.call(taskFunctions) !== '[object Object]'
121 ) {
122 throw new Error('taskFunctions parameter is not an object literal')
123 }
124 this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>()
125 if (typeof taskFunctions !== 'function') {
126 for (const [name, fn] of Object.entries(taskFunctions)) {
127 if (typeof fn !== 'function') {
128 throw new Error(
129 'A taskFunctions parameter object value is not a function'
130 )
131 }
132 this.taskFunctions.set(name, fn.bind(this))
133 }
134 } else {
135 this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this))
136 }
137 }
138
139 /**
140 * Worker message listener.
141 *
142 * @param message - Message received.
143 */
144 protected messageListener (message: MessageValue<Data, MainWorker>): void {
145 if (message.id != null && message.data != null) {
146 // Task message received
147 const fn = this.getTaskFunction(message.name)
148 if (fn?.constructor.name === 'AsyncFunction') {
149 this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
150 } else {
151 this.runInAsyncScope(this.run.bind(this), this, fn, message)
152 }
153 } else if (message.parent != null) {
154 // Main worker reference message received
155 this.mainWorker = message.parent
156 } else if (message.kill != null) {
157 // Kill message received
158 this.aliveInterval != null && clearInterval(this.aliveInterval)
159 this.emitDestroy()
160 }
161 }
162
163 /**
164 * Returns the main worker.
165 *
166 * @returns Reference to the main worker.
167 */
168 protected getMainWorker (): MainWorker {
169 if (this.mainWorker == null) {
170 throw new Error('Main worker was not set')
171 }
172 return this.mainWorker
173 }
174
175 /**
176 * Sends a message to the main worker.
177 *
178 * @param message - The response message.
179 */
180 protected abstract sendToMainWorker (message: MessageValue<Response>): void
181
182 /**
183 * Checks if the worker should be terminated, because its living too long.
184 */
185 protected checkAlive (): void {
186 if (
187 performance.now() - this.lastTaskTimestamp >
188 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
189 ) {
190 this.sendToMainWorker({ kill: this.opts.killBehavior })
191 }
192 }
193
194 /**
195 * Handles an error and convert it to a string so it can be sent back to the main worker.
196 *
197 * @param e - The error raised by the worker.
198 * @returns Message of the error.
199 */
200 protected handleError (e: Error | string): string {
201 return e as string
202 }
203
204 /**
205 * Runs the given function synchronously.
206 *
207 * @param fn - Function that will be executed.
208 * @param message - Input data for the given function.
209 */
210 protected run (
211 fn: WorkerSyncFunction<Data, Response>,
212 message: MessageValue<Data>
213 ): void {
214 try {
215 const startTimestamp = performance.now()
216 const res = fn(message.data)
217 const runTime = performance.now() - startTimestamp
218 this.sendToMainWorker({
219 data: res,
220 id: message.id,
221 runTime
222 })
223 } catch (e) {
224 const err = this.handleError(e as Error)
225 this.sendToMainWorker({ error: err, id: message.id })
226 } finally {
227 !this.isMain && (this.lastTaskTimestamp = performance.now())
228 }
229 }
230
231 /**
232 * Runs the given function asynchronously.
233 *
234 * @param fn - Function that will be executed.
235 * @param message - Input data for the given function.
236 */
237 protected runAsync (
238 fn: WorkerAsyncFunction<Data, Response>,
239 message: MessageValue<Data>
240 ): void {
241 const startTimestamp = performance.now()
242 fn(message.data)
243 .then(res => {
244 const runTime = performance.now() - startTimestamp
245 this.sendToMainWorker({
246 data: res,
247 id: message.id,
248 runTime
249 })
250 return null
251 })
252 .catch(e => {
253 const err = this.handleError(e as Error)
254 this.sendToMainWorker({ error: err, id: message.id })
255 })
256 .finally(() => {
257 !this.isMain && (this.lastTaskTimestamp = performance.now())
258 })
259 .catch(EMPTY_FUNCTION)
260 }
261
262 private getTaskFunction (name?: string): WorkerFunction<Data, Response> {
263 name = name ?? DEFAULT_FUNCTION_NAME
264 const fn = this.taskFunctions.get(name)
265 if (fn == null) {
266 throw new Error(`Task function "${name}" not found`)
267 }
268 return fn
269 }
270 }