DEFAULT_TASK_NAME,
DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
EMPTY_FUNCTION,
+ average,
isKillBehavior,
isPlainObject,
+ max,
median,
+ min,
round,
updateMeasurementStatistics
} from '../utils'
import { KillBehaviors } from '../worker/worker-options'
+import type { TaskFunction } from '../worker/task-functions'
import {
type IPool,
PoolEmitter,
Response
>
+ /**
+ * Dynamic pool maximum size property placeholder.
+ */
+ protected readonly max?: number
+
/**
* Whether the pool is starting or not.
*/
private readonly starting: boolean
+ /**
+ * Whether the pool is started or not.
+ */
+ private started: boolean
/**
* The start timestamp of the pool.
*/
this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
this.executeTask = this.executeTask.bind(this)
this.enqueueTask = this.enqueueTask.bind(this)
- this.dequeueTask = this.dequeueTask.bind(this)
- this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
if (this.opts.enableEvents === true) {
this.emitter = new PoolEmitter()
this.starting = true
this.startPool()
this.starting = false
+ this.started = true
this.startTimestamp = performance.now()
}
protected checkDynamicPoolSize (min: number, max: number): void {
if (this.type === PoolTypes.dynamic) {
if (max == null) {
- throw new Error(
+ throw new TypeError(
'Cannot instantiate a dynamic pool without specifying the maximum pool size'
)
} else if (!Number.isSafeInteger(max)) {
)
}
if (
- workerChoiceStrategyOptions.choiceRetries != null &&
- !Number.isSafeInteger(workerChoiceStrategyOptions.choiceRetries)
+ workerChoiceStrategyOptions.retries != null &&
+ !Number.isSafeInteger(workerChoiceStrategyOptions.retries)
) {
throw new TypeError(
- 'Invalid worker choice strategy options: choice retries must be an integer'
+ 'Invalid worker choice strategy options: retries must be an integer'
)
}
if (
- workerChoiceStrategyOptions.choiceRetries != null &&
- workerChoiceStrategyOptions.choiceRetries <= 0
+ workerChoiceStrategyOptions.retries != null &&
+ workerChoiceStrategyOptions.retries < 0
) {
throw new RangeError(
- `Invalid worker choice strategy options: choice retries '${workerChoiceStrategyOptions.choiceRetries}' must be greater than zero`
+ `Invalid worker choice strategy options: retries '${workerChoiceStrategyOptions.retries}' must be greater or equal than zero`
)
}
if (
}
if (
tasksQueueOptions?.concurrency != null &&
- !Number.isSafeInteger(tasksQueueOptions.concurrency)
+ !Number.isSafeInteger(tasksQueueOptions?.concurrency)
) {
throw new TypeError(
- 'Invalid worker tasks concurrency: must be an integer'
+ 'Invalid worker node tasks concurrency: must be an integer'
)
}
if (
tasksQueueOptions?.concurrency != null &&
- tasksQueueOptions.concurrency <= 0
+ tasksQueueOptions?.concurrency <= 0
) {
+ throw new RangeError(
+ `Invalid worker node tasks concurrency: ${tasksQueueOptions?.concurrency} is a negative integer or zero`
+ )
+ }
+ if (tasksQueueOptions?.queueMaxSize != null) {
throw new Error(
- `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
+ 'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
+ )
+ }
+ if (
+ tasksQueueOptions?.size != null &&
+ !Number.isSafeInteger(tasksQueueOptions?.size)
+ ) {
+ throw new TypeError(
+ 'Invalid worker node tasks queue size: must be an integer'
+ )
+ }
+ if (tasksQueueOptions?.size != null && tasksQueueOptions?.size <= 0) {
+ throw new RangeError(
+ `Invalid worker node tasks queue size: ${tasksQueueOptions?.size} is a negative integer or zero`
)
}
}
0
)
}),
+ ...(this.opts.enableTasksQueue === true && {
+ backPressure: this.hasBackPressure()
+ }),
+ ...(this.opts.enableTasksQueue === true && {
+ stolenTasks: this.workerNodes.reduce(
+ (accumulator, workerNode) =>
+ accumulator + workerNode.usage.tasks.stolen,
+ 0
+ )
+ }),
failedTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + workerNode.usage.tasks.failed,
.runTime.aggregate && {
runTime: {
minimum: round(
- Math.min(
+ min(
...this.workerNodes.map(
- (workerNode) => workerNode.usage.runTime?.minimum ?? Infinity
+ workerNode => workerNode.usage.runTime?.minimum ?? Infinity
)
)
),
maximum: round(
- Math.max(
+ max(
...this.workerNodes.map(
- (workerNode) => workerNode.usage.runTime?.maximum ?? -Infinity
+ workerNode => workerNode.usage.runTime?.maximum ?? -Infinity
)
)
),
- average: round(
- this.workerNodes.reduce(
- (accumulator, workerNode) =>
- accumulator + (workerNode.usage.runTime?.aggregate ?? 0),
- 0
- ) /
- this.workerNodes.reduce(
- (accumulator, workerNode) =>
- accumulator + (workerNode.usage.tasks?.executed ?? 0),
- 0
+ ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
+ .runTime.average && {
+ average: round(
+ average(
+ this.workerNodes.reduce<number[]>(
+ (accumulator, workerNode) =>
+ accumulator.concat(workerNode.usage.runTime.history),
+ []
+ )
)
- ),
+ )
+ }),
...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
.runTime.median && {
median: round(
median(
- this.workerNodes.map(
- (workerNode) => workerNode.usage.runTime?.median ?? 0
+ this.workerNodes.reduce<number[]>(
+ (accumulator, workerNode) =>
+ accumulator.concat(workerNode.usage.runTime.history),
+ []
)
)
)
.waitTime.aggregate && {
waitTime: {
minimum: round(
- Math.min(
+ min(
...this.workerNodes.map(
- (workerNode) => workerNode.usage.waitTime?.minimum ?? Infinity
+ workerNode => workerNode.usage.waitTime?.minimum ?? Infinity
)
)
),
maximum: round(
- Math.max(
+ max(
...this.workerNodes.map(
- (workerNode) => workerNode.usage.waitTime?.maximum ?? -Infinity
+ workerNode => workerNode.usage.waitTime?.maximum ?? -Infinity
)
)
),
- average: round(
- this.workerNodes.reduce(
- (accumulator, workerNode) =>
- accumulator + (workerNode.usage.waitTime?.aggregate ?? 0),
- 0
- ) /
- this.workerNodes.reduce(
- (accumulator, workerNode) =>
- accumulator + (workerNode.usage.tasks?.executed ?? 0),
- 0
+ ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
+ .waitTime.average && {
+ average: round(
+ average(
+ this.workerNodes.reduce<number[]>(
+ (accumulator, workerNode) =>
+ accumulator.concat(workerNode.usage.waitTime.history),
+ []
+ )
)
- ),
+ )
+ }),
...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
.waitTime.median && {
median: round(
median(
- this.workerNodes.map(
- (workerNode) => workerNode.usage.waitTime?.median ?? 0
+ this.workerNodes.reduce<number[]>(
+ (accumulator, workerNode) =>
+ accumulator.concat(workerNode.usage.waitTime.history),
+ []
)
)
)
/**
* The pool minimum size.
*/
- protected abstract get minSize (): number
+ protected get minSize (): number {
+ return this.numberOfWorkers
+ }
/**
* The pool maximum size.
*/
- protected abstract get maxSize (): number
+ protected get maxSize (): number {
+ return this.max ?? this.numberOfWorkers
+ }
/**
* Checks if the worker id sent in the received message from a worker is valid.
*/
private getWorkerNodeKeyByWorker (worker: Worker): number {
return this.workerNodes.findIndex(
- (workerNode) => workerNode.worker === worker
+ workerNode => workerNode.worker === worker
)
}
*/
private getWorkerNodeKeyByWorkerId (workerId: number): number {
return this.workerNodes.findIndex(
- (workerNode) => workerNode.info.id === workerId
+ workerNode => workerNode.info.id === workerId
)
}
this.checkValidTasksQueueOptions(tasksQueueOptions)
this.opts.tasksQueueOptions =
this.buildTasksQueueOptions(tasksQueueOptions)
+ this.setTasksQueueSize(this.opts.tasksQueueOptions.size as number)
} else if (this.opts.tasksQueueOptions != null) {
delete this.opts.tasksQueueOptions
}
}
+ private setTasksQueueSize (size: number): void {
+ for (const workerNode of this.workerNodes) {
+ workerNode.tasksQueueBackPressureSize = size
+ }
+ }
+
private buildTasksQueueOptions (
tasksQueueOptions: TasksQueueOptions
): TasksQueueOptions {
return {
- concurrency: tasksQueueOptions?.concurrency ?? 1
+ ...{
+ size: Math.pow(this.maxSize, 2),
+ concurrency: 1
+ },
+ ...tasksQueueOptions
}
}
if (this.opts.enableTasksQueue === true) {
return (
this.workerNodes.findIndex(
- (workerNode) =>
+ workerNode =>
workerNode.info.ready &&
workerNode.usage.tasks.executing <
(this.opts.tasksQueueOptions?.concurrency as number)
} else {
return (
this.workerNodes.findIndex(
- (workerNode) =>
+ workerNode =>
workerNode.info.ready && workerNode.usage.tasks.executing === 0
) === -1
)
}
}
+ private async sendTaskFunctionOperationToWorker (
+ message: Omit<MessageValue<Data>, 'workerId'>
+ ): Promise<boolean> {
+ return await new Promise<boolean>((resolve, reject) => {
+ const responsesReceived = new Array<MessageValue<Data | Response>>()
+ for (const [workerNodeKey] of this.workerNodes.entries()) {
+ this.registerWorkerMessageListener(workerNodeKey, message => {
+ if (message.taskFunctionOperationStatus != null) {
+ responsesReceived.push(message)
+ if (
+ responsesReceived.length === this.workerNodes.length &&
+ responsesReceived.every(
+ message => message.taskFunctionOperationStatus === true
+ )
+ ) {
+ resolve(true)
+ } else if (
+ responsesReceived.length === this.workerNodes.length &&
+ responsesReceived.some(
+ message => message.taskFunctionOperationStatus === false
+ )
+ ) {
+ reject(
+ new Error(
+ `Task function operation ${
+ message.taskFunctionOperation as string
+ } failed on worker ${message.workerId}`
+ )
+ )
+ }
+ }
+ })
+ this.sendToWorker(workerNodeKey, {
+ ...message,
+ workerId: this.getWorkerInfo(workerNodeKey).id as number
+ })
+ }
+ })
+ }
+
/** @inheritDoc */
- public listTaskFunctions (): string[] {
+ public hasTaskFunction (name: string): boolean {
for (const workerNode of this.workerNodes) {
if (
- Array.isArray(workerNode.info.taskFunctions) &&
- workerNode.info.taskFunctions.length > 0
+ Array.isArray(workerNode.info.taskFunctionNames) &&
+ workerNode.info.taskFunctionNames.includes(name)
) {
- return workerNode.info.taskFunctions
+ return true
+ }
+ }
+ return false
+ }
+
+ /** @inheritDoc */
+ public async addTaskFunction (
+ name: string,
+ taskFunction: TaskFunction
+ ): Promise<boolean> {
+ return await this.sendTaskFunctionOperationToWorker({
+ taskFunctionOperation: 'add',
+ taskFunctionName: name,
+ taskFunction: taskFunction.toString()
+ })
+ }
+
+ /** @inheritDoc */
+ public async removeTaskFunction (name: string): Promise<boolean> {
+ return await this.sendTaskFunctionOperationToWorker({
+ taskFunctionOperation: 'remove',
+ taskFunctionName: name
+ })
+ }
+
+ /** @inheritDoc */
+ public listTaskFunctionNames (): string[] {
+ for (const workerNode of this.workerNodes) {
+ if (
+ Array.isArray(workerNode.info.taskFunctionNames) &&
+ workerNode.info.taskFunctionNames.length > 0
+ ) {
+ return workerNode.info.taskFunctionNames
}
}
return []
}
+ /** @inheritDoc */
+ public async setDefaultTaskFunction (name: string): Promise<boolean> {
+ return await this.sendTaskFunctionOperationToWorker({
+ taskFunctionOperation: 'default',
+ taskFunctionName: name
+ })
+ }
+
+ private shallExecuteTask (workerNodeKey: number): boolean {
+ return (
+ this.tasksQueueSize(workerNodeKey) === 0 &&
+ this.workerNodes[workerNodeKey].usage.tasks.executing <
+ (this.opts.tasksQueueOptions?.concurrency as number)
+ )
+ }
+
/** @inheritDoc */
public async execute (
data?: Data,
transferList?: TransferListItem[]
): Promise<Response> {
return await new Promise<Response>((resolve, reject) => {
+ if (!this.started) {
+ reject(new Error('Cannot execute a task on destroyed pool'))
+ return
+ }
if (name != null && typeof name !== 'string') {
reject(new TypeError('name argument must be a string'))
+ return
}
if (
name != null &&
name.trim().length === 0
) {
reject(new TypeError('name argument must not be an empty string'))
+ return
}
if (transferList != null && !Array.isArray(transferList)) {
reject(new TypeError('transferList argument must be an array'))
+ return
}
const timestamp = performance.now()
const workerNodeKey = this.chooseWorkerNode()
- const workerInfo = this.getWorkerInfo(workerNodeKey)
- if (
- name != null &&
- Array.isArray(workerInfo.taskFunctions) &&
- !workerInfo.taskFunctions.includes(name)
- ) {
- reject(
- new Error(`Task function '${name}' is not registered in the pool`)
- )
- }
const task: Task<Data> = {
name: name ?? DEFAULT_TASK_NAME,
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
data: data ?? ({} as Data),
transferList,
timestamp,
- workerId: workerInfo.id as number,
+ workerId: this.getWorkerInfo(workerNodeKey).id as number,
taskId: randomUUID()
}
this.promiseResponseMap.set(task.taskId as string, {
if (
this.opts.enableTasksQueue === false ||
(this.opts.enableTasksQueue === true &&
- this.workerNodes[workerNodeKey].usage.tasks.executing <
- (this.opts.tasksQueueOptions?.concurrency as number))
+ this.shallExecuteTask(workerNodeKey))
) {
this.executeTask(workerNodeKey, task)
} else {
this.enqueueTask(workerNodeKey, task)
}
- this.checkAndEmitEvents()
})
}
await this.destroyWorkerNode(workerNodeKey)
})
)
- this.emitter?.emit(PoolEvents.destroy)
+ this.emitter?.emit(PoolEvents.destroy, this.info)
+ this.started = false
}
protected async sendKillMessageToWorker (
workerId: number
): Promise<void> {
await new Promise<void>((resolve, reject) => {
- this.registerWorkerMessageListener(workerNodeKey, (message) => {
+ this.registerWorkerMessageListener(workerNodeKey, message => {
if (message.kill === 'success') {
resolve()
} else if (message.kill === 'failure') {
* @virtual
*/
protected setupHook (): void {
- // Intentionally empty
+ /* Intentionally empty */
}
/**
workerNodeKey: number,
task: Task<Data>
): void {
- const workerUsage = this.workerNodes[workerNodeKey].usage
- ++workerUsage.tasks.executing
- this.updateWaitTimeWorkerUsage(workerUsage, task)
- if (this.canUpdateTaskWorkerUsage(workerNodeKey)) {
- const taskWorkerUsage = this.workerNodes[
+ if (this.workerNodes[workerNodeKey]?.usage != null) {
+ const workerUsage = this.workerNodes[workerNodeKey].usage
+ ++workerUsage.tasks.executing
+ this.updateWaitTimeWorkerUsage(workerUsage, task)
+ }
+ if (
+ this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
+ this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
+ task.name as string
+ ) != null
+ ) {
+ const taskFunctionWorkerUsage = this.workerNodes[
workerNodeKey
- ].getTaskWorkerUsage(task.name as string) as WorkerUsage
- ++taskWorkerUsage.tasks.executing
- this.updateWaitTimeWorkerUsage(taskWorkerUsage, task)
+ ].getTaskFunctionWorkerUsage(task.name as string) as WorkerUsage
+ ++taskFunctionWorkerUsage.tasks.executing
+ this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage, task)
}
}
workerNodeKey: number,
message: MessageValue<Response>
): void {
- const workerUsage = this.workerNodes[workerNodeKey].usage
- this.updateTaskStatisticsWorkerUsage(workerUsage, message)
- this.updateRunTimeWorkerUsage(workerUsage, message)
- this.updateEluWorkerUsage(workerUsage, message)
- if (this.canUpdateTaskWorkerUsage(workerNodeKey)) {
- const taskWorkerUsage = this.workerNodes[
+ if (this.workerNodes[workerNodeKey]?.usage != null) {
+ const workerUsage = this.workerNodes[workerNodeKey].usage
+ this.updateTaskStatisticsWorkerUsage(workerUsage, message)
+ this.updateRunTimeWorkerUsage(workerUsage, message)
+ this.updateEluWorkerUsage(workerUsage, message)
+ }
+ if (
+ this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
+ this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
+ message.taskPerformance?.name as string
+ ) != null
+ ) {
+ const taskFunctionWorkerUsage = this.workerNodes[
workerNodeKey
- ].getTaskWorkerUsage(
- message.taskPerformance?.name ?? DEFAULT_TASK_NAME
+ ].getTaskFunctionWorkerUsage(
+ message.taskPerformance?.name as string
) as WorkerUsage
- this.updateTaskStatisticsWorkerUsage(taskWorkerUsage, message)
- this.updateRunTimeWorkerUsage(taskWorkerUsage, message)
- this.updateEluWorkerUsage(taskWorkerUsage, message)
+ this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
+ this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage, message)
+ this.updateEluWorkerUsage(taskFunctionWorkerUsage, message)
}
}
- private canUpdateTaskWorkerUsage (workerNodeKey: number): boolean {
+ /**
+ * Whether the worker node shall update its task function worker usage or not.
+ *
+ * @param workerNodeKey - The worker node key.
+ * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
+ */
+ private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
const workerInfo = this.getWorkerInfo(workerNodeKey)
return (
- Array.isArray(workerInfo.taskFunctions) &&
- workerInfo.taskFunctions.length > 1
+ workerInfo != null &&
+ Array.isArray(workerInfo.taskFunctionNames) &&
+ workerInfo.taskFunctionNames.length > 2
)
}
message: MessageValue<Response>
): void {
const workerTaskStatistics = workerUsage.tasks
- --workerTaskStatistics.executing
- if (message.taskError == null) {
+ if (
+ workerTaskStatistics.executing != null &&
+ workerTaskStatistics.executing > 0
+ ) {
+ --workerTaskStatistics.executing
+ }
+ if (message.workerError == null) {
++workerTaskStatistics.executed
} else {
++workerTaskStatistics.failed
workerUsage: WorkerUsage,
message: MessageValue<Response>
): void {
+ if (message.workerError != null) {
+ return
+ }
updateMeasurementStatistics(
workerUsage.runTime,
this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime,
- message.taskPerformance?.runTime ?? 0,
- workerUsage.tasks.executed
+ message.taskPerformance?.runTime ?? 0
)
}
updateMeasurementStatistics(
workerUsage.waitTime,
this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime,
- taskWaitTime,
- workerUsage.tasks.executed
+ taskWaitTime
)
}
workerUsage: WorkerUsage,
message: MessageValue<Response>
): void {
+ if (message.workerError != null) {
+ return
+ }
const eluTaskStatisticsRequirements: MeasurementStatisticsRequirements =
this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
updateMeasurementStatistics(
workerUsage.elu.active,
eluTaskStatisticsRequirements,
- message.taskPerformance?.elu?.active ?? 0,
- workerUsage.tasks.executed
+ message.taskPerformance?.elu?.active ?? 0
)
updateMeasurementStatistics(
workerUsage.elu.idle,
eluTaskStatisticsRequirements,
- message.taskPerformance?.elu?.idle ?? 0,
- workerUsage.tasks.executed
+ message.taskPerformance?.elu?.idle ?? 0
)
if (eluTaskStatisticsRequirements.aggregate) {
if (message.taskPerformance?.elu != null) {
if (this.shallCreateDynamicWorker()) {
const workerNodeKey = this.createAndSetupDynamicWorkerNode()
if (
- this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker
+ this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
) {
return workerNodeKey
}
worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
- worker.on('error', (error) => {
+ worker.on('error', error => {
const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
const workerInfo = this.getWorkerInfo(workerNodeKey)
workerInfo.ready = false
this.workerNodes[workerNodeKey].closeChannel()
this.emitter?.emit(PoolEvents.error, error)
- if (this.opts.restartWorkerOnError === true && !this.starting) {
+ if (
+ this.opts.restartWorkerOnError === true &&
+ this.started &&
+ !this.starting
+ ) {
if (workerInfo.dynamic) {
this.createAndSetupDynamicWorkerNode()
} else {
*/
protected createAndSetupDynamicWorkerNode (): number {
const workerNodeKey = this.createAndSetupWorkerNode()
- this.registerWorkerMessageListener(workerNodeKey, (message) => {
+ this.registerWorkerMessageListener(workerNodeKey, message => {
const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
message.workerId
)
workerUsage.tasks.executing === 0 &&
this.tasksQueueSize(localWorkerNodeKey) === 0)))
) {
- this.destroyWorkerNode(localWorkerNodeKey).catch((error) => {
+ this.destroyWorkerNode(localWorkerNodeKey).catch(error => {
this.emitter?.emit(PoolEvents.error, error)
})
}
workerId: workerInfo.id as number
})
workerInfo.dynamic = true
- if (this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker) {
+ if (
+ this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerReady ||
+ this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
+ ) {
workerInfo.ready = true
}
+ this.checkAndEmitDynamicWorkerCreationEvents()
return workerNodeKey
}
this.sendStartupMessageToWorker(workerNodeKey)
// Send the statistics message to worker.
this.sendStatisticsMessageToWorker(workerNodeKey)
+ if (this.opts.enableTasksQueue === true) {
+ this.workerNodes[workerNodeKey].onEmptyQueue =
+ this.taskStealingOnEmptyQueue.bind(this)
+ this.workerNodes[workerNodeKey].onBackPressure =
+ this.tasksStealingOnBackPressure.bind(this)
+ }
}
/**
private redistributeQueuedTasks (workerNodeKey: number): void {
while (this.tasksQueueSize(workerNodeKey) > 0) {
- let targetWorkerNodeKey: number = workerNodeKey
- let minQueuedTasks = Infinity
- let executeTask = false
- for (const [workerNodeId, workerNode] of this.workerNodes.entries()) {
- const workerInfo = this.getWorkerInfo(workerNodeId)
- if (
- workerNodeId !== workerNodeKey &&
- workerInfo.ready &&
- workerNode.usage.tasks.queued === 0
- ) {
- if (
- this.workerNodes[workerNodeId].usage.tasks.executing <
- (this.opts.tasksQueueOptions?.concurrency as number)
- ) {
- executeTask = true
- }
- targetWorkerNodeKey = workerNodeId
- break
- }
- if (
- workerNodeId !== workerNodeKey &&
- workerInfo.ready &&
- workerNode.usage.tasks.queued < minQueuedTasks
- ) {
- minQueuedTasks = workerNode.usage.tasks.queued
- targetWorkerNodeKey = workerNodeId
- }
+ const destinationWorkerNodeKey = this.workerNodes.reduce(
+ (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
+ return workerNode.info.ready &&
+ workerNode.usage.tasks.queued <
+ workerNodes[minWorkerNodeKey].usage.tasks.queued
+ ? workerNodeKey
+ : minWorkerNodeKey
+ },
+ 0
+ )
+ const destinationWorkerNode = this.workerNodes[destinationWorkerNodeKey]
+ const task = {
+ ...(this.dequeueTask(workerNodeKey) as Task<Data>),
+ workerId: destinationWorkerNode.info.id as number
}
- if (executeTask) {
- this.executeTask(
- targetWorkerNodeKey,
- this.dequeueTask(workerNodeKey) as Task<Data>
- )
+ if (this.shallExecuteTask(destinationWorkerNodeKey)) {
+ this.executeTask(destinationWorkerNodeKey, task)
} else {
- this.enqueueTask(
- targetWorkerNodeKey,
- this.dequeueTask(workerNodeKey) as Task<Data>
+ this.enqueueTask(destinationWorkerNodeKey, task)
+ }
+ }
+ }
+
+ private updateTaskStolenStatisticsWorkerUsage (
+ workerNodeKey: number,
+ taskName: string
+ ): void {
+ const workerNode = this.workerNodes[workerNodeKey]
+ if (workerNode?.usage != null) {
+ ++workerNode.usage.tasks.stolen
+ }
+ if (
+ this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
+ workerNode.getTaskFunctionWorkerUsage(taskName) != null
+ ) {
+ const taskFunctionWorkerUsage = workerNode.getTaskFunctionWorkerUsage(
+ taskName
+ ) as WorkerUsage
+ ++taskFunctionWorkerUsage.tasks.stolen
+ }
+ }
+
+ private taskStealingOnEmptyQueue (workerId: number): void {
+ const destinationWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
+ const destinationWorkerNode = this.workerNodes[destinationWorkerNodeKey]
+ const workerNodes = this.workerNodes
+ .slice()
+ .sort(
+ (workerNodeA, workerNodeB) =>
+ workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued
+ )
+ const sourceWorkerNode = workerNodes.find(
+ workerNode =>
+ workerNode.info.ready &&
+ workerNode.info.id !== workerId &&
+ workerNode.usage.tasks.queued > 0
+ )
+ if (sourceWorkerNode != null) {
+ const task = {
+ ...(sourceWorkerNode.popTask() as Task<Data>),
+ workerId: destinationWorkerNode.info.id as number
+ }
+ if (this.shallExecuteTask(destinationWorkerNodeKey)) {
+ this.executeTask(destinationWorkerNodeKey, task)
+ } else {
+ this.enqueueTask(destinationWorkerNodeKey, task)
+ }
+ this.updateTaskStolenStatisticsWorkerUsage(
+ destinationWorkerNodeKey,
+ task.name as string
+ )
+ }
+ }
+
+ private tasksStealingOnBackPressure (workerId: number): void {
+ const sizeOffset = 1
+ if ((this.opts.tasksQueueOptions?.size as number) <= sizeOffset) {
+ return
+ }
+ const sourceWorkerNode =
+ this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
+ const workerNodes = this.workerNodes
+ .slice()
+ .sort(
+ (workerNodeA, workerNodeB) =>
+ workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
+ )
+ for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
+ if (
+ sourceWorkerNode.usage.tasks.queued > 0 &&
+ workerNode.info.ready &&
+ workerNode.info.id !== workerId &&
+ workerNode.usage.tasks.queued <
+ (this.opts.tasksQueueOptions?.size as number) - sizeOffset
+ ) {
+ const task = {
+ ...(sourceWorkerNode.popTask() as Task<Data>),
+ workerId: workerNode.info.id as number
+ }
+ if (this.shallExecuteTask(workerNodeKey)) {
+ this.executeTask(workerNodeKey, task)
+ } else {
+ this.enqueueTask(workerNodeKey, task)
+ }
+ this.updateTaskStolenStatisticsWorkerUsage(
+ workerNodeKey,
+ task.name as string
)
}
}
* @returns The listener function to execute when a message is received from a worker.
*/
protected workerListener (): (message: MessageValue<Response>) => void {
- return (message) => {
+ return message => {
this.checkMessageWorkerId(message)
- if (message.ready != null && message.taskFunctions != null) {
+ if (message.ready != null && message.taskFunctionNames != null) {
// Worker ready response received from worker
this.handleWorkerReadyResponse(message)
} else if (message.taskId != null) {
// Task execution response received from worker
this.handleTaskExecutionResponse(message)
- } else if (message.taskFunctions != null) {
- // Task functions message received from worker
+ } else if (message.taskFunctionNames != null) {
+ // Task function names message received from worker
this.getWorkerInfo(
this.getWorkerNodeKeyByWorkerId(message.workerId)
- ).taskFunctions = message.taskFunctions
+ ).taskFunctionNames = message.taskFunctionNames
+ } else if (message.taskFunctionOperation != null) {
+ // Task function operation response received from worker
}
}
}
this.getWorkerNodeKeyByWorkerId(message.workerId)
)
workerInfo.ready = message.ready as boolean
- workerInfo.taskFunctions = message.taskFunctions
+ workerInfo.taskFunctionNames = message.taskFunctionNames
if (this.emitter != null && this.ready) {
this.emitter.emit(PoolEvents.ready, this.info)
}
}
private handleTaskExecutionResponse (message: MessageValue<Response>): void {
- const { taskId, taskError, data } = message
+ const { taskId, workerError, data } = message
const promiseResponse = this.promiseResponseMap.get(taskId as string)
if (promiseResponse != null) {
- if (taskError != null) {
- this.emitter?.emit(PoolEvents.taskError, taskError)
- promiseResponse.reject(taskError.message)
+ if (workerError != null) {
+ this.emitter?.emit(PoolEvents.taskError, workerError)
+ promiseResponse.reject(workerError.message)
} else {
promiseResponse.resolve(data as Response)
}
const workerNodeKey = promiseResponse.workerNodeKey
this.afterTaskExecutionHook(workerNodeKey, message)
+ this.workerChoiceStrategyContext.update(workerNodeKey)
this.promiseResponseMap.delete(taskId as string)
if (
this.opts.enableTasksQueue === true &&
this.dequeueTask(workerNodeKey) as Task<Data>
)
}
- this.workerChoiceStrategyContext.update(workerNodeKey)
}
}
- private checkAndEmitEvents (): void {
- if (this.emitter != null) {
- if (this.busy) {
- this.emitter.emit(PoolEvents.busy, this.info)
- }
- if (this.type === PoolTypes.dynamic && this.full) {
- this.emitter.emit(PoolEvents.full, this.info)
+ private checkAndEmitTaskExecutionEvents (): void {
+ if (this.busy) {
+ this.emitter?.emit(PoolEvents.busy, this.info)
+ }
+ }
+
+ private checkAndEmitTaskQueuingEvents (): void {
+ if (this.hasBackPressure()) {
+ this.emitter?.emit(PoolEvents.backPressure, this.info)
+ }
+ }
+
+ private checkAndEmitDynamicWorkerCreationEvents (): void {
+ if (this.type === PoolTypes.dynamic) {
+ if (this.full) {
+ this.emitter?.emit(PoolEvents.full, this.info)
}
}
}
private addWorkerNode (worker: Worker): number {
const workerNode = new WorkerNode<Worker, Data>(
worker,
- this.worker,
- this.maxSize
+ this.opts.tasksQueueOptions?.size ?? Math.pow(this.maxSize, 2)
)
// Flag the worker node as ready at pool startup.
if (this.starting) {
this.workerNodes.push(workerNode)
const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
if (workerNodeKey === -1) {
- throw new Error('Worker node added not found')
+ throw new Error('Worker added not found in worker nodes')
}
return workerNodeKey
}
/** @inheritDoc */
public hasWorkerNodeBackPressure (workerNodeKey: number): boolean {
- if (
+ return (
this.opts.enableTasksQueue === true &&
this.workerNodes[workerNodeKey].hasBackPressure()
- ) {
- return true
- }
- return false
+ )
+ }
+
+ private hasBackPressure (): boolean {
+ return (
+ this.opts.enableTasksQueue === true &&
+ this.workerNodes.findIndex(
+ workerNode => !workerNode.hasBackPressure()
+ ) === -1
+ )
}
/**
private executeTask (workerNodeKey: number, task: Task<Data>): void {
this.beforeTaskExecutionHook(workerNodeKey, task)
this.sendToWorker(workerNodeKey, task, task.transferList)
+ this.checkAndEmitTaskExecutionEvents()
}
private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task)
- if (this.hasWorkerNodeBackPressure(workerNodeKey)) {
- this.emitter?.emit(PoolEvents.backPressure, {
- workerId: this.getWorkerInfo(workerNodeKey).id,
- ...this.info
- })
- }
+ this.checkAndEmitTaskQueuingEvents()
return tasksQueueSize
}