X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fselection-strategies%2Fworker-choice-strategy-context.ts;h=157a61223a251aa1305be38555e67511b37798d6;hb=3c8a79b4b146fb20de682c19d8b409bfbdf05df4;hp=fefc1275f5cb7fbacf72d689dfaf8140a733ffac;hpb=4ba8492f17b13668853cfc15a1ec9ff8c8d7b179;p=poolifier.git diff --git a/src/pools/selection-strategies/worker-choice-strategy-context.ts b/src/pools/selection-strategies/worker-choice-strategy-context.ts index fefc1275..157a6122 100644 --- a/src/pools/selection-strategies/worker-choice-strategy-context.ts +++ b/src/pools/selection-strategies/worker-choice-strategy-context.ts @@ -34,11 +34,6 @@ export class WorkerChoiceStrategyContext< IWorkerChoiceStrategy > - /** - * The number of times the worker choice strategy in the context has been retried. - */ - private choiceRetriesCount = 0 - /** * Worker choice strategy context constructor. * @@ -168,23 +163,40 @@ export class WorkerChoiceStrategyContext< * Executes the worker choice strategy in the context algorithm. * * @returns The key of the worker node. - * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker node key is null or undefined. + * @throws {@link https://nodejs.org/api/errors.html#class-error} If after configured retries the worker node key is null or undefined. + * @throws {@link https://nodejs.org/api/errors.html#class-rangeerror} If the maximum consecutive worker choice strategy executions has been reached. */ public execute (): number { - const workerNodeKey = ( - this.workerChoiceStrategies.get( - this.workerChoiceStrategy - ) as IWorkerChoiceStrategy - ).choose() - if ( - workerNodeKey == null && - this.choiceRetriesCount < (this.opts.choiceRetries as number) - ) { - this.choiceRetriesCount++ - return this.execute() - } else if (workerNodeKey == null) { - throw new TypeError( - `Worker node key chosen is null or undefined after ${this.choiceRetriesCount} retries` + const workerChoiceStrategy = this.workerChoiceStrategies.get( + this.workerChoiceStrategy + ) as IWorkerChoiceStrategy + let workerNodeKey: number | undefined + const maxExecutionCount = 10000 + let executionCount = 0 + let chooseCount = 0 + let retriesCount = 0 + do { + if (workerChoiceStrategy.hasPoolWorkerNodesReady()) { + workerNodeKey = workerChoiceStrategy.choose() + if (chooseCount > 0) { + retriesCount++ + } + chooseCount++ + } + executionCount++ + } while ( + executionCount < maxExecutionCount && + (!workerChoiceStrategy.hasPoolWorkerNodesReady() || + (workerNodeKey == null && retriesCount < (this.opts.retries as number))) + ) + if (executionCount >= maxExecutionCount) { + throw new RangeError( + `Worker choice strategy consecutive executions has exceeded the maximum of ${maxExecutionCount}` + ) + } + if (workerNodeKey == null) { + throw new Error( + `Worker node key chosen is null or undefined after ${retriesCount} retries` ) } return workerNodeKey