Commit | Line | Data |
---|---|---|
fc3e6586 | 1 | import { AsyncResource } from 'node:async_hooks' |
6677a3d3 | 2 | import type { Worker } from 'node:cluster' |
fc3e6586 | 3 | import type { MessagePort } from 'node:worker_threads' |
d715b7bc JB |
4 | import { performance } from 'node:perf_hooks' |
5 | import type { | |
6 | MessageValue, | |
5c4d16da | 7 | Task, |
d715b7bc JB |
8 | TaskPerformance, |
9 | WorkerStatistics | |
10 | } from '../utility-types' | |
ff128cc9 JB |
11 | import { |
12 | DEFAULT_TASK_NAME, | |
13 | EMPTY_FUNCTION, | |
14 | isAsyncFunction, | |
15 | isPlainObject | |
16 | } from '../utils' | |
d38d0e30 | 17 | import { KillBehaviors, type WorkerOptions } from './worker-options' |
b6b32453 | 18 | import type { |
82ea6492 JB |
19 | TaskAsyncFunction, |
20 | TaskFunction, | |
b6b32453 | 21 | TaskFunctions, |
82ea6492 JB |
22 | TaskSyncFunction |
23 | } from './task-functions' | |
4c35177b | 24 | |
978aad6f | 25 | const DEFAULT_MAX_INACTIVE_TIME = 60000 |
d38d0e30 JB |
26 | const DEFAULT_WORKER_OPTIONS: WorkerOptions = { |
27 | /** | |
28 | * The kill behavior option on this worker or its default value. | |
29 | */ | |
30 | killBehavior: KillBehaviors.SOFT, | |
31 | /** | |
32 | * The maximum time to keep this worker active while idle. | |
33 | * The pool automatically checks and terminates this worker when the time expires. | |
34 | */ | |
35 | maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME, | |
36 | /** | |
37 | * The function to call when the worker is killed. | |
38 | */ | |
39 | killHandler: EMPTY_FUNCTION | |
40 | } | |
c97c7edb | 41 | |
729c563d | 42 | /** |
ea7a90d3 | 43 | * Base class that implements some shared logic for all poolifier workers. |
729c563d | 44 | * |
38e795c1 | 45 | * @typeParam MainWorker - Type of main worker. |
e102732c JB |
46 | * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data. |
47 | * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data. | |
729c563d | 48 | */ |
c97c7edb | 49 | export abstract class AbstractWorker< |
6677a3d3 | 50 | MainWorker extends Worker | MessagePort, |
d3c8a1a8 S |
51 | Data = unknown, |
52 | Response = unknown | |
c97c7edb | 53 | > extends AsyncResource { |
f59e1027 | 54 | /** |
83fa0a36 | 55 | * Worker id. |
f59e1027 JB |
56 | */ |
57 | protected abstract id: number | |
a86b6df1 JB |
58 | /** |
59 | * Task function(s) processed by the worker when the pool's `execution` function is invoked. | |
60 | */ | |
82ea6492 | 61 | protected taskFunctions!: Map<string, TaskFunction<Data, Response>> |
729c563d S |
62 | /** |
63 | * Timestamp of the last task processed by this worker. | |
64 | */ | |
a9d9ea34 | 65 | protected lastTaskTimestamp!: number |
b6b32453 | 66 | /** |
8a970421 | 67 | * Performance statistics computation requirements. |
b6b32453 JB |
68 | */ |
69 | protected statistics!: WorkerStatistics | |
729c563d | 70 | /** |
b0a4db63 | 71 | * Handler id of the `activeInterval` worker activity check. |
729c563d | 72 | */ |
b0a4db63 | 73 | protected activeInterval?: NodeJS.Timeout |
c97c7edb | 74 | /** |
729c563d | 75 | * Constructs a new poolifier worker. |
c97c7edb | 76 | * |
38e795c1 JB |
77 | * @param type - The type of async event. |
78 | * @param isMain - Whether this is the main worker or not. | |
38e795c1 | 79 | * @param mainWorker - Reference to main worker. |
85aeb3f3 | 80 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function. |
38e795c1 | 81 | * @param opts - Options for the worker. |
c97c7edb S |
82 | */ |
83 | public constructor ( | |
84 | type: string, | |
c2ade475 | 85 | protected readonly isMain: boolean, |
6c0c538c | 86 | private readonly mainWorker: MainWorker, |
82ea6492 | 87 | taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>, |
d38d0e30 | 88 | protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS |
c97c7edb S |
89 | ) { |
90 | super(type) | |
9d2d0da1 JB |
91 | if (this.isMain == null) { |
92 | throw new Error('isMain parameter is mandatory') | |
93 | } | |
a86b6df1 | 94 | this.checkTaskFunctions(taskFunctions) |
9d2d0da1 | 95 | this.checkWorkerOptions(this.opts) |
1f68cede | 96 | if (!this.isMain) { |
9d2d0da1 | 97 | this.getMainWorker().on('message', this.handleReadyMessage.bind(this)) |
c97c7edb S |
98 | } |
99 | } | |
100 | ||
41aa7dcd | 101 | private checkWorkerOptions (opts: WorkerOptions): void { |
c20084b6 JB |
102 | if (opts != null && !isPlainObject(opts)) { |
103 | throw new TypeError('opts worker options parameter is not a plain object') | |
104 | } | |
105 | if ( | |
106 | opts?.killBehavior != null && | |
107 | !Object.values(KillBehaviors).includes(opts.killBehavior) | |
108 | ) { | |
109 | throw new TypeError( | |
110 | `killBehavior option '${opts.killBehavior}' is not valid` | |
111 | ) | |
112 | } | |
113 | if ( | |
114 | opts?.maxInactiveTime != null && | |
115 | !Number.isSafeInteger(opts.maxInactiveTime) | |
116 | ) { | |
117 | throw new TypeError('maxInactiveTime option is not an integer') | |
118 | } | |
119 | if (opts?.maxInactiveTime != null && opts.maxInactiveTime < 5) { | |
120 | throw new TypeError( | |
121 | 'maxInactiveTime option is not a positive integer greater or equal than 5' | |
122 | ) | |
123 | } | |
124 | if (opts?.killHandler != null && typeof opts.killHandler !== 'function') { | |
125 | throw new TypeError('killHandler option is not a function') | |
126 | } | |
127 | if (opts?.async != null) { | |
128 | throw new Error('async option is deprecated') | |
129 | } | |
d38d0e30 | 130 | this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts } |
41aa7dcd JB |
131 | } |
132 | ||
583c3981 | 133 | private checkValidTaskFunctionEntry ( |
0628df39 JB |
134 | name: string, |
135 | fn: TaskFunction<Data, Response> | |
136 | ): void { | |
137 | if (typeof name !== 'string') { | |
138 | throw new TypeError( | |
139 | 'A taskFunctions parameter object key is not a string' | |
140 | ) | |
141 | } | |
142 | if (typeof name === 'string' && name.trim().length === 0) { | |
143 | throw new TypeError( | |
144 | 'A taskFunctions parameter object key is an empty string' | |
145 | ) | |
146 | } | |
147 | if (typeof fn !== 'function') { | |
148 | throw new TypeError( | |
149 | 'A taskFunctions parameter object value is not a function' | |
150 | ) | |
151 | } | |
152 | } | |
153 | ||
41aa7dcd | 154 | /** |
c20084b6 | 155 | * Checks if the `taskFunctions` parameter is passed to the constructor and valid. |
41aa7dcd | 156 | * |
82888165 | 157 | * @param taskFunctions - The task function(s) parameter that should be checked. |
41aa7dcd | 158 | */ |
a86b6df1 | 159 | private checkTaskFunctions ( |
82ea6492 | 160 | taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response> |
a86b6df1 | 161 | ): void { |
ec8fd331 JB |
162 | if (taskFunctions == null) { |
163 | throw new Error('taskFunctions parameter is mandatory') | |
164 | } | |
82ea6492 | 165 | this.taskFunctions = new Map<string, TaskFunction<Data, Response>>() |
0d80593b | 166 | if (typeof taskFunctions === 'function') { |
2a69b8c5 JB |
167 | const boundFn = taskFunctions.bind(this) |
168 | this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn) | |
169 | this.taskFunctions.set( | |
170 | typeof taskFunctions.name === 'string' && | |
8ebe6c30 | 171 | taskFunctions.name.trim().length > 0 |
2a69b8c5 JB |
172 | ? taskFunctions.name |
173 | : 'fn1', | |
174 | boundFn | |
175 | ) | |
0d80593b | 176 | } else if (isPlainObject(taskFunctions)) { |
82888165 | 177 | let firstEntry = true |
a86b6df1 | 178 | for (const [name, fn] of Object.entries(taskFunctions)) { |
583c3981 | 179 | this.checkValidTaskFunctionEntry(name, fn) |
2a69b8c5 | 180 | const boundFn = fn.bind(this) |
82888165 | 181 | if (firstEntry) { |
2a69b8c5 | 182 | this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn) |
82888165 JB |
183 | firstEntry = false |
184 | } | |
c50b93fb | 185 | this.taskFunctions.set(name, boundFn) |
a86b6df1 | 186 | } |
630f0acf JB |
187 | if (firstEntry) { |
188 | throw new Error('taskFunctions parameter object is empty') | |
189 | } | |
a86b6df1 | 190 | } else { |
f34fdabe JB |
191 | throw new TypeError( |
192 | 'taskFunctions parameter is not a function or a plain object' | |
193 | ) | |
41aa7dcd JB |
194 | } |
195 | } | |
196 | ||
968a2e8c JB |
197 | /** |
198 | * Checks if the worker has a task function with the given name. | |
199 | * | |
200 | * @param name - The name of the task function to check. | |
201 | * @returns Whether the worker has a task function with the given name or not. | |
9e746eec | 202 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string. |
968a2e8c JB |
203 | */ |
204 | public hasTaskFunction (name: string): boolean { | |
d5e3c4ff | 205 | this.checkTaskFunctionName(name) |
968a2e8c JB |
206 | return this.taskFunctions.has(name) |
207 | } | |
208 | ||
209 | /** | |
210 | * Adds a task function to the worker. | |
211 | * If a task function with the same name already exists, it is replaced. | |
212 | * | |
213 | * @param name - The name of the task function to add. | |
214 | * @param fn - The task function to add. | |
215 | * @returns Whether the task function was added or not. | |
9e746eec | 216 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string. |
13a332e6 JB |
217 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name. |
218 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function. | |
968a2e8c JB |
219 | */ |
220 | public addTaskFunction ( | |
221 | name: string, | |
82ea6492 | 222 | fn: TaskFunction<Data, Response> |
968a2e8c | 223 | ): boolean { |
d5e3c4ff | 224 | this.checkTaskFunctionName(name) |
968a2e8c JB |
225 | if (name === DEFAULT_TASK_NAME) { |
226 | throw new Error( | |
227 | 'Cannot add a task function with the default reserved name' | |
228 | ) | |
229 | } | |
230 | if (typeof fn !== 'function') { | |
231 | throw new TypeError('fn parameter is not a function') | |
232 | } | |
233 | try { | |
646d040a | 234 | const boundFn = fn.bind(this) |
968a2e8c JB |
235 | if ( |
236 | this.taskFunctions.get(name) === | |
237 | this.taskFunctions.get(DEFAULT_TASK_NAME) | |
238 | ) { | |
2a69b8c5 | 239 | this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn) |
968a2e8c | 240 | } |
2a69b8c5 | 241 | this.taskFunctions.set(name, boundFn) |
90d7d101 | 242 | this.sendTaskFunctionsListToMainWorker() |
968a2e8c JB |
243 | return true |
244 | } catch { | |
245 | return false | |
246 | } | |
247 | } | |
248 | ||
249 | /** | |
250 | * Removes a task function from the worker. | |
251 | * | |
252 | * @param name - The name of the task function to remove. | |
253 | * @returns Whether the task function existed and was removed or not. | |
9e746eec | 254 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string. |
13a332e6 JB |
255 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name. |
256 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function. | |
968a2e8c JB |
257 | */ |
258 | public removeTaskFunction (name: string): boolean { | |
d5e3c4ff | 259 | this.checkTaskFunctionName(name) |
968a2e8c JB |
260 | if (name === DEFAULT_TASK_NAME) { |
261 | throw new Error( | |
262 | 'Cannot remove the task function with the default reserved name' | |
263 | ) | |
264 | } | |
265 | if ( | |
266 | this.taskFunctions.get(name) === this.taskFunctions.get(DEFAULT_TASK_NAME) | |
267 | ) { | |
268 | throw new Error( | |
269 | 'Cannot remove the task function used as the default task function' | |
270 | ) | |
271 | } | |
90d7d101 JB |
272 | const deleteStatus = this.taskFunctions.delete(name) |
273 | this.sendTaskFunctionsListToMainWorker() | |
274 | return deleteStatus | |
968a2e8c JB |
275 | } |
276 | ||
277 | /** | |
c50b93fb JB |
278 | * Lists the names of the worker's task functions. |
279 | * | |
280 | * @returns The names of the worker's task functions. | |
281 | */ | |
282 | public listTaskFunctions (): string[] { | |
b558f6b5 JB |
283 | const names: string[] = [...this.taskFunctions.keys()] |
284 | let defaultTaskFunctionName: string = DEFAULT_TASK_NAME | |
285 | for (const [name, fn] of this.taskFunctions) { | |
286 | if ( | |
287 | name !== DEFAULT_TASK_NAME && | |
288 | fn === this.taskFunctions.get(DEFAULT_TASK_NAME) | |
289 | ) { | |
290 | defaultTaskFunctionName = name | |
291 | break | |
292 | } | |
293 | } | |
294 | return [ | |
295 | names[names.indexOf(DEFAULT_TASK_NAME)], | |
296 | defaultTaskFunctionName, | |
297 | ...names.filter( | |
041dc05b | 298 | name => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName |
b558f6b5 JB |
299 | ) |
300 | ] | |
c50b93fb JB |
301 | } |
302 | ||
303 | /** | |
304 | * Sets the default task function to use in the worker. | |
968a2e8c JB |
305 | * |
306 | * @param name - The name of the task function to use as default task function. | |
307 | * @returns Whether the default task function was set or not. | |
9e746eec | 308 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string. |
13a332e6 JB |
309 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name. |
310 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function. | |
968a2e8c JB |
311 | */ |
312 | public setDefaultTaskFunction (name: string): boolean { | |
d5e3c4ff | 313 | this.checkTaskFunctionName(name) |
968a2e8c JB |
314 | if (name === DEFAULT_TASK_NAME) { |
315 | throw new Error( | |
316 | 'Cannot set the default task function reserved name as the default task function' | |
317 | ) | |
318 | } | |
319 | if (!this.taskFunctions.has(name)) { | |
320 | throw new Error( | |
321 | 'Cannot set the default task function to a non-existing task function' | |
322 | ) | |
323 | } | |
324 | try { | |
325 | this.taskFunctions.set( | |
326 | DEFAULT_TASK_NAME, | |
82ea6492 | 327 | this.taskFunctions.get(name) as TaskFunction<Data, Response> |
968a2e8c JB |
328 | ) |
329 | return true | |
330 | } catch { | |
331 | return false | |
332 | } | |
333 | } | |
334 | ||
d5e3c4ff JB |
335 | private checkTaskFunctionName (name: string): void { |
336 | if (typeof name !== 'string') { | |
337 | throw new TypeError('name parameter is not a string') | |
338 | } | |
339 | if (typeof name === 'string' && name.trim().length === 0) { | |
340 | throw new TypeError('name parameter is an empty string') | |
341 | } | |
342 | } | |
343 | ||
a038b517 JB |
344 | /** |
345 | * Handles the ready message sent by the main worker. | |
346 | * | |
347 | * @param message - The ready message. | |
348 | */ | |
349 | protected abstract handleReadyMessage (message: MessageValue<Data>): void | |
350 | ||
aee46736 JB |
351 | /** |
352 | * Worker message listener. | |
353 | * | |
6b813701 | 354 | * @param message - The received message. |
aee46736 | 355 | */ |
85aeb3f3 | 356 | protected messageListener (message: MessageValue<Data>): void { |
9e746eec | 357 | this.checkMessageWorkerId(message) |
310de0aa JB |
358 | if (message.statistics != null) { |
359 | // Statistics message received | |
360 | this.statistics = message.statistics | |
361 | } else if (message.checkActive != null) { | |
362 | // Check active message received | |
363 | message.checkActive ? this.startCheckActive() : this.stopCheckActive() | |
364 | } else if (message.taskId != null && message.data != null) { | |
365 | // Task message received | |
366 | this.run(message) | |
367 | } else if (message.kill === true) { | |
368 | // Kill message received | |
369 | this.handleKillMessage(message) | |
cf597bc5 JB |
370 | } |
371 | } | |
372 | ||
984dc9c8 JB |
373 | /** |
374 | * Handles a kill message sent by the main worker. | |
375 | * | |
376 | * @param message - The kill message. | |
377 | */ | |
378 | protected handleKillMessage (message: MessageValue<Data>): void { | |
29d8b961 | 379 | this.stopCheckActive() |
07588f30 | 380 | if (isAsyncFunction(this.opts.killHandler)) { |
041dc05b | 381 | (this.opts.killHandler?.() as Promise<void>) |
1e3214b6 JB |
382 | .then(() => { |
383 | this.sendToMainWorker({ kill: 'success', workerId: this.id }) | |
384 | return null | |
385 | }) | |
386 | .catch(() => { | |
387 | this.sendToMainWorker({ kill: 'failure', workerId: this.id }) | |
388 | }) | |
389 | .finally(() => { | |
390 | this.emitDestroy() | |
391 | }) | |
07588f30 JB |
392 | .catch(EMPTY_FUNCTION) |
393 | } else { | |
1e3214b6 JB |
394 | try { |
395 | // eslint-disable-next-line @typescript-eslint/no-invalid-void-type | |
396 | this.opts.killHandler?.() as void | |
397 | this.sendToMainWorker({ kill: 'success', workerId: this.id }) | |
7c8ac84e | 398 | } catch { |
1e3214b6 JB |
399 | this.sendToMainWorker({ kill: 'failure', workerId: this.id }) |
400 | } finally { | |
401 | this.emitDestroy() | |
402 | } | |
07588f30 | 403 | } |
984dc9c8 JB |
404 | } |
405 | ||
9e746eec JB |
406 | /** |
407 | * Check if the message worker id is set and matches the worker id. | |
408 | * | |
409 | * @param message - The message to check. | |
410 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the message worker id is not set or does not match the worker id. | |
411 | */ | |
412 | private checkMessageWorkerId (message: MessageValue<Data>): void { | |
413 | if (message.workerId == null) { | |
414 | throw new Error('Message worker id is not set') | |
415 | } else if (message.workerId != null && message.workerId !== this.id) { | |
416 | throw new Error( | |
417 | `Message worker id ${message.workerId} does not match the worker id ${this.id}` | |
418 | ) | |
419 | } | |
420 | } | |
421 | ||
48487131 | 422 | /** |
b0a4db63 | 423 | * Starts the worker check active interval. |
48487131 | 424 | */ |
b0a4db63 | 425 | private startCheckActive (): void { |
75d3401a | 426 | this.lastTaskTimestamp = performance.now() |
b0a4db63 JB |
427 | this.activeInterval = setInterval( |
428 | this.checkActive.bind(this), | |
75d3401a | 429 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
984dc9c8 | 430 | ) |
75d3401a JB |
431 | } |
432 | ||
48487131 | 433 | /** |
b0a4db63 | 434 | * Stops the worker check active interval. |
48487131 | 435 | */ |
b0a4db63 | 436 | private stopCheckActive (): void { |
c3f498b5 JB |
437 | if (this.activeInterval != null) { |
438 | clearInterval(this.activeInterval) | |
439 | delete this.activeInterval | |
440 | } | |
48487131 JB |
441 | } |
442 | ||
443 | /** | |
444 | * Checks if the worker should be terminated, because its living too long. | |
445 | */ | |
b0a4db63 | 446 | private checkActive (): void { |
48487131 JB |
447 | if ( |
448 | performance.now() - this.lastTaskTimestamp > | |
449 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
450 | ) { | |
21f710aa | 451 | this.sendToMainWorker({ kill: this.opts.killBehavior, workerId: this.id }) |
48487131 JB |
452 | } |
453 | } | |
454 | ||
729c563d S |
455 | /** |
456 | * Returns the main worker. | |
838898f1 S |
457 | * |
458 | * @returns Reference to the main worker. | |
155bb3de | 459 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set. |
729c563d | 460 | */ |
838898f1 | 461 | protected getMainWorker (): MainWorker { |
78cea37e | 462 | if (this.mainWorker == null) { |
e102732c | 463 | throw new Error('Main worker not set') |
838898f1 S |
464 | } |
465 | return this.mainWorker | |
466 | } | |
c97c7edb | 467 | |
729c563d | 468 | /** |
aa9eede8 | 469 | * Sends a message to main worker. |
729c563d | 470 | * |
38e795c1 | 471 | * @param message - The response message. |
729c563d | 472 | */ |
82f36766 JB |
473 | protected abstract sendToMainWorker ( |
474 | message: MessageValue<Response, Data> | |
475 | ): void | |
c97c7edb | 476 | |
90d7d101 JB |
477 | /** |
478 | * Sends the list of task function names to the main worker. | |
479 | */ | |
480 | protected sendTaskFunctionsListToMainWorker (): void { | |
481 | this.sendToMainWorker({ | |
482 | taskFunctions: this.listTaskFunctions(), | |
483 | workerId: this.id | |
484 | }) | |
485 | } | |
486 | ||
729c563d | 487 | /** |
8accb8d5 | 488 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 489 | * |
646bced2 | 490 | * @param error - The error raised by the worker. |
ab80dc46 | 491 | * @returns The error message. |
729c563d | 492 | */ |
646bced2 JB |
493 | protected handleError (error: Error | string): string { |
494 | return error instanceof Error ? error.message : error | |
c97c7edb S |
495 | } |
496 | ||
5c4d16da JB |
497 | /** |
498 | * Runs the given task. | |
499 | * | |
500 | * @param task - The task to execute. | |
501 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found. | |
502 | */ | |
503 | protected run (task: Task<Data>): void { | |
9d2d0da1 JB |
504 | const { name, taskId, data } = task |
505 | const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME) | |
506 | if (fn == null) { | |
507 | this.sendToMainWorker({ | |
508 | taskError: { | |
509 | name: name as string, | |
510 | message: `Task function '${name as string}' not found`, | |
511 | data | |
512 | }, | |
513 | workerId: this.id, | |
514 | taskId | |
515 | }) | |
516 | return | |
517 | } | |
5c4d16da JB |
518 | if (isAsyncFunction(fn)) { |
519 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, task) | |
520 | } else { | |
521 | this.runInAsyncScope(this.runSync.bind(this), this, fn, task) | |
522 | } | |
523 | } | |
524 | ||
729c563d | 525 | /** |
4dd93fcf | 526 | * Runs the given task function synchronously. |
729c563d | 527 | * |
5c4d16da JB |
528 | * @param fn - Task function that will be executed. |
529 | * @param task - Input data for the task function. | |
729c563d | 530 | */ |
70a4f5ea | 531 | protected runSync ( |
82ea6492 | 532 | fn: TaskSyncFunction<Data, Response>, |
5c4d16da | 533 | task: Task<Data> |
c97c7edb | 534 | ): void { |
310de0aa | 535 | const { name, taskId, data } = task |
c97c7edb | 536 | try { |
310de0aa JB |
537 | let taskPerformance = this.beginTaskPerformance(name) |
538 | const res = fn(data) | |
d715b7bc | 539 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
540 | this.sendToMainWorker({ |
541 | data: res, | |
d715b7bc | 542 | taskPerformance, |
f59e1027 | 543 | workerId: this.id, |
310de0aa | 544 | taskId |
3fafb1b2 | 545 | }) |
646bced2 | 546 | } catch (error) { |
91ee39ed | 547 | this.sendToMainWorker({ |
82f36766 | 548 | taskError: { |
0628755c | 549 | name: name as string, |
646bced2 | 550 | message: this.handleError(error as Error | string), |
310de0aa | 551 | data |
82f36766 | 552 | }, |
21f710aa | 553 | workerId: this.id, |
310de0aa | 554 | taskId |
91ee39ed | 555 | }) |
6e9d10db | 556 | } finally { |
c3f498b5 | 557 | this.updateLastTaskTimestamp() |
c97c7edb S |
558 | } |
559 | } | |
560 | ||
729c563d | 561 | /** |
4dd93fcf | 562 | * Runs the given task function asynchronously. |
729c563d | 563 | * |
5c4d16da JB |
564 | * @param fn - Task function that will be executed. |
565 | * @param task - Input data for the task function. | |
729c563d | 566 | */ |
c97c7edb | 567 | protected runAsync ( |
82ea6492 | 568 | fn: TaskAsyncFunction<Data, Response>, |
5c4d16da | 569 | task: Task<Data> |
c97c7edb | 570 | ): void { |
310de0aa JB |
571 | const { name, taskId, data } = task |
572 | let taskPerformance = this.beginTaskPerformance(name) | |
573 | fn(data) | |
041dc05b | 574 | .then(res => { |
d715b7bc | 575 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
576 | this.sendToMainWorker({ |
577 | data: res, | |
d715b7bc | 578 | taskPerformance, |
f59e1027 | 579 | workerId: this.id, |
310de0aa | 580 | taskId |
3fafb1b2 | 581 | }) |
c97c7edb S |
582 | return null |
583 | }) | |
646bced2 | 584 | .catch(error => { |
91ee39ed | 585 | this.sendToMainWorker({ |
82f36766 | 586 | taskError: { |
0628755c | 587 | name: name as string, |
646bced2 | 588 | message: this.handleError(error as Error | string), |
310de0aa | 589 | data |
82f36766 | 590 | }, |
21f710aa | 591 | workerId: this.id, |
310de0aa | 592 | taskId |
91ee39ed | 593 | }) |
6e9d10db JB |
594 | }) |
595 | .finally(() => { | |
c3f498b5 | 596 | this.updateLastTaskTimestamp() |
c97c7edb | 597 | }) |
6e9d10db | 598 | .catch(EMPTY_FUNCTION) |
c97c7edb | 599 | } |
ec8fd331 | 600 | |
197b4aa5 | 601 | private beginTaskPerformance (name?: string): TaskPerformance { |
8a970421 | 602 | this.checkStatistics() |
62c15a68 | 603 | return { |
ff128cc9 | 604 | name: name ?? DEFAULT_TASK_NAME, |
1c6fe997 | 605 | timestamp: performance.now(), |
b6b32453 | 606 | ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) |
62c15a68 JB |
607 | } |
608 | } | |
609 | ||
d9d31201 JB |
610 | private endTaskPerformance ( |
611 | taskPerformance: TaskPerformance | |
612 | ): TaskPerformance { | |
8a970421 | 613 | this.checkStatistics() |
62c15a68 JB |
614 | return { |
615 | ...taskPerformance, | |
b6b32453 JB |
616 | ...(this.statistics.runTime && { |
617 | runTime: performance.now() - taskPerformance.timestamp | |
618 | }), | |
619 | ...(this.statistics.elu && { | |
62c15a68 | 620 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 621 | }) |
62c15a68 JB |
622 | } |
623 | } | |
8a970421 JB |
624 | |
625 | private checkStatistics (): void { | |
626 | if (this.statistics == null) { | |
627 | throw new Error('Performance statistics computation requirements not set') | |
628 | } | |
629 | } | |
c3f498b5 JB |
630 | |
631 | private updateLastTaskTimestamp (): void { | |
29d8b961 | 632 | if (this.activeInterval != null) { |
c3f498b5 JB |
633 | this.lastTaskTimestamp = performance.now() |
634 | } | |
635 | } | |
c97c7edb | 636 | } |