+ /** @inheritDoc */
+ public abstract get type (): PoolType
+
+ /**
+ * Number of tasks concurrently running in the pool.
+ */
+ private get numberOfRunningTasks (): number {
+ return this.promiseResponseMap.size
+ }
+
+ /**
+ * Gets the given worker key.
+ *
+ * @param worker - The worker.
+ * @returns The worker key if the worker is found in the pool, `-1` otherwise.
+ */
+ private getWorkerKey (worker: Worker): number {
+ return this.workers.findIndex(workerItem => workerItem.worker === worker)
+ }
+
+ /** @inheritDoc */
+ public setWorkerChoiceStrategy (
+ workerChoiceStrategy: WorkerChoiceStrategy
+ ): void {
+ this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
+ this.opts.workerChoiceStrategy = workerChoiceStrategy
+ for (const [index, workerItem] of this.workers.entries()) {
+ this.setWorker(index, workerItem.worker, {
+ run: 0,
+ running: 0,
+ runTime: 0,
+ avgRunTime: 0,
+ error: 0
+ })
+ }
+ this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
+ workerChoiceStrategy
+ )
+ }
+
+ /** @inheritDoc */
+ public abstract get full (): boolean
+
+ /** @inheritDoc */
+ public abstract get busy (): boolean
+
+ protected internalBusy (): boolean {
+ return (
+ this.numberOfRunningTasks >= this.numberOfWorkers &&
+ this.findFreeWorkerKey() === -1
+ )
+ }
+
+ /** @inheritDoc */
+ public findFreeWorkerKey (): number {
+ return this.workers.findIndex(workerItem => {
+ return workerItem.tasksUsage.running === 0
+ })
+ }
+
+ /** @inheritDoc */
+ public async execute (data: Data): Promise<Response> {
+ const [workerKey, worker] = this.chooseWorker()
+ const messageId = crypto.randomUUID()
+ const res = this.internalExecute(workerKey, worker, messageId)
+ this.checkAndEmitFull()
+ this.checkAndEmitBusy()
+ this.sendToWorker(worker, {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
+ data: data ?? ({} as Data),
+ id: messageId
+ })
+ // eslint-disable-next-line @typescript-eslint/return-await
+ return res
+ }
+
+ /** @inheritDoc */
+ public async destroy (): Promise<void> {
+ await Promise.all(
+ this.workers.map(async workerItem => {
+ await this.destroyWorker(workerItem.worker)
+ })
+ )