Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.4 KiB · at 358de06

Write retryFetch(fetcher, url, options), which calls an HTTP fetcher and retries transient failures with exponential backoff.

fetcher(url) is asynchronous. It either produces a response { status: number, body: string } or fails with a network error { kind: "network", message: string }.

options is { retries, baseDelayMs, sleep }: retries is a non-negative integer (the number of extra attempts allowed after the first), baseDelayMs is a non-negative number, and sleep(ms) is an injected asynchronous delay. Never use real timers.

Each attempt calls fetcher(url) once and is classified:

  • Status 200 to 299: success. retryFetch returns the response body.
  • Status 500 to 599, or a network error: retryable.
  • Any other status (1xx, 3xx, 4xx): fails immediately with { kind: "http", status }, no further attempts.

Before retry number n (n = 0 for the first retry, 1 for the second, ...), wait for sleep(baseDelayMs * 2 ** n) to complete, then attempt again. sleep is called exactly once before every retry, even when the delay is 0, and never after the last attempt. With retries: 0 there is exactly one attempt and no sleep.

When the last allowed attempt is still retryable, fail with { kind: "exhausted", attempts, lastStatus }:

  • attempts is the total number of fetcher calls made.
  • lastStatus is the HTTP status of the final attempt if it was a 5xx response, and absent if the final attempt failed with a network error.