Skip to content

Commit

Permalink
feat: Add waiter parameter for exponentialBackoff (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
MikuroXina committed Apr 17, 2024
1 parent 10bd666 commit 0dd89ac
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/optical/retriable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { err, ok } from "../result.ts";
import { assertEquals } from "../../deps.ts";

Deno.test("exponential backoff", async () => {
const optic = exponentialBackoff(3)(
const optic = exponentialBackoff(3, () => Promise.resolve())(
() => ({ bar: 3 } as Record<string, number>),
)(
(record: Record<string, number>) => (attempt) =>
Expand Down
25 changes: 15 additions & 10 deletions src/optical/retriable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,17 +104,22 @@ export const newRetriable =
* Creates a retriable optical by exponential backoff method. It increases the delay duration (100 milliseconds) multiplied by the power of two, but its exponent stops at 23.
*
* @param maxRetries - Maximum retry counts.
* @param waiter - The waiter function to delay. Defaults to `setTimeout` method.
* @param triable - An operation that may fail.
* @param set - A function to substitute the data `S`.
* @returns The retriable optical.
*/
export const exponentialBackoff =
(maxRetries: number) => <E, T>(fallback: (err: E) => T) =>
newRetriable(promiseMonad)(0)((err: E) => async (attempt) => {
if (attempt >= maxRetries) {
return newBreak(fallback(err));
}
const delay = 100 << Math.min(23, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
return newContinue(attempt + 1);
});
export const exponentialBackoff = (
maxRetries: number,
waiter: (milliseconds: number) => Promise<void> = (ms) =>
new Promise((resolve) => setTimeout(resolve, ms)),
) =>
<E, T>(fallback: (err: E) => T) =>
newRetriable(promiseMonad)(0)((err: E) => async (attempt) => {
if (attempt >= maxRetries) {
return newBreak(fallback(err));
}
const delay = 100 << Math.min(23, attempt);
await waiter(delay);
return newContinue(attempt + 1);
});

0 comments on commit 0dd89ac

Please sign in to comment.