TypeScript: Retry with a Result type

Operations over a network fail now and then. Retry them with growing waits, and report success or failure with a Result type instead of an exception.

What to build

A program that retries flaky operations and reports what happened.

Requirements

  • Declare type Result<T> = { ok: true; value: T; attempts: number } | { ok: false; error: string; attempts: number }.
  • Write retry<T>(name: string, op: () => Promise<T>, attempts: number): Promise<Result<T>>: try op; on failure print NAME: attempt K failed: MESSAGE and, if attempts remain, NAME: waiting W ms and wait W = 100 × 2^(K-1) ms before trying again.
  • Each operation NAME F VALUE fails its first F calls with the error message NAME call C failed (C counts calls from 1) and then returns VALUE. Allow 3 attempts. Run the operations one after another, and after each print NAME: ok VALUE after A attempts or NAME: gave up after A attempts.

Input

Line 1: n. Then n lines NAME F VALUE.

Output

The attempt lines and one result line per operation.

Constraints

1 ≤ n ≤ 10; 0 ≤ F ≤ 5.

Example

Input:

2
weather 1 sunny
stocks 0 42

Output:

weather: attempt 1 failed: weather call 1 failed
weather: waiting 100 ms
weather: ok sunny after 2 attempts
stocks: ok 42 after 1 attempts

Why it works

The Result type makes the caller check ok before using the value, the error is caught as unknown and checked before its message is read, and the doubling wait gives a struggling server more time on each try.

Examples

Example 1 · Input
2
weather 1 sunny
stocks 0 42
Expected output
weather: attempt 1 failed: weather call 1 failed
weather: waiting 100 ms
weather: ok sunny after 2 attempts
stocks: ok 42 after 1 attempts
Example 2 · Input
1
login 3 token
Expected output
login: attempt 1 failed: login call 1 failed
login: waiting 100 ms
login: attempt 2 failed: login call 2 failed
login: waiting 200 ms
login: attempt 3 failed: login call 3 failed
login: gave up after 3 attempts

Hints

Hint 1

async function retry<T>(name: string, op: () => Promise<T>, attempts: number): Promise<Result<T>> loops, awaiting op() in try ... catch.

Hint 2

The wait before attempt k + 1 is 100 × 2^(k - 1) milliseconds.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";

type Result<T> = { ok: true; value: T; attempts: number } | { ok: false; error: string; attempts: number };

function wait(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function retry<T>(name: string, op: () => Promise<T>, attempts: number): Promise<Result<T>> {
  let lastError = "";
  for (let k = 1; k <= attempts; k++) {
    try {
      const value = await op();
      return { ok: true, value, attempts: k };
    } catch (error: unknown) {
      lastError = error instanceof Error ? error.message : String(error);
      console.log(name + ": attempt " + k + " failed: " + lastError);
      if (k < attempts) {
        const ms = 100 * 2 ** (k - 1);
        console.log(name + ": waiting " + ms + " ms");
        await wait(ms);
      }
    }
  }
  return { ok: false, error: lastError, attempts };
}

function flaky(name: string, failures: number, value: string): () => Promise<string> {
  let calls = 0;
  return async () => {
    calls++;
    if (calls <= failures) throw new Error(name + " call " + calls + " failed");
    return value;
  };
}

async function main(): Promise<void> {
  const n = Number(read());
  for (let i = 0; i < n; i++) {
    const [name, f, value] = read().split(" ");
    const result = await retry(name, flaky(name, Number(f), value), 3);
    if (result.ok) console.log(name + ": ok " + result.value + " after " + result.attempts + " attempts");
    else console.log(name + ": gave up after " + result.attempts + " attempts");
  }
}

main();

Lesson: Async code with types →