X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fworker%2Fabstract-worker.ts;h=bb6ac5666e0252195b4f1cafbda38471ec7fcf07;hb=910416386b4f7d0da4e6f0d8551cefa2539c5ced;hp=15259106cfe59e1e73d7ec3a613da27a262c62a8;hpb=04212af7b1a1494ff58da58c9e5b3397d25f18b7;p=poolifier.git diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index 15259106..bb6ac566 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -1,31 +1,35 @@ import type { Worker } from 'node:cluster' -import type { MessagePort } from 'node:worker_threads' import { performance } from 'node:perf_hooks' +import type { MessagePort } from 'node:worker_threads' + import type { MessageValue, Task, + TaskFunctionProperties, TaskPerformance, WorkerStatistics -} from '../utility-types' +} from '../utility-types.js' import { + buildTaskFunctionProperties, DEFAULT_TASK_NAME, EMPTY_FUNCTION, isAsyncFunction, isPlainObject -} from '../utils' -import { KillBehaviors, type WorkerOptions } from './worker-options' +} from '../utils.js' import type { TaskAsyncFunction, TaskFunction, + TaskFunctionObject, TaskFunctionOperationResult, TaskFunctions, TaskSyncFunction -} from './task-functions' +} from './task-functions.js' import { checkTaskFunctionName, - checkValidTaskFunctionEntry, + checkValidTaskFunctionObjectEntry, checkValidWorkerOptions -} from './utils' +} from './utils.js' +import { KillBehaviors, type WorkerOptions } from './worker-options.js' const DEFAULT_MAX_INACTIVE_TIME = 60000 const DEFAULT_WORKER_OPTIONS: WorkerOptions = { @@ -61,9 +65,9 @@ export abstract class AbstractWorker< */ protected abstract id: number /** - * Task function(s) processed by the worker when the pool's `execution` function is invoked. + * Task function object(s) processed by the worker when the pool's `execution` function is invoked. */ - protected taskFunctions!: Map> + protected taskFunctions!: Map> /** * Timestamp of the last task processed by this worker. */ @@ -71,23 +75,23 @@ export abstract class AbstractWorker< /** * Performance statistics computation requirements. */ - protected statistics!: WorkerStatistics + protected statistics?: WorkerStatistics /** * Handler id of the `activeInterval` worker activity check. */ protected activeInterval?: NodeJS.Timeout + /** * Constructs a new poolifier worker. * - * @param type - The type of async event. * @param isMain - Whether this is the main worker or not. * @param mainWorker - Reference to main worker. * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function. * @param opts - Options for the worker. */ public constructor ( - protected readonly isMain: boolean, - private readonly mainWorker: MainWorker, + protected readonly isMain: boolean | undefined, + private readonly mainWorker: MainWorker | undefined | null, taskFunctions: TaskFunction | TaskFunctions, protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS ) { @@ -113,32 +117,41 @@ export abstract class AbstractWorker< * @param taskFunctions - The task function(s) parameter that should be checked. */ private checkTaskFunctions ( - taskFunctions: TaskFunction | TaskFunctions + taskFunctions: + | TaskFunction + | TaskFunctions + | undefined ): void { if (taskFunctions == null) { throw new Error('taskFunctions parameter is mandatory') } - this.taskFunctions = new Map>() + this.taskFunctions = new Map>() if (typeof taskFunctions === 'function') { - const boundFn = taskFunctions.bind(this) - this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn) + const fnObj = { taskFunction: taskFunctions.bind(this) } + this.taskFunctions.set(DEFAULT_TASK_NAME, fnObj) this.taskFunctions.set( typeof taskFunctions.name === 'string' && - taskFunctions.name.trim().length > 0 + taskFunctions.name.trim().length > 0 ? taskFunctions.name : 'fn1', - boundFn + fnObj ) } else if (isPlainObject(taskFunctions)) { let firstEntry = true - for (const [name, fn] of Object.entries(taskFunctions)) { - checkValidTaskFunctionEntry(name, fn) - const boundFn = fn.bind(this) + for (let [name, fnObj] of Object.entries(taskFunctions)) { + if (typeof fnObj === 'function') { + fnObj = { taskFunction: fnObj } satisfies TaskFunctionObject< + Data, + Response + > + } + checkValidTaskFunctionObjectEntry(name, fnObj) + fnObj.taskFunction = fnObj.taskFunction.bind(this) if (firstEntry) { - this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn) + this.taskFunctions.set(DEFAULT_TASK_NAME, fnObj) firstEntry = false } - this.taskFunctions.set(name, boundFn) + this.taskFunctions.set(name, fnObj) } if (firstEntry) { throw new Error('taskFunctions parameter object is empty') @@ -175,7 +188,7 @@ export abstract class AbstractWorker< */ public addTaskFunction ( name: string, - fn: TaskFunction + fn: TaskFunction | TaskFunctionObject ): TaskFunctionOperationResult { try { checkTaskFunctionName(name) @@ -184,18 +197,19 @@ export abstract class AbstractWorker< 'Cannot add a task function with the default reserved name' ) } - if (typeof fn !== 'function') { - throw new TypeError('fn parameter is not a function') + if (typeof fn === 'function') { + fn = { taskFunction: fn } satisfies TaskFunctionObject } - const boundFn = fn.bind(this) + checkValidTaskFunctionObjectEntry(name, fn) + fn.taskFunction = fn.taskFunction.bind(this) if ( this.taskFunctions.get(name) === this.taskFunctions.get(DEFAULT_TASK_NAME) ) { - this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn) + this.taskFunctions.set(DEFAULT_TASK_NAME, fn) } - this.taskFunctions.set(name, boundFn) - this.sendTaskFunctionNamesToMainWorker() + this.taskFunctions.set(name, fn) + this.sendTaskFunctionsPropertiesToMainWorker() return { status: true } } catch (error) { return { status: false, error: error as Error } @@ -225,7 +239,7 @@ export abstract class AbstractWorker< ) } const deleteStatus = this.taskFunctions.delete(name) - this.sendTaskFunctionNamesToMainWorker() + this.sendTaskFunctionsPropertiesToMainWorker() return { status: deleteStatus } } catch (error) { return { status: false, error: error as Error } @@ -233,28 +247,38 @@ export abstract class AbstractWorker< } /** - * Lists the names of the worker's task functions. + * Lists the properties of the worker's task functions. * - * @returns The names of the worker's task functions. + * @returns The properties of the worker's task functions. */ - public listTaskFunctionNames (): string[] { - const names: string[] = [...this.taskFunctions.keys()] - let defaultTaskFunctionName: string = DEFAULT_TASK_NAME - for (const [name, fn] of this.taskFunctions) { + public listTaskFunctionsProperties (): TaskFunctionProperties[] { + let defaultTaskFunctionName = DEFAULT_TASK_NAME + for (const [name, fnObj] of this.taskFunctions) { if ( name !== DEFAULT_TASK_NAME && - fn === this.taskFunctions.get(DEFAULT_TASK_NAME) + fnObj === this.taskFunctions.get(DEFAULT_TASK_NAME) ) { defaultTaskFunctionName = name break } } + const taskFunctionsProperties: TaskFunctionProperties[] = [] + for (const [name, fnObj] of this.taskFunctions) { + if (name === DEFAULT_TASK_NAME || name === defaultTaskFunctionName) { + continue + } + taskFunctionsProperties.push(buildTaskFunctionProperties(name, fnObj)) + } return [ - names[names.indexOf(DEFAULT_TASK_NAME)], - defaultTaskFunctionName, - ...names.filter( - name => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName - ) + buildTaskFunctionProperties( + DEFAULT_TASK_NAME, + this.taskFunctions.get(DEFAULT_TASK_NAME) + ), + buildTaskFunctionProperties( + defaultTaskFunctionName, + this.taskFunctions.get(defaultTaskFunctionName) + ), + ...taskFunctionsProperties ] } @@ -277,11 +301,9 @@ export abstract class AbstractWorker< 'Cannot set the default task function to a non-existing task function' ) } - this.taskFunctions.set( - DEFAULT_TASK_NAME, - this.taskFunctions.get(name) as TaskFunction - ) - this.sendTaskFunctionNamesToMainWorker() + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.taskFunctions.set(DEFAULT_TASK_NAME, this.taskFunctions.get(name)!) + this.sendTaskFunctionsPropertiesToMainWorker() return { status: true } } catch (error) { return { status: false, error: error as Error } @@ -302,19 +324,27 @@ export abstract class AbstractWorker< */ protected messageListener (message: MessageValue): void { this.checkMessageWorkerId(message) - if (message.statistics != null) { + const { + statistics, + checkActive, + taskFunctionOperation, + taskId, + data, + kill + } = message + if (statistics != null) { // Statistics message received - this.statistics = message.statistics - } else if (message.checkActive != null) { + this.statistics = statistics + } else if (checkActive != null) { // Check active message received - message.checkActive ? this.startCheckActive() : this.stopCheckActive() - } else if (message.taskFunctionOperation != null) { + checkActive ? this.startCheckActive() : this.stopCheckActive() + } else if (taskFunctionOperation != null) { // Task function operation message received this.handleTaskFunctionOperationMessage(message) - } else if (message.taskId != null && message.data != null) { + } else if (taskId != null && data != null) { // Task message received this.run(message) - } else if (message.kill === true) { + } else if (kill === true) { // Kill message received this.handleKillMessage(message) } @@ -323,24 +353,34 @@ export abstract class AbstractWorker< protected handleTaskFunctionOperationMessage ( message: MessageValue ): void { - const { taskFunctionOperation, taskFunctionName, taskFunction } = message - let response!: TaskFunctionOperationResult + const { taskFunctionOperation, taskFunctionProperties, taskFunction } = + message + if (taskFunctionProperties == null) { + throw new Error( + 'Cannot handle task function operation message without task function properties' + ) + } + let response: TaskFunctionOperationResult switch (taskFunctionOperation) { case 'add': - response = this.addTaskFunction( - taskFunctionName as string, + response = this.addTaskFunction(taskFunctionProperties.name, { // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func - new Function(`return ${taskFunction as string}`)() as TaskFunction< - Data, - Response - > - ) + taskFunction: new Function( + `return ${taskFunction}` + )() as TaskFunction, + ...(taskFunctionProperties.priority != null && { + priority: taskFunctionProperties.priority + }), + ...(taskFunctionProperties.strategy != null && { + strategy: taskFunctionProperties.strategy + }) + }) break case 'remove': - response = this.removeTaskFunction(taskFunctionName as string) + response = this.removeTaskFunction(taskFunctionProperties.name) break case 'default': - response = this.setDefaultTaskFunction(taskFunctionName as string) + response = this.setDefaultTaskFunction(taskFunctionProperties.name) break default: response = { status: false, error: new Error('Unknown task operation') } @@ -349,11 +389,11 @@ export abstract class AbstractWorker< this.sendToMainWorker({ taskFunctionOperation, taskFunctionOperationStatus: response.status, - taskFunctionName, + taskFunctionProperties, ...(!response.status && - response?.error != null && { + response.error != null && { workerError: { - name: taskFunctionName as string, + name: taskFunctionProperties.name, message: this.handleError(response.error as Error | string) } }) @@ -368,7 +408,7 @@ export abstract class AbstractWorker< protected handleKillMessage (_message: MessageValue): void { this.stopCheckActive() if (isAsyncFunction(this.opts.killHandler)) { - (this.opts.killHandler?.() as Promise) + (this.opts.killHandler() as Promise) .then(() => { this.sendToMainWorker({ kill: 'success' }) return undefined @@ -459,11 +499,11 @@ export abstract class AbstractWorker< ): void /** - * Sends task function names to the main worker. + * Sends task functions properties to the main worker. */ - protected sendTaskFunctionNamesToMainWorker (): void { + protected sendTaskFunctionsPropertiesToMainWorker (): void { this.sendToMainWorker({ - taskFunctionNames: this.listTaskFunctionNames() + taskFunctionsProperties: this.listTaskFunctionsProperties() }) } @@ -482,21 +522,22 @@ export abstract class AbstractWorker< * * @param task - The task to execute. */ - protected run (task: Task): void { + protected readonly run = (task: Task): void => { const { name, taskId, data } = task const taskFunctionName = name ?? DEFAULT_TASK_NAME if (!this.taskFunctions.has(taskFunctionName)) { this.sendToMainWorker({ workerError: { - name: name as string, - message: `Task function '${name as string}' not found`, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + name: name!, + message: `Task function '${name}' not found`, data }, taskId }) return } - const fn = this.taskFunctions.get(taskFunctionName) + const fn = this.taskFunctions.get(taskFunctionName)?.taskFunction if (isAsyncFunction(fn)) { this.runAsync(fn as TaskAsyncFunction, task) } else { @@ -510,10 +551,10 @@ export abstract class AbstractWorker< * @param fn - Task function that will be executed. * @param task - Input data for the task function. */ - protected runSync ( + protected readonly runSync = ( fn: TaskSyncFunction, task: Task - ): void { + ): void => { const { name, taskId, data } = task try { let taskPerformance = this.beginTaskPerformance(name) @@ -527,7 +568,8 @@ export abstract class AbstractWorker< } catch (error) { this.sendToMainWorker({ workerError: { - name: name as string, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + name: name!, message: this.handleError(error as Error | string), data }, @@ -544,10 +586,10 @@ export abstract class AbstractWorker< * @param fn - Task function that will be executed. * @param task - Input data for the task function. */ - protected runAsync ( + protected readonly runAsync = ( fn: TaskAsyncFunction, task: Task - ): void { + ): void => { const { name, taskId, data } = task let taskPerformance = this.beginTaskPerformance(name) fn(data) @@ -560,10 +602,11 @@ export abstract class AbstractWorker< }) return undefined }) - .catch(error => { + .catch((error: unknown) => { this.sendToMainWorker({ workerError: { - name: name as string, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + name: name!, message: this.handleError(error as Error | string), data }, @@ -577,18 +620,24 @@ export abstract class AbstractWorker< } private beginTaskPerformance (name?: string): TaskPerformance { - this.checkStatistics() + if (this.statistics == null) { + throw new Error('Performance statistics computation requirements not set') + } return { name: name ?? DEFAULT_TASK_NAME, timestamp: performance.now(), - ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) + ...(this.statistics.elu && { + elu: performance.eventLoopUtilization() + }) } } private endTaskPerformance ( taskPerformance: TaskPerformance ): TaskPerformance { - this.checkStatistics() + if (this.statistics == null) { + throw new Error('Performance statistics computation requirements not set') + } return { ...taskPerformance, ...(this.statistics.runTime && { @@ -600,12 +649,6 @@ export abstract class AbstractWorker< } } - private checkStatistics (): void { - if (this.statistics == null) { - throw new Error('Performance statistics computation requirements not set') - } - } - private updateLastTaskTimestamp (): void { if (this.activeInterval != null) { this.lastTaskTimestamp = performance.now()