From 515ec7e36829b1d63703a33224b0ba46e948acd4 Mon Sep 17 00:00:00 2001 From: andrew <44451818+afostr@users.noreply.github.com> Date: Wed, 5 Jun 2024 00:34:09 -0500 Subject: [PATCH] throttled node check to allow only N active requests --- src/utils.ts | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 3a68ab89..c07e1f60 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -139,8 +139,38 @@ export async function updateNodeList(tryInfinate = false): Promise { }) } if (config.filterDeadNodesFromArchiver) { - const promises = nodes.map(checkIfNodeIsActive) - const results = await Promise.all(promises) + //const promises = nodes.map(checkIfNodeIsActive) //dont blast all requests at once + + const concurrentRequests = 50 + const semaphore = new Semaphore(concurrentRequests); + const results: boolean[] = new Array(nodes.length).fill(false); + + const waitForAllPromise = new Deferred() + let finished = 0 + for(let i=0; i= nodes.length) { + waitForAllPromise.resolve() + } + } + } + throttledNodeCheck(node, i) + } + + //wait for finished count + await waitForAllPromise + + //const results = await Promise.all(promises) const activeNodes = nodes.filter((_, index) => results[index]) nodeList = activeNodes if (verbose) @@ -1773,3 +1803,50 @@ export function hexToBN(hexString: string): BN { } return new BN(hexString, 16) } + + +class Semaphore { + private queue: (() => void)[] = []; + private value: number; + + constructor(maxConcurrency: number) { + this.value = maxConcurrency; + } + + async wait(): Promise { + return new Promise((resolve) => { + const tryAcquire = () => { + if (this.value > 0) { + this.value--; + resolve(); + } else { + this.queue.push(tryAcquire); + } + }; + tryAcquire(); + }); + } + + signal(): void { + this.value++; + if (this.queue.length > 0) { + const next = this.queue.shift(); + if (next) { + next(); + } + } + } +} + +class Deferred { + public promise: Promise; + public resolve!: (value: T | PromiseLike) => void; + public reject!: (reason?: any) => void; + + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} \ No newline at end of file