+ private getWorkerKey (worker: Worker): number | undefined {
+ return [...this.workers].find(([, value]) => value.worker === worker)?.[0]
+ }
+
+ /** {@inheritDoc} */
+ public getWorkerRunningTasks (worker: Worker): number | undefined {
+ return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
+ ?.running
+ }
+
+ /** {@inheritDoc} */
+ public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
+ return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
+ ?.avgRunTime
+ }
+
+ /** {@inheritDoc} */
+ public setWorkerChoiceStrategy (
+ workerChoiceStrategy: WorkerChoiceStrategy
+ ): void {
+ this.opts.workerChoiceStrategy = workerChoiceStrategy
+ 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 abstract get busy (): boolean
+
+ protected internalGetBusyStatus (): boolean {
+ return (
+ this.numberOfRunningTasks >= this.numberOfWorkers &&
+ this.findFreeWorker() === false
+ )
+ }
+
+ /** {@inheritDoc} */
+ public findFreeWorker (): Worker | false {
+ for (const value of this.workers.values()) {
+ if (value.tasksUsage.running === 0) {
+ // A worker is free, return the matching worker
+ return value.worker
+ }
+ }
+ return false
+ }
+
+ /** {@inheritDoc} */
+ public async execute (data: Data): Promise<Response> {
+ const worker = this.chooseWorker()
+ const messageId = crypto.randomUUID()
+ const res = this.internalExecute(worker, messageId)
+ 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 ([, value]) => {
+ await this.destroyWorker(value.worker)
+ })
+ )