From 32803c441678cd640e46153688d26c4c0746d7b3 Mon Sep 17 00:00:00 2001 From: Lizzy Hunt Date: Wed, 15 Feb 2023 18:03:46 -0700 Subject: We do a little logging, but cringe OpenAPI errors be making me want to shoot myself. We have some shit working though. --- src/exponential_retry.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/exponential_retry.js (limited to 'src/exponential_retry.js') diff --git a/src/exponential_retry.js b/src/exponential_retry.js new file mode 100644 index 0000000..96ca979 --- /dev/null +++ b/src/exponential_retry.js @@ -0,0 +1,35 @@ +import { + MAX_DEFAULT_RETRY_AMOUNT, + WAIT_MS, + RETRY_EXPONENT, + RETRY_EXPONENTIAL_FACTOR, +} from "./constants.js"; + +const wait_for = (ms) => new Promise((rs) => setTimeout(rs, ms)); + +export const with_exponential_retry = async ( + promise_fn, + validation_fn = (x) => Promise.resolve(!!x), + max_retries = MAX_DEFAULT_RETRY_AMOUNT, + retries = 0 +) => { + try { + if (retries) + await wait_for( + WAIT_MS * Math.pow(RETRY_EXPONENT, RETRY_EXPONENTIAL_FACTOR * retries) + ); + + const res = await promise_fn(); + if (await validation_fn(res)) return res; + + throw new Error("Validation predicate not satisfied"); + } catch (e) { + if (retries >= max_retries) throw e; + return with_exponential_retry( + promise_fn, + validation_fn, + max_retries, + retries + 1 + ); + } +}; -- cgit v1.2.3-70-g09d2