Skip to content

Commit

Permalink
fix: fetch randomness with timeout (#98)
Browse files Browse the repository at this point in the history
Co-authored-by: Sylvain Goumy <[email protected]>
  • Loading branch information
brandonchuah and goums authored Mar 28, 2024
1 parent 7bb5017 commit 6deba6d
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/drand_util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,34 @@ async function fetchDrandResponseWithCaching(round: number) {
return { round, randomness };
}

async function fetchBeaconWithTimeout(
client: HttpChainClient,
round: number,
timeout: number = 5_000
) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => reject(new Error(`Timeout`)), timeout);
fetchBeacon(client, round)
.then((response) => {
clearTimeout(timeoutId);
resolve(response);
})
.catch((err) => {
clearTimeout(timeoutId);
reject(err);
});
});
}

async function fetchDrandResponse(round: number) {
console.log(`Fetching randomness from round ${round}`);
const errors = [];

for (const client of clientCache.getClients()) {
try {
return await fetchBeacon(client, round);
return await fetchBeaconWithTimeout(client, round);
} catch (err) {
console.error(`Failed to fetch randomness: ${(err as Error).message}`);
errors.push(err);
}
}
Expand Down

0 comments on commit 6deba6d

Please sign in to comment.