Async Fallback Chain Over Mirrors

Try mirrors in order and keep the first success: failures accumulate into an attempts report, so a final miss lists every reason.

TypescriptResilience

Code

typescriptsnippet
38 lines
// Result-shaped fallback chain over mirrors: try each in order, the first
// success wins, and every failure is recorded for the final report
type Mirror = readonly [name: string, fetchOne: (path: string) => Promise<string>];

type ChainResult =
  | { readonly ok: true; readonly mirror: string; readonly body: string }
  | { readonly ok: false; readonly attempts: readonly string[] };

async function fetchWithFallback(mirrors: readonly Mirror[], path: string): Promise<ChainResult> {
  const attempts: string[] = [];
  for (const [name, fetchOne] of mirrors) {
    try {
      return { ok: true, mirror: name, body: await fetchOne(path) };
    } catch (error) {
      attempts.push(`${name}: ${(error as Error).message}`);
    }
  }
  return { ok: false, attempts };
}

// Local stand-ins keep the chain runnable without a network
const mirrors: readonly Mirror[] = [
  ["eu-1", () => Promise.reject(new Error("503"))],
  ["us-2", () => Promise.reject(new Error("timeout"))],
  ["ap-3", (path) => Promise.resolve(`${path} via ap-3`)],
];

async function main(): Promise<void> {
  const lost = await fetchWithFallback(mirrors.slice(0, 2), "/v1/status");
  console.log("all mirrors failed:", lost.ok ? "unexpected" : lost.attempts);

  const won = await fetchWithFallback(mirrors, "/v1/status");
  console.log("served by:", won.ok ? won.mirror : "unexpected", "| body:", won.ok ? won.body : "-");
}

main().catch((error: unknown) => {
  throw error;
});

Output

Captured from a sandboxed run of this snippet in the build pipeline.

all mirrors failed: [ 'eu-1: 503', 'us-2: timeout' ]
served by: ap-3 | body: /v1/status via ap-3

How the logic is organized

Everything happens inside the functions fetchWithFallback and main.

The loop for (const [name, fetchOne] of mirrors) is the only repeated construct. Every asynchronous step is awaited, so rejections surface where the call happens.

The result comes back as an object carrying true, name.

What to watch for

  • No install step — all APIs used come with the platform.

Using it

The main signature to know: async function fetchWithFallback(mirrors: readonly Mirror[], path: string)

Look for the all mirrors failed:, served by: prefixes when execution starts; each line stays tied to the step that emitted it.

The call returns true, name — destructure what you need at the call site.

Key statements

type Mirror = readonly [name: string, fetchOne: (path: string) => Promise<string>];
return { ok: true, mirror: name, body: await fetchOne(path) };
main().catch((error: unknown) => {
  throw error;
});

Interactive Tools for This Topic

FAQ

Does `fetchWithFallback` modify its input?
No mutation happens — the function reads its input and returns a new value.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `fetchWithFallback`, `main` at load time.