Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions async/retry.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

import { delay } from "./delay.ts";
import { exponentialBackoffWithJitter } from "./_util.ts";

/**
Expand Down Expand Up @@ -129,19 +129,34 @@ export async function retry<T>(
jitter = 1,
} = options ?? {};

if (maxTimeout <= 0) {
throw new TypeError(
`Cannot retry as 'maxTimeout' must be positive: current value is ${maxTimeout}`,
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
throw new RangeError(
`Cannot retry as 'maxAttempts' must be a positive integer: current value is ${maxAttempts}`,
);
}
if (!Number.isFinite(multiplier) || multiplier < 1) {
throw new RangeError(
`Cannot retry as 'multiplier' must be a finite number >= 1: current value is ${multiplier}`,
);
}
if (Number.isNaN(maxTimeout) || maxTimeout <= 0) {
throw new RangeError(
`Cannot retry as 'maxTimeout' must be a positive number: current value is ${maxTimeout}`,
);
}
if (Number.isNaN(minTimeout) || minTimeout < 0) {
throw new RangeError(
`Cannot retry as 'minTimeout' must be >= 0: current value is ${minTimeout}`,
);
}
if (minTimeout > maxTimeout) {
throw new TypeError(
throw new RangeError(
`Cannot retry as 'minTimeout' must be <= 'maxTimeout': current values 'minTimeout=${minTimeout}', 'maxTimeout=${maxTimeout}'`,
);
}
if (jitter > 1) {
throw new TypeError(
`Cannot retry as 'jitter' must be <= 1: current value is ${jitter}`,
if (Number.isNaN(jitter) || jitter < 0 || jitter > 1) {
throw new RangeError(
`Cannot retry as 'jitter' must be between 0 and 1: current value is ${jitter}`,
);
}

Expand All @@ -161,7 +176,7 @@ export async function retry<T>(
multiplier,
jitter,
);
await new Promise((r) => setTimeout(r, timeout));
await delay(timeout);
}
attempt++;
}
Expand Down
207 changes: 196 additions & 11 deletions async/retry_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,26 @@ Deno.test("retry()", async () => {
assertEquals(result, 3);
});

Deno.test("retry() works with async functions", async () => {
let attempts = 0;
const result = await retry(async () => {
await Promise.resolve();
attempts++;
if (attempts < 3) throw new Error("Not yet");
return "async success";
}, { minTimeout: 1 });
assertEquals(result, "async success");
assertEquals(attempts, 3);
});

Deno.test("retry() returns immediately on first success", async () => {
using time = new FakeTime();
const startTime = time.now;
const result = await retry(() => "immediate");
assertEquals(result, "immediate");
assertEquals(time.now, startTime); // No time passed
});

Deno.test("retry() fails after five errors by default", async () => {
const fiveErrors = generateErroringFunction(5);
await assertRejects(() =>
Expand All @@ -43,6 +63,20 @@ Deno.test("retry() fails after five errors when undefined is passed", async () =
);
});

Deno.test("retry() throws RetryError with last error as cause", async () => {
const specificError = new Error("Specific failure");
const error = await assertRejects(
() =>
retry(() => {
throw specificError;
}, { maxAttempts: 1 }),
RetryError,
);
assertEquals(error.cause, specificError);
assertEquals(error.name, "RetryError");
assertEquals(error.message, "Retrying exceeded the maxAttempts (1).");
});

Deno.test("retry() waits four times by default", async () => {
let callCount = 0;
const onlyErrors = function () {
Expand All @@ -66,51 +100,177 @@ Deno.test("retry() waits four times by default", async () => {
});

Deno.test(
"retry() throws if minTimeout is less than maxTimeout",
"retry() throws if minTimeout is greater than maxTimeout",
async () => {
await assertRejects(
() =>
retry(() => {}, {
minTimeout: 1000,
maxTimeout: 100,
}),
TypeError,
RangeError,
"Cannot retry as 'minTimeout' must be <= 'maxTimeout': current values 'minTimeout=1000', 'maxTimeout=100'",
);
},
);

Deno.test(
"retry() throws if maxTimeout is less than 0",
"retry() throws if maxTimeout is less than or equal to 0",
async () => {
await assertRejects(
() =>
retry(() => {}, {
maxTimeout: -1,
}),
TypeError,
"Cannot retry as 'maxTimeout' must be positive: current value is -1",
RangeError,
"Cannot retry as 'maxTimeout' must be a positive number: current value is -1",
);
},
);

Deno.test(
"retry() throws if jitter is bigger than 1",
"retry() throws if jitter is greater than 1",
async () => {
await assertRejects(
() =>
retry(() => {}, {
jitter: 2,
}),
TypeError,
"Cannot retry as 'jitter' must be <= 1: current value is 2",
RangeError,
"Cannot retry as 'jitter' must be between 0 and 1: current value is 2",
);
},
);

Deno.test("retry() checks backoff function timings", async (t) => {
const originalMathRandom = Math.random;
Deno.test(
"retry() throws if maxAttempts is 0",
async () => {
await assertRejects(
() => retry(() => {}, { maxAttempts: 0 }),
RangeError,
"Cannot retry as 'maxAttempts' must be a positive integer: current value is 0",
);
},
);

Deno.test(
"retry() throws if maxAttempts is not an integer",
async () => {
await assertRejects(
() => retry(() => {}, { maxAttempts: 2.5 }),
RangeError,
"Cannot retry as 'maxAttempts' must be a positive integer: current value is 2.5",
);
},
);

Deno.test("retry() respects custom maxAttempts", async () => {
let attempts = 0;
const error = await assertRejects(
() =>
retry(() => {
attempts++;
throw new Error();
}, {
maxAttempts: 3,
minTimeout: 1,
}),
RetryError,
"Retrying exceeded the maxAttempts (3).",
);
assertEquals(attempts, 3);
assertEquals(error.message, "Retrying exceeded the maxAttempts (3).");
});

Deno.test(
"retry() throws if multiplier is less than 1",
async () => {
await assertRejects(
() => retry(() => {}, { multiplier: 0.5 }),
RangeError,
"Cannot retry as 'multiplier' must be a finite number >= 1: current value is 0.5",
);
},
);

Deno.test(
"retry() throws if multiplier is NaN",
async () => {
await assertRejects(
() => retry(() => {}, { multiplier: NaN }),
RangeError,
"Cannot retry as 'multiplier' must be a finite number >= 1: current value is NaN",
);
},
);

Deno.test(
"retry() throws if multiplier is Infinity",
async () => {
await assertRejects(
() => retry(() => {}, { multiplier: Infinity }),
RangeError,
"Cannot retry as 'multiplier' must be a finite number >= 1: current value is Infinity",
);
},
);

Deno.test(
"retry() throws if minTimeout is negative",
async () => {
await assertRejects(
() => retry(() => {}, { minTimeout: -100 }),
RangeError,
"Cannot retry as 'minTimeout' must be >= 0: current value is -100",
);
},
);

Deno.test(
"retry() throws if minTimeout is NaN",
async () => {
await assertRejects(
() => retry(() => {}, { minTimeout: NaN }),
RangeError,
"Cannot retry as 'minTimeout' must be >= 0: current value is NaN",
);
},
);

Deno.test(
"retry() throws if jitter is negative",
async () => {
await assertRejects(
() => retry(() => {}, { jitter: -0.5 }),
RangeError,
"Cannot retry as 'jitter' must be between 0 and 1: current value is -0.5",
);
},
);

Deno.test(
"retry() throws if jitter is NaN",
async () => {
await assertRejects(
() => retry(() => {}, { jitter: NaN }),
RangeError,
"Cannot retry as 'jitter' must be between 0 and 1: current value is NaN",
);
},
);

Deno.test(
"retry() throws if maxTimeout is NaN",
async () => {
await assertRejects(
() => retry(() => {}, { maxTimeout: NaN }),
RangeError,
"Cannot retry as 'maxTimeout' must be a positive number: current value is NaN",
);
},
);

Deno.test("retry() checks backoff function timings", async (t) => {
await t.step("wait fixed times without jitter", async () => {
using time = new FakeTime();
let resolved = false;
Expand Down Expand Up @@ -148,6 +308,31 @@ Deno.test("retry() checks backoff function timings", async (t) => {
assertEquals(time.now - startTime, 15000);
await promise;
});
});

Deno.test("retry() caps backoff at maxTimeout", async () => {
using time = new FakeTime();
const promise = retry(() => {
throw new Error();
}, {
minTimeout: 1000,
maxTimeout: 1500, // Should cap at 1500, not grow to 2000, 4000, etc.
multiplier: 2,
jitter: 0,
});

Math.random = originalMathRandom;
const startTime = time.now;
await time.nextAsync(); // 1000ms (1000 * 2^0)
assertEquals(time.now - startTime, 1000);

await time.nextAsync(); // 1500ms capped (would be 2000)
assertEquals(time.now - startTime, 2500);

await time.nextAsync(); // 1500ms capped (would be 4000)
assertEquals(time.now - startTime, 4000);

await time.nextAsync(); // 1500ms capped (would be 8000)
assertEquals(time.now - startTime, 5500);

await assertRejects(() => promise, RetryError);
});
Loading