X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fselection-strategies%2Fworker-choice-strategy-context.ts;h=d6a6e26d27e87fbb263a9ef5b61e5c1745b60950;hb=613a91dc3e9745e9f4ae53f589fe0ee6d2b594cd;hp=a3e3379c9ac461fc7cd16c2d32bb8735ca2d50ff;hpb=0ffa432eaff319902a2657c5e44374ea109cfb87;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 a3e3379c..d6a6e26d 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,26 +163,44 @@ 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. */ public execute (): number { - const workerNodeKey = ( - this.workerChoiceStrategies.get( - this.workerChoiceStrategy - ) as IWorkerChoiceStrategy - ).choose() - if ( + const workerChoiceStrategy = this.workerChoiceStrategies.get( + this.workerChoiceStrategy + ) as IWorkerChoiceStrategy + if (!workerChoiceStrategy.hasPoolWorkerNodesReady()) { + // wait for a worker node to be ready without blocking the event loop + } + return this.executeStrategy(workerChoiceStrategy) + } + + /** + * Executes the given worker choice strategy. + * + * @param workerChoiceStrategy - The worker choice strategy. + * @returns The key of the worker node. + * @throws {@link https://nodejs.org/api/errors.html#class-error} If after configured retries the worker node key is null or undefined. + */ + private executeStrategy (workerChoiceStrategy: IWorkerChoiceStrategy): number { + let workerNodeKey: number | undefined + let chooseCount = 0 + let retriesCount = 0 + do { + workerNodeKey = workerChoiceStrategy.choose() + if (workerNodeKey == null && chooseCount > 0) { + retriesCount++ + } + chooseCount++ + } while ( 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` + retriesCount < (this.opts.retries as number) + ) + if (workerNodeKey == null) { + throw new Error( + `Worker node key chosen is null or undefined after ${retriesCount} retries` ) } - this.choiceRetriesCount = 0 return workerNodeKey }