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