+ this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext(
+ this,
+ () => {
+ const workerCreated = this.createAndSetupWorker()
+ this.registerWorkerMessageListener(workerCreated, message => {
+ const tasksInProgress = this.tasks.get(workerCreated)
+ if (
+ isKillBehavior(KillBehaviors.HARD, message.kill) ||
+ tasksInProgress === 0
+ ) {
+ // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
+ void this.destroyWorker(workerCreated)
+ }
+ })
+ return workerCreated
+ },
+ opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
+ )
+ }
+
+ private checkFilePath (filePath: string): void {
+ if (!filePath) {
+ throw new Error('Please specify a file with a worker implementation')
+ }
+ }
+
+ private checkNumberOfWorkers (numberOfWorkers: number): void {
+ if (numberOfWorkers == null) {
+ throw new Error(
+ 'Cannot instantiate a pool without specifying the number of workers'
+ )
+ } else if (!Number.isSafeInteger(numberOfWorkers)) {
+ throw new Error(
+ 'Cannot instantiate a pool with a non integer number of workers'
+ )
+ } else if (numberOfWorkers < 0) {
+ throw new Error(
+ 'Cannot instantiate a pool with a negative number of workers'
+ )
+ } else if (!this.dynamic && numberOfWorkers === 0) {
+ throw new Error('Cannot instantiate a fixed pool with no worker')
+ }
+ }
+
+ /** @inheritdoc */
+ public get dynamic (): boolean {
+ return false
+ }
+
+ /** @inheritdoc */
+ public setWorkerChoiceStrategy (
+ workerChoiceStrategy: WorkerChoiceStrategy
+ ): void {
+ this.opts.workerChoiceStrategy = workerChoiceStrategy
+ this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
+ workerChoiceStrategy
+ )
+ }
+
+ /** @inheritdoc */
+ public execute (data: Data): Promise<Response> {
+ // Configure worker to handle message with the specified task
+ const worker = this.chooseWorker()
+ this.increaseWorkersTask(worker)
+ const messageId = ++this.nextMessageId
+ const res = this.internalExecute(worker, messageId)
+ this.sendToWorker(worker, { data: data || ({} as Data), id: messageId })
+ return res
+ }
+
+ /** @inheritdoc */
+ public async destroy (): Promise<void> {
+ await Promise.all(this.workers.map(worker => this.destroyWorker(worker)))