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.checkAndEmitTaskExecutionEvents =
- this.checkAndEmitTaskExecutionEvents.bind(this)
- this.checkAndEmitTaskQueuingEvents =
- this.checkAndEmitTaskQueuingEvents.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)) {
!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
) {
- throw new Error(
- `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}' is a negative integer or zero`
+ throw new RangeError(
+ `Invalid worker node tasks concurrency: ${tasksQueueOptions.concurrency} is a negative integer or zero`
+ )
+ }
+ if (
+ tasksQueueOptions?.queueMaxSize != null &&
+ !Number.isSafeInteger(tasksQueueOptions.queueMaxSize)
+ ) {
+ throw new TypeError(
+ 'Invalid worker node tasks queue max size: must be an integer'
+ )
+ }
+ if (
+ tasksQueueOptions?.queueMaxSize != null &&
+ tasksQueueOptions.queueMaxSize <= 0
+ ) {
+ throw new RangeError(
+ `Invalid worker node tasks queue max size: ${tasksQueueOptions.queueMaxSize} is a negative integer or zero`
)
}
}
/**
* 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.
this.checkValidTasksQueueOptions(tasksQueueOptions)
this.opts.tasksQueueOptions =
this.buildTasksQueueOptions(tasksQueueOptions)
+ this.setTasksQueueMaxSize(
+ this.opts.tasksQueueOptions.queueMaxSize as number
+ )
} else if (this.opts.tasksQueueOptions != null) {
delete this.opts.tasksQueueOptions
}
}
+ private setTasksQueueMaxSize (queueMaxSize: number): void {
+ for (const workerNode of this.workerNodes) {
+ workerNode.tasksQueueBackPressureSize = queueMaxSize
+ }
+ }
+
private buildTasksQueueOptions (
tasksQueueOptions: TasksQueueOptions
): TasksQueueOptions {
return {
- concurrency: tasksQueueOptions?.concurrency ?? 1
+ ...{
+ queueMaxSize: Math.pow(this.maxSize, 2),
+ concurrency: 1
+ },
+ ...tasksQueueOptions
}
}
transferList?: TransferListItem[]
): Promise<Response> {
return await new Promise<Response>((resolve, reject) => {
+ if (!this.started) {
+ reject(new Error('Cannot execute a task on destroyed pool'))
+ }
if (name != null && typeof name !== 'string') {
reject(new TypeError('name argument must be a string'))
}
}
const timestamp = performance.now()
const workerNodeKey = this.chooseWorkerNode()
- const workerInfo = this.getWorkerInfo(workerNodeKey)
+ const workerInfo = this.getWorkerInfo(workerNodeKey) as WorkerInfo
if (
name != null &&
Array.isArray(workerInfo.taskFunctions) &&
await this.destroyWorkerNode(workerNodeKey)
})
)
- this.emitter?.emit(PoolEvents.destroy)
+ this.emitter?.emit(PoolEvents.destroy, this.info)
+ this.started = false
}
protected async sendKillMessageToWorker (
workerNodeKey: number,
task: Task<Data>
): void {
- const workerUsage = this.workerNodes[workerNodeKey].usage
- ++workerUsage.tasks.executing
- this.updateWaitTimeWorkerUsage(workerUsage, task)
- if (this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey)) {
+ 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
].getTaskFunctionWorkerUsage(task.name as string) as WorkerUsage
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.shallUpdateTaskFunctionWorkerUsage(workerNodeKey)) {
+ 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
].getTaskFunctionWorkerUsage(
- message.taskPerformance?.name ?? DEFAULT_TASK_NAME
+ message.taskPerformance?.name as string
) as WorkerUsage
this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage, message)
private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
const workerInfo = this.getWorkerInfo(workerNodeKey)
return (
+ workerInfo != null &&
Array.isArray(workerInfo.taskFunctions) &&
workerInfo.taskFunctions.length > 2
)
workerTaskStatistics.executing > 0
) {
--workerTaskStatistics.executing
- } else if (
- workerTaskStatistics.executing != null &&
- workerTaskStatistics.executing < 0
- ) {
- throw new Error(
- 'Worker usage statistic for tasks executing cannot be negative'
- )
}
if (message.taskError == null) {
++workerTaskStatistics.executed
if (this.shallCreateDynamicWorker()) {
const workerNodeKey = this.createAndSetupDynamicWorkerNode()
if (
- this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker
+ this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
) {
return workerNodeKey
}
worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
worker.on('error', (error) => {
const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
- const workerInfo = this.getWorkerInfo(workerNodeKey)
+ const workerInfo = this.getWorkerInfo(workerNodeKey) as WorkerInfo
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.starting &&
+ this.started
+ ) {
if (workerInfo.dynamic) {
this.createAndSetupDynamicWorkerNode()
} else {
})
}
})
- const workerInfo = this.getWorkerInfo(workerNodeKey)
+ const workerInfo = this.getWorkerInfo(workerNodeKey) as WorkerInfo
this.sendToWorker(workerNodeKey, {
checkActive: true,
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].onBackPressure =
+ this.tasksStealingOnBackPressure.bind(this)
+ }
}
/**
elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
.elu.aggregate
},
- workerId: this.getWorkerInfo(workerNodeKey).id as number
+ workerId: (this.getWorkerInfo(workerNodeKey) as WorkerInfo).id as number
})
}
private redistributeQueuedTasks (workerNodeKey: number): void {
+ const workerNodes = this.workerNodes.filter(
+ (_, workerNodeId) => workerNodeId !== workerNodeKey
+ )
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)
+ for (const [workerNodeId, workerNode] of workerNodes.entries()) {
if (
- workerNodeId !== workerNodeKey &&
- workerInfo.ready &&
- workerNode.usage.tasks.queued === 0
+ workerNode.usage.tasks.executing <
+ (this.opts.tasksQueueOptions?.concurrency as number)
) {
- if (
- this.workerNodes[workerNodeId].usage.tasks.executing <
- (this.opts.tasksQueueOptions?.concurrency as number)
- ) {
- executeTask = true
- }
+ executeTask = true
+ }
+ if (workerNode.info.ready && workerNode.usage.tasks.queued === 0) {
targetWorkerNodeKey = workerNodeId
break
}
if (
- workerNodeId !== workerNodeKey &&
- workerInfo.ready &&
+ workerNode.info.ready &&
workerNode.usage.tasks.queued < minQueuedTasks
) {
minQueuedTasks = workerNode.usage.tasks.queued
}
}
+ private tasksStealingOnBackPressure (workerId: number): void {
+ const sourceWorkerNode =
+ this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
+ const workerNodes = this.workerNodes
+ .filter((workerNode) => workerNode.info.id !== workerId)
+ .sort(
+ (workerNodeA, workerNodeB) =>
+ workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
+ )
+ for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
+ if (
+ workerNode.info.ready &&
+ sourceWorkerNode.usage.tasks.queued > 0 &&
+ !workerNode.hasBackPressure()
+ ) {
+ if (
+ workerNode.usage.tasks.executing <
+ (this.opts.tasksQueueOptions?.concurrency as number)
+ ) {
+ this.executeTask(
+ workerNodeKey,
+ sourceWorkerNode.popTask() as Task<Data>
+ )
+ } else {
+ this.enqueueTask(
+ workerNodeKey,
+ sourceWorkerNode.popTask() as Task<Data>
+ )
+ }
+ }
+ }
+ }
+
/**
* This method is the listener registered for each worker message.
*
this.handleTaskExecutionResponse(message)
} else if (message.taskFunctions != null) {
// Task functions message received from worker
- this.getWorkerInfo(
- this.getWorkerNodeKeyByWorkerId(message.workerId)
+ (
+ this.getWorkerInfo(
+ this.getWorkerNodeKeyByWorkerId(message.workerId)
+ ) as WorkerInfo
).taskFunctions = message.taskFunctions
}
}
}
const workerInfo = this.getWorkerInfo(
this.getWorkerNodeKeyByWorkerId(message.workerId)
- )
+ ) as WorkerInfo
workerInfo.ready = message.ready as boolean
workerInfo.taskFunctions = message.taskFunctions
if (this.emitter != null && this.ready) {
}
private checkAndEmitTaskExecutionEvents (): 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)
- }
+ if (this.busy) {
+ this.emitter?.emit(PoolEvents.busy, this.info)
}
}
}
}
+ private checkAndEmitDynamicWorkerCreationEvents (): void {
+ if (this.type === PoolTypes.dynamic) {
+ if (this.full) {
+ this.emitter?.emit(PoolEvents.full, this.info)
+ }
+ }
+ }
+
/**
* Gets the worker information given its worker node key.
*
* @param workerNodeKey - The worker node key.
* @returns The worker information.
*/
- protected getWorkerInfo (workerNodeKey: number): WorkerInfo {
- return this.workerNodes[workerNodeKey].info
+ protected getWorkerInfo (workerNodeKey: number): WorkerInfo | undefined {
+ return this.workerNodes[workerNodeKey]?.info
}
/**
const workerNode = new WorkerNode<Worker, Data>(
worker,
this.worker,
- this.maxSize
+ this.opts.tasksQueueOptions?.queueMaxSize ?? Math.pow(this.maxSize, 2)
)
// Flag the worker node as ready at pool startup.
if (this.starting) {