### Changed
+- Optimize worker storage in pool.
- Optimize worker alive status check.
+### Fixed
+
+- Ensure trimmable characters are checked at pool initialization.
+
## [2.3.10] - 2023-03-18
### Fixed
import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
import type { PoolOptions } from './pool'
import { PoolEmitter } from './pool'
-import type { IPoolInternal, TasksUsage } from './pool-internal'
+import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
import { PoolType } from './pool-internal'
import type { IPoolWorker } from './pool-worker'
import {
Response = unknown
> implements IPoolInternal<Worker, Data, Response> {
/** {@inheritDoc} */
- public readonly workers: Worker[] = []
-
- /** {@inheritDoc} */
- public readonly workersTasksUsage: Map<Worker, TasksUsage> = new Map<
- Worker,
- TasksUsage
+ public readonly workers: Map<number, WorkerType<Worker>> = new Map<
+ number,
+ WorkerType<Worker>
>()
/** {@inheritDoc} */
public readonly emitter?: PoolEmitter
+ /**
+ * Id of the next worker.
+ */
+ protected nextWorkerId: number = 0
+
/**
* The promise map.
*
- * - `key`: This is the message Id of each submitted task.
+ * - `key`: This is the message id of each submitted task.
* - `value`: An object that contains the worker, the resolve function and the reject function.
*
* When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
}
private checkFilePath (filePath: string): void {
- if (filePath == null || filePath.length === 0) {
+ if (
+ filePath == null ||
+ (typeof filePath === 'string' && filePath.trim().length === 0)
+ ) {
throw new Error('Please specify a file with a worker implementation')
}
}
return this.promiseMap.size
}
- /** {@inheritDoc} */
- public getWorkerIndex (worker: Worker): number {
- return this.workers.indexOf(worker)
+ /**
+ * Gets worker key.
+ *
+ * @param worker - The worker.
+ * @returns The worker key.
+ */
+ private getWorkerKey (worker: Worker): number | undefined {
+ return [...this.workers].find(([, value]) => value.worker === worker)?.[0]
}
/** {@inheritDoc} */
public getWorkerRunningTasks (worker: Worker): number | undefined {
- return this.workersTasksUsage.get(worker)?.running
+ return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
+ ?.running
}
/** {@inheritDoc} */
public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
- return this.workersTasksUsage.get(worker)?.avgRunTime
+ return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
+ ?.avgRunTime
}
/** {@inheritDoc} */
workerChoiceStrategy: WorkerChoiceStrategy
): void {
this.opts.workerChoiceStrategy = workerChoiceStrategy
- for (const worker of this.workers) {
- this.resetWorkerTasksUsage(worker)
+ for (const [key, value] of this.workers) {
+ this.setWorker(key, value.worker, {
+ run: 0,
+ running: 0,
+ runTime: 0,
+ avgRunTime: 0
+ })
}
this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
workerChoiceStrategy
/** {@inheritDoc} */
public findFreeWorker (): Worker | false {
- for (const worker of this.workers) {
- if (this.getWorkerRunningTasks(worker) === 0) {
+ for (const value of this.workers.values()) {
+ if (value.tasksUsage.running === 0) {
// A worker is free, return the matching worker
- return worker
+ return value.worker
}
}
return false
/** {@inheritDoc} */
public async destroy (): Promise<void> {
await Promise.all(
- this.workers.map(async worker => {
- await this.destroyWorker(worker)
+ [...this.workers].map(async ([, value]) => {
+ await this.destroyWorker(value.worker)
})
)
}
* @param worker - The worker that will be removed.
*/
protected removeWorker (worker: Worker): void {
- // Clean worker from data structure
- this.workers.splice(this.getWorkerIndex(worker), 1)
- this.removeWorkerTasksUsage(worker)
+ this.workers.delete(this.getWorkerKey(worker) as number)
+ --this.nextWorkerId
}
/**
this.removeWorker(worker)
})
- this.workers.push(worker)
-
- // Init worker tasks usage map
- this.initWorkerTasksUsage(worker)
+ this.setWorker(this.nextWorkerId, worker, {
+ run: 0,
+ running: 0,
+ runTime: 0,
+ avgRunTime: 0
+ })
+ ++this.nextWorkerId
this.afterWorkerSetup(worker)
this.stepWorkerRunningTasks(worker, -1)
}
+ /**
+ * Get tasks usage of the given worker.
+ *
+ * @param worker - Worker which tasks usage is returned.
+ */
+ private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
+ if (this.checkWorker(worker)) {
+ const workerKey = this.getWorkerKey(worker) as number
+ const workerEntry = this.workers.get(workerKey) as WorkerType<Worker>
+ return workerEntry.tasksUsage
+ }
+ }
+
/**
* Steps the number of tasks that the given worker has applied.
*
* @param step - Number of running tasks step.
*/
private stepWorkerRunningTasks (worker: Worker, step: number): void {
- if (this.checkWorkerTasksUsage(worker)) {
- const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
- tasksUsage.running = tasksUsage.running + step
- this.workersTasksUsage.set(worker, tasksUsage)
- }
+ // prettier-ignore
+ (this.getWorkerTasksUsage(worker) as TasksUsage).running += step
}
/**
* @param step - Number of run tasks step.
*/
private stepWorkerRunTasks (worker: Worker, step: number): void {
- if (this.checkWorkerTasksUsage(worker)) {
- const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
- tasksUsage.run = tasksUsage.run + step
- this.workersTasksUsage.set(worker, tasksUsage)
- }
+ // prettier-ignore
+ (this.getWorkerTasksUsage(worker) as TasksUsage).run += step
}
/**
): void {
if (
this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .requiredStatistics.runTime &&
- this.checkWorkerTasksUsage(worker)
+ .requiredStatistics.runTime
) {
- const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
- tasksUsage.runTime += taskRunTime ?? 0
- if (tasksUsage.run !== 0) {
- tasksUsage.avgRunTime = tasksUsage.runTime / tasksUsage.run
+ const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
+ workerTasksUsage.runTime += taskRunTime ?? 0
+ if (workerTasksUsage.run !== 0) {
+ workerTasksUsage.avgRunTime =
+ workerTasksUsage.runTime / workerTasksUsage.run
}
- this.workersTasksUsage.set(worker, tasksUsage)
}
}
/**
- * Checks if the given worker is registered in the workers tasks usage map.
- *
- * @param worker - Worker to check.
- * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
- */
- private checkWorkerTasksUsage (worker: Worker): boolean {
- const hasTasksUsage = this.workersTasksUsage.has(worker)
- if (!hasTasksUsage) {
- throw new Error('Worker could not be found in workers tasks usage map')
- }
- return hasTasksUsage
- }
-
- /**
- * Initializes tasks usage statistics.
+ * Sets the given worker.
*
+ * @param workerKey - The worker key.
* @param worker - The worker.
+ * @param tasksUsage - The worker tasks usage.
*/
- private initWorkerTasksUsage (worker: Worker): void {
- this.workersTasksUsage.set(worker, {
- run: 0,
- running: 0,
- runTime: 0,
- avgRunTime: 0
+ private setWorker (
+ workerKey: number,
+ worker: Worker,
+ tasksUsage: TasksUsage
+ ): void {
+ this.workers.set(workerKey, {
+ worker,
+ tasksUsage
})
}
/**
- * Removes worker tasks usage statistics.
- *
- * @param worker - The worker.
- */
- private removeWorkerTasksUsage (worker: Worker): void {
- this.workersTasksUsage.delete(worker)
- }
-
- /**
- * Resets worker tasks usage statistics.
+ * Checks if the given worker is registered in the pool.
*
- * @param worker - The worker.
+ * @param worker - Worker to check.
+ * @returns `true` if the worker is registered in the pool.
*/
- private resetWorkerTasksUsage (worker: Worker): void {
- this.removeWorkerTasksUsage(worker)
- this.initWorkerTasksUsage(worker)
+ private checkWorker (worker: Worker): boolean {
+ if (this.getWorkerKey(worker) == null) {
+ throw new Error('Worker could not be found in the pool')
+ }
+ return true
}
}
/** {@inheritDoc} */
public get busy (): boolean {
- return this.workers.length === this.max
+ return this.workers.size === this.max
}
}
avgRunTime: number
}
+/**
+ * Internal worker type.
+ *
+ * @typeParam Worker - Type of worker which manages this pool.
+ */
+export interface WorkerType<Worker extends IPoolWorker> {
+ worker: Worker
+ tasksUsage: TasksUsage
+}
+
/**
* Internal contract definition for a poolifier pool.
*
Response = unknown
> extends IPool<Data, Response> {
/**
- * List of currently available workers.
+ * Map of workers.
*/
- readonly workers: Worker[]
-
- /**
- * The workers tasks usage map.
- *
- * `key`: The `Worker`
- * `value`: Worker tasks usage statistics.
- */
- readonly workersTasksUsage: Map<Worker, TasksUsage>
+ readonly workers: Map<number, WorkerType<Worker>>
/**
* Pool type.
*/
findFreeWorker: () => Worker | false
- /**
- * Gets worker index.
- *
- * @param worker - The worker.
- * @returns The worker index.
- */
- getWorkerIndex: (worker: Worker) => number
-
/**
* Gets worker running tasks.
*
public choose (): Worker {
let minWorkerVirtualTaskEndTimestamp = Infinity
let chosenWorker!: Worker
- for (const worker of this.pool.workers) {
+ for (const value of this.pool.workers.values()) {
+ const worker = value.worker
this.computeWorkerLastVirtualTaskTimestamp(worker)
const workerLastVirtualTaskEndTimestamp =
this.workerLastVirtualTaskTimestamp.get(worker)?.end ?? 0
let minNumberOfRunningTasks = Infinity
// A worker is always found because it picks the one with fewer tasks
let lessRecentlyUsedWorker!: Worker
- for (const worker of this.pool.workers) {
+ for (const value of this.pool.workers.values()) {
+ const worker = value.worker
const workerRunningTasks = this.pool.getWorkerRunningTasks(
worker
) as number
Response
> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
/**
- * Index for the next worker.
+ * Id of the next worker.
*/
- private nextWorkerIndex: number = 0
+ private nextWorkerId: number = 0
/** {@inheritDoc} */
public reset (): boolean {
- this.nextWorkerIndex = 0
+ this.nextWorkerId = 0
return true
}
/** {@inheritDoc} */
public choose (): Worker {
- const chosenWorker = this.pool.workers[this.nextWorkerIndex]
- this.nextWorkerIndex =
- this.nextWorkerIndex === this.pool.workers.length - 1
+ const chosenWorker = this.pool.workers.get(this.nextWorkerId)
+ ?.worker as Worker
+ this.nextWorkerId =
+ this.nextWorkerId === this.pool.workers.size - 1
? 0
- : this.nextWorkerIndex + 1
+ : this.nextWorkerId + 1
return chosenWorker
}
}
}
/**
- * Worker index where the current task will be submitted.
+ * Worker id where the current task will be submitted.
*/
- private currentWorkerIndex: number = 0
+ private currentWorkerId: number = 0
/**
* Default worker weight.
*/
/** {@inheritDoc} */
public reset (): boolean {
- this.currentWorkerIndex = 0
+ this.currentWorkerId = 0
this.workersTaskRunTime.clear()
this.initWorkersTaskRunTime()
return true
/** {@inheritDoc} */
public choose (): Worker {
- const chosenWorker = this.pool.workers[this.currentWorkerIndex]
+ const chosenWorker = this.pool.workers.get(this.currentWorkerId)
+ ?.worker as Worker
if (this.isDynamicPool && !this.workersTaskRunTime.has(chosenWorker)) {
this.initWorkerTaskRunTime(chosenWorker)
}
(this.getWorkerVirtualTaskRunTime(chosenWorker) ?? 0)
)
} else {
- this.currentWorkerIndex =
- this.currentWorkerIndex === this.pool.workers.length - 1
+ this.currentWorkerId =
+ this.currentWorkerId === this.pool.workers.size - 1
? 0
- : this.currentWorkerIndex + 1
+ : this.currentWorkerId + 1
this.setWorkerTaskRunTime(
- this.pool.workers[this.currentWorkerIndex],
+ this.pool.workers.get(this.currentWorkerId)?.worker as Worker,
workerTaskWeight,
0
)
}
private initWorkersTaskRunTime (): void {
- for (const worker of this.pool.workers) {
- this.initWorkerTaskRunTime(worker)
+ for (const value of this.pool.workers.values()) {
+ this.initWorkerTaskRunTime(value.worker)
}
}
/** {@inheritDoc} */
public get busy (): boolean {
- return this.workers.length === this.max
+ return this.workers.size === this.max
}
}
describe('Abstract pool test suite', () => {
const numberOfWorkers = 1
const workerNotFoundInTasksUsageMapError = new Error(
- 'Worker could not be found in workers tasks usage map'
+ 'Worker could not be found in the pool'
)
class StubPoolWithRemoveAllWorker extends FixedThreadPool {
removeAllWorker () {
- this.workers = []
- this.workersTasksUsage.clear()
+ this.workers = new Map()
this.promiseMap.clear()
}
}
numberOfWorkers,
'./tests/worker-files/cluster/testWorker.js'
)
- for (const tasksUsage of pool.workersTasksUsage.values()) {
- expect(tasksUsage).toBeDefined()
- expect(tasksUsage.run).toBe(0)
- expect(tasksUsage.running).toBe(0)
- expect(tasksUsage.runTime).toBe(0)
- expect(tasksUsage.avgRunTime).toBe(0)
+ for (const value of pool.workers.values()) {
+ expect(value.tasksUsage).toBeDefined()
+ expect(value.tasksUsage.run).toBe(0)
+ expect(value.tasksUsage.running).toBe(0)
+ expect(value.tasksUsage.runTime).toBe(0)
+ expect(value.tasksUsage.avgRunTime).toBe(0)
}
await pool.destroy()
})
for (let i = 0; i < numberOfWorkers * 2; i++) {
promises.push(pool.execute())
}
- for (const tasksUsage of pool.workersTasksUsage.values()) {
- expect(tasksUsage).toBeDefined()
- expect(tasksUsage.run).toBe(0)
- expect(tasksUsage.running).toBe(numberOfWorkers * 2)
- expect(tasksUsage.runTime).toBe(0)
- expect(tasksUsage.avgRunTime).toBe(0)
+ for (const value of pool.workers.values()) {
+ expect(value.tasksUsage).toBeDefined()
+ expect(value.tasksUsage.run).toBe(0)
+ expect(value.tasksUsage.running).toBe(numberOfWorkers * 2)
+ expect(value.tasksUsage.runTime).toBe(0)
+ expect(value.tasksUsage.avgRunTime).toBe(0)
}
await Promise.all(promises)
- for (const tasksUsage of pool.workersTasksUsage.values()) {
- expect(tasksUsage).toBeDefined()
- expect(tasksUsage.run).toBe(numberOfWorkers * 2)
- expect(tasksUsage.running).toBe(0)
- expect(tasksUsage.runTime).toBeGreaterThanOrEqual(0)
- expect(tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
+ for (const value of pool.workers.values()) {
+ expect(value.tasksUsage).toBeDefined()
+ expect(value.tasksUsage.run).toBe(numberOfWorkers * 2)
+ expect(value.tasksUsage.running).toBe(0)
+ expect(value.tasksUsage.runTime).toBeGreaterThanOrEqual(0)
+ expect(value.tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
}
await pool.destroy()
})
promises.push(pool.execute())
}
await Promise.all(promises)
- for (const tasksUsage of pool.workersTasksUsage.values()) {
- expect(tasksUsage).toBeDefined()
- expect(tasksUsage.run).toBe(numberOfWorkers * 2)
- expect(tasksUsage.running).toBe(0)
- expect(tasksUsage.runTime).toBeGreaterThanOrEqual(0)
- expect(tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
+ for (const value of pool.workers.values()) {
+ expect(value.tasksUsage).toBeDefined()
+ expect(value.tasksUsage.run).toBe(numberOfWorkers * 2)
+ expect(value.tasksUsage.running).toBe(0)
+ expect(value.tasksUsage.runTime).toBeGreaterThanOrEqual(0)
+ expect(value.tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
}
pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.FAIR_SHARE)
- for (const tasksUsage of pool.workersTasksUsage.values()) {
- expect(tasksUsage).toBeDefined()
- expect(tasksUsage.run).toBe(0)
- expect(tasksUsage.running).toBe(0)
- expect(tasksUsage.runTime).toBe(0)
- expect(tasksUsage.avgRunTime).toBe(0)
+ for (const value of pool.workers.values()) {
+ expect(value.tasksUsage).toBeDefined()
+ expect(value.tasksUsage.run).toBe(0)
+ expect(value.tasksUsage.running).toBe(0)
+ expect(value.tasksUsage.runTime).toBe(0)
+ expect(value.tasksUsage.avgRunTime).toBe(0)
}
await pool.destroy()
})
it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => {
let poolBusy = 0
- pool.emitter.on('busy', () => poolBusy++)
+ pool.emitter.on('busy', () => ++poolBusy)
for (let i = 0; i < max * 2; i++) {
pool.execute()
}
- expect(pool.workers.length).toBeLessThanOrEqual(max)
- expect(pool.workers.length).toBeGreaterThan(min)
+ expect(pool.workers.size).toBeLessThanOrEqual(max)
+ expect(pool.workers.size).toBeGreaterThan(min)
// The `busy` event is triggered when the number of submitted tasks at once reach the max number of workers in the dynamic pool.
// So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the dynamic pool.
expect(poolBusy).toBe(max + 1)
})
it('Verify scale worker up and down is working', async () => {
- expect(pool.workers.length).toBe(min)
+ expect(pool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
pool.execute()
}
- expect(pool.workers.length).toBeGreaterThan(min)
+ expect(pool.workers.size).toBeGreaterThan(min)
await TestUtils.waitExits(pool, max - min)
- expect(pool.workers.length).toBe(min)
+ expect(pool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
pool.execute()
}
- expect(pool.workers.length).toBeGreaterThan(min)
+ expect(pool.workers.size).toBeGreaterThan(min)
await TestUtils.waitExits(pool, max - min)
- expect(pool.workers.length).toBe(min)
+ expect(pool.workers.size).toBe(min)
})
it('Shutdown test', async () => {
exitHandler: () => console.log('long running worker exited')
}
)
- expect(longRunningPool.workers.length).toBe(min)
+ expect(longRunningPool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
longRunningPool.execute()
}
- expect(longRunningPool.workers.length).toBe(max)
+ expect(longRunningPool.workers.size).toBe(max)
await TestUtils.waitExits(longRunningPool, max - min)
// Here we expect the workers to be at the max size since that the task is still running
- expect(longRunningPool.workers.length).toBe(min)
+ expect(longRunningPool.workers.size).toBe(min)
// We need to clean up the resources after our test
await longRunningPool.destroy()
})
exitHandler: () => console.log('long running worker exited')
}
)
- expect(longRunningPool.workers.length).toBe(min)
+ expect(longRunningPool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
longRunningPool.execute()
}
- expect(longRunningPool.workers.length).toBe(max)
+ expect(longRunningPool.workers.size).toBe(max)
await TestUtils.sleep(1500)
// Here we expect the workers to be at the max size since that the task is still running
- expect(longRunningPool.workers.length).toBe(max)
+ expect(longRunningPool.workers.size).toBe(max)
// We need to clean up the resources after our test
await longRunningPool.destroy()
})
it('Verify that busy event is emitted', async () => {
let poolBusy = 0
- pool.emitter.on('busy', () => poolBusy++)
+ pool.emitter.on('busy', () => ++poolBusy)
for (let i = 0; i < numberOfWorkers * 2; i++) {
pool.execute()
}
WorkerChoiceStrategies.ROUND_ROBIN
)
expect(
- pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerIndex
+ pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerId
).toBe(0)
// We need to clean up the resources after our test
await pool.destroy()
{ workerChoiceStrategy: WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN }
)
expect(
- pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerIndex
+ pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerId
).toBeUndefined()
pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.ROUND_ROBIN)
expect(
- pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerIndex
+ pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerId
).toBe(0)
await pool.destroy()
pool = new DynamicThreadPool(
)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .workerChoiceStrategy.nextWorkerIndex
+ .workerChoiceStrategy.nextWorkerId
).toBeUndefined()
pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.ROUND_ROBIN)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .workerChoiceStrategy.nextWorkerIndex
+ .workerChoiceStrategy.nextWorkerId
).toBe(0)
// We need to clean up the resources after our test
await pool.destroy()
WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN
)
expect(
- pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .currentWorkerIndex
+ pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().currentWorkerId
).toBe(0)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
'./tests/worker-files/thread/testWorker.js'
)
expect(
- pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .currentWorkerIndex
+ pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().currentWorkerId
).toBeUndefined()
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
).toBeUndefined()
pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN)
expect(
- pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .currentWorkerIndex
+ pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().currentWorkerId
).toBe(0)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .workerChoiceStrategy.currentWorkerIndex
+ .workerChoiceStrategy.currentWorkerId
).toBeUndefined()
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .workerChoiceStrategy.currentWorkerIndex
+ .workerChoiceStrategy.currentWorkerId
).toBe(0)
expect(
pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
it('Verify that reset() resets internals', () => {
const strategy = new WeightedRoundRobinWorkerChoiceStrategy(pool)
- strategy.currentWorkerIndex = TestUtils.generateRandomInteger()
+ strategy.currentWorkerId = TestUtils.generateRandomInteger()
const workersTaskRunTimeClearStub = sinon
.stub(strategy.workersTaskRunTime, 'clear')
.returns()
.returns()
const resetResult = strategy.reset()
expect(resetResult).toBe(true)
- expect(strategy.currentWorkerIndex).toBe(0)
+ expect(strategy.currentWorkerId).toBe(0)
expect(workersTaskRunTimeClearStub.calledOnce).toBe(true)
expect(initWorkersTaskRunTimeStub.calledOnce).toBe(true)
})
it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => {
let poolBusy = 0
- pool.emitter.on('busy', () => poolBusy++)
+ pool.emitter.on('busy', () => ++poolBusy)
for (let i = 0; i < max * 2; i++) {
pool.execute()
}
- expect(pool.workers.length).toBeLessThanOrEqual(max)
- expect(pool.workers.length).toBeGreaterThan(min)
+ expect(pool.workers.size).toBeLessThanOrEqual(max)
+ expect(pool.workers.size).toBeGreaterThan(min)
// The `busy` event is triggered when the number of submitted tasks at once reach the max number of workers in the dynamic pool.
// So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the dynamic pool.
expect(poolBusy).toBe(max + 1)
})
it('Verify scale thread up and down is working', async () => {
- expect(pool.workers.length).toBe(min)
+ expect(pool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
pool.execute()
}
- expect(pool.workers.length).toBe(max)
+ expect(pool.workers.size).toBe(max)
await TestUtils.waitExits(pool, max - min)
- expect(pool.workers.length).toBe(min)
+ expect(pool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
pool.execute()
}
- expect(pool.workers.length).toBe(max)
+ expect(pool.workers.size).toBe(max)
await TestUtils.waitExits(pool, max - min)
- expect(pool.workers.length).toBe(min)
+ expect(pool.workers.size).toBe(min)
})
it('Shutdown test', async () => {
exitHandler: () => console.log('long running worker exited')
}
)
- expect(longRunningPool.workers.length).toBe(min)
+ expect(longRunningPool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
longRunningPool.execute()
}
- expect(longRunningPool.workers.length).toBe(max)
+ expect(longRunningPool.workers.size).toBe(max)
await TestUtils.waitExits(longRunningPool, max - min)
- expect(longRunningPool.workers.length).toBe(min)
+ expect(longRunningPool.workers.size).toBe(min)
// We need to clean up the resources after our test
await longRunningPool.destroy()
})
exitHandler: () => console.log('long running worker exited')
}
)
- expect(longRunningPool.workers.length).toBe(min)
+ expect(longRunningPool.workers.size).toBe(min)
for (let i = 0; i < max * 10; i++) {
longRunningPool.execute()
}
- expect(longRunningPool.workers.length).toBe(max)
+ expect(longRunningPool.workers.size).toBe(max)
await TestUtils.sleep(1500)
// Here we expect the workers to be at the max size since that the task is still running
- expect(longRunningPool.workers.length).toBe(max)
+ expect(longRunningPool.workers.size).toBe(max)
// We need to clean up the resources after our test
await longRunningPool.destroy()
})
it('Verify that busy event is emitted', async () => {
let poolBusy = 0
- pool.emitter.on('busy', () => poolBusy++)
+ pool.emitter.on('busy', () => ++poolBusy)
for (let i = 0; i < numberOfThreads * 2; i++) {
pool.execute()
}
static async waitExits (pool, numberOfExitEventsToWait) {
return new Promise(resolve => {
let exitEvents = 0
- for (const worker of pool.workers) {
- worker.on('exit', () => {
- exitEvents++
+ for (const value of pool.workers.values()) {
+ value.worker.on('exit', () => {
+ ++exitEvents
if (exitEvents === numberOfExitEventsToWait) {
resolve(exitEvents)
}
describe('Thread worker test suite', () => {
let numberOfMessagesPosted = 0
const postMessage = function () {
- numberOfMessagesPosted++
+ ++numberOfMessagesPosted
}
class SpyWorker extends ThreadWorker {
getMainWorker () {