Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retry backoff example #881

Closed
wants to merge 4 commits into from
Closed
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
96 changes: 96 additions & 0 deletions examples/retry-backoff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { run, sleep, Task } from "../mod.ts";
import { afterEach, beforeEach, describe, expect, it } from "../test/suite.ts";
import { CustomError, retryBackoffExample } from "./retry-backoff.ts";
/**
* Requirements:
* * only retry if the error matches specific error/s (otherwise fail)
* * begin with a delay of startDelay ms between retries
* * double the delay each retry attempt up to a max of maxDelay ms
* * retry a maximum of 5 times
* Source: https://discord.com/channels/795981131316985866/1125094089281511474/1189299794145988748
*/
describe("retry-backoff-example", () => {
it("fails for unknown errors", () => {
expect(run(function* () {
yield* retryBackoffExample(function* () {
throw new Error("RandomError");
});
})).rejects.toMatch(/RandomError/);
});

describe("retries", () => {
describe("known errors", () => {
let task: Task<void>;
let retries: number;
beforeEach(async () => {
retries = -1;
task = run(function* () {
yield* retryBackoffExample(function* () {
retries++;
throw new CustomError("LockTimeout");
});
});
try {
await task;
} catch {}
});
it("rejects to a known error", async () => {
await expect(task).rejects.toEqual({
_tag: "LockTimeout",
});
});
it("5 times", () => {
expect(retries).toBe(5);
});
});
// describe("delay", () => {
// let task: Task<void>;
// let backoffs: number[];
// let attempt: number;
// let start: number;
// beforeEach(async () => {
// attempt = 0;
// backoffs = [];
// task = run(function* () {
// start = performance.now();
// yield* retryBackoffExample(function* () {
// if (attempt > 0) {
// backoffs.push(performance.now() - start);
// }
// attempt++;
// throw new CustomError('LockTimeout');
// });
// });
// try {
// await task;
// } catch { }
// });
// it("doubles backoffs at every attempt", () => {
// expect(backoffs).toEqual([5, 10, 20, 40, 80])
// });
// });
describe("timeout", () => {
let task: Task<void>;
beforeEach(async () => {
let retry = 0;
task = run(function* () {
yield* retryBackoffExample(function* () {
if (retry > 0) {
yield* sleep(200);
}
retry++;
throw new CustomError("ConflictDetected");
}, { maxDelay: 100 });
});
try {
await task;
} catch (e) {
console.log(e);
}
});
it("throws an error", async () => {
await expect(task).rejects.toMatch(/Timeout/);
});
});
});
});
71 changes: 71 additions & 0 deletions examples/retry-backoff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { type Operation, race, sleep } from "../mod.ts";

export class CustomError extends Error {
public _tag: string;

constructor(_tag: string) {
super(_tag);
this._tag = _tag;
}
}

const isKnownError = (e: Error): e is CustomError =>
!!((e as CustomError)._tag) &&
["LockTimeout", "ConflictDetected", "TransactionNotFound"].includes(
(e as CustomError)._tag,
);

export function* retryBackoffExample<T>(
op: () => Operation<T>,
{ attempts = 5, startDelay = 5, maxDelay = 200 } = {},
): Operation<T | undefined> {
try {
// This is the initial operation,
// if it succeeds then the operation will be complete
return yield* op();
} catch (e) {
// if we encounter error that we're not expecting then throw
// and do not proceed any further
if (!isKnownError(e)) {
throw e;
}
}

// we're here because we encountered a known issue,
// we want to run the retry logic attempting up to 5 attempts
// pause between each attempt and double the delay with each attempt
// trigger a timeout if we reach maxDelay
// we do this by setting up a race between retry logic and
// the timeout. If retry logic succeeds, timeout will be halted
// automatically. If timeout reaches the throw, it'll interrupt the
// retry logic automatically.

let lastError: Error;
function* retry() {
let delay = startDelay;
for (let attempt = 0; attempt < attempts; attempt++) {
yield* sleep(delay);
delay = delay * 2;

try {
return yield* op();
} catch (e) {
if (isKnownError(e)) {
lastError = e;
if (attempt + 1 < attempts) {
continue;
}
}
throw e;
}
}
}

function* timeout(): Operation<undefined> {
yield* sleep(maxDelay);

throw lastError || new Error("Timeout");
}

return yield* race([retry(), timeout()]);
}
Loading