import { getNS, stringify } from "../common"; import { ParallelExecutor } from "./ParallelExecutor"; export class AgreementExecutor extends ParallelExecutor { constructor( private readonly quorumNumber: number, timeoutMs: number | undefined, protected shouldResolveUnagreedToUndefined = false ) { super(timeoutMs); } public override aggregate(results: R[]): R { const modes = this.getModes(results); this.logger.debug(`Found modes: ${stringify(modes)}`); if (!modes) { throw new Error(`That should've never happened but still...: ${stringify(modes)}`); } if (modes.length !== 1) { this.logger[this.shouldResolveUnagreedToUndefined ? "info" : "warn"]( `Multiple modes found (shouldResolveUnagreedToUndefined = ${this.shouldResolveUnagreedToUndefined}; were the returning promises sync?): ${stringify(modes)}` ); if (this.shouldResolveUnagreedToUndefined) { return undefined as R; } } return modes[0].item; } public verifySettlements(successfulResults: R[], errorResults: unknown[], totalLength: number) { const modes = this.getModes(successfulResults); const quorum = this.getQuorum(totalLength); const maxCount = modes?.[0]?.count ?? 0; const isEnough = maxCount >= quorum; if (isEnough) { return true; } if (successfulResults.length + errorResults.length < totalLength) { this.logger.debug( `Returning, still doesn't have enough of ${quorum} results: ${successfulResults.length} successes + ${errorResults.length} errors` ); return false; } this.logger.debug("Successful results:", successfulResults); if (this.shouldResolveUnagreedToUndefined) { return true; // Will be resolved to undefined } const failedCount = errorResults.length; throw new AggregateError( errorResults, `Agreement failed: got max ${getNS(maxCount, "equal result")}, needed at least ${quorum}` + (failedCount > 0 ? `; ${getNS(failedCount, "fail")}` : "") ); } protected getQuorum(totalLength: number) { return totalLength <= this.quorumNumber ? Math.min(1, this.quorumNumber) : this.quorumNumber; } }