From 930a75cbc5748570ddc0747117c0c3017fb4c815 Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:40:04 +0300 Subject: [PATCH 1/2] ci(docker): a cluster failover test on the candidate image (#290) Three instances on SeaweedFS. The first is killed with SIGKILL ten seconds before a scheduled release is due: the other two must serve the site and Studio again within 60 s with the published content intact, and the release must run exactly once, not early, and be live everywhere. The killed instance rejoins on its volume; then b and c stop gracefully in turn while the others take a steady load, with not one failed request and an exit within the grace period. No instance may log a migration error. Every docker command and request is bounded, the step has timeout-minutes, and a failure prints each instance's state, release, runs, scheduler status and log. The script refuses to run outside GitHub Actions. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .github/workflows/docker.yml | 12 +- deploy/docker/README.md | 2 + docs/guides/self-host.md | 4 +- scripts/failover-smoke.ts | 415 +++++++++++++++++++++++++++++++++++ 4 files changed, 431 insertions(+), 2 deletions(-) create mode 100644 scripts/failover-smoke.ts diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 98bb49c0..642a9e88 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -10,7 +10,9 @@ name: Docker image # and scripts/helm-smoke.sh (kind) on the amd64 image # (compose.yml's SeaweedFS, the image's own `secrets`, the first site and owner, a publish live # on the next request, a restart, the Node-volume guard, a second instance taking over while the -# first stops) and Trivy, which fails the job on a CRITICAL vulnerability with a fix; +# first stops), scripts/failover-smoke.ts (three instances, one killed with SIGKILL while a release +# is due, then graceful handoffs under load; #290) and Trivy, which fails the job on a CRITICAL +# vulnerability with a fix; # - `smoke-arm64` runs the same smoke test on the arm64 image, on GitHub's native arm64 runner; # - `tag` adds the release tags to the very digest that passed, with `imagetools create`, writes # the GitHub build attestation for it, and for a release pushes the Helm chart of that version to @@ -49,6 +51,7 @@ on: - "deploy/docker/**" - ".github/workflows/docker.yml" - "scripts/docker-smoke.ts" + - "scripts/failover-smoke.ts" - "scripts/pack-packages.ts" - "scripts/selfhost-edge-bundle.ts" - "packages/cli/src/selfhost/**" @@ -241,6 +244,13 @@ jobs: run: | kind version && helm version --short scripts/helm-smoke.sh cloudhal:ci + # Cluster failover (#290, RFC-0047 §7): three instances on SeaweedFS, the first killed with + # SIGKILL while a release is due (the others serve again within 60 s, the release runs exactly + # once), then two graceful SIGTERM handoffs under load with not one failed request. CI only: + # the script refuses to run outside GitHub Actions. + - name: Cluster failover test + timeout-minutes: 20 + run: node scripts/failover-smoke.ts --image cloudhal:ci - name: Trivy scan timeout-minutes: 15 uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 diff --git a/deploy/docker/README.md b/deploy/docker/README.md index ca6d0379..774f2be2 100644 --- a/deploy/docker/README.md +++ b/deploy/docker/README.md @@ -28,3 +28,5 @@ node scripts/pack-packages.ts deploy/docker/tarballs && pnpm --filter @cloudhal/ ``` `node scripts/docker-smoke.ts --image cloudhal:local` runs what CI runs after every build (`.github/workflows/docker.yml`); `--platform linux/arm64` runs the other architecture where Docker can. + +`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index ab336d90..6eac84dd 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -139,9 +139,11 @@ Instances with the same `.env` and store form one installation. Each Durable Obj - **Network:** the cluster port 7000 must be reachable between instances only, on a private network. Instances authenticate each other with the cluster key, but their traffic is not encrypted, so use a VPC, WireGuard, Tailscale or Docker Swarm's `encrypted` overlay. - **Stopping:** on SIGTERM an instance hands its objects to the others and exits within 8 s. `stop_grace_period: 15s` in the compose file allows for that. -- **A killed instance:** its objects move once its lease expires, about 20 s later. +- **A killed instance:** its objects move once its lease expires, about 20 s later. Until then, requests that need one of its objects (the database among them) fail, so run at least two instances behind a readiness-aware load balancer. - **Readiness:** use `GET /ready` on port 7000 as the readiness probe of a rolling restart. +CI checks this with every image ([`scripts/failover-smoke.ts`](https://github.com/cloudhal-dev/cloudhal/blob/main/scripts/failover-smoke.ts)): three instances on SeaweedFS, one killed with SIGKILL shortly before a scheduled release is due. The other two must serve the site and Studio again within 60 s with the published content intact, and the release must run exactly once. Then two instances in turn stop gracefully while the others take a steady load, and not one request may fail. + The cluster runs on workerd's experimental cluster mode, so treat several instances as a preview until workerd documents it. ### Docker Swarm and Kubernetes diff --git a/scripts/failover-smoke.ts b/scripts/failover-smoke.ts new file mode 100644 index 00000000..1c9eeb06 --- /dev/null +++ b/scripts/failover-smoke.ts @@ -0,0 +1,415 @@ +/** + * The cluster failover test (RFC-0047 §7, §12; #290). CI only: .github/workflows/docker.yml runs + * it on the candidate image, and it refuses to start outside GitHub Actions, because three + * instances and a store are more than a developer machine should carry next to everything else. + * + * 1. Three instances of the image on compose.yml's SeaweedFS. Instance a starts first (it runs the + * migrations and creates the site, so it owns the database and the scheduler's objects), then b + * and c join. + * 2. The first owner signs up and publishes. A change to the starter post is put in a release due + * about 80 s later. + * 3. Shortly before the release is due, a is killed with SIGKILL. The site and Studio on b and c + * must answer again within 60 s with the published content intact (the spike measured about + * 16 s while a's lease runs out). + * 4. The release, due while a was down, must run exactly once: one succeeded run, not early, and + * the change live on every instance. a starts again on its volume and rejoins. + * 5. b and then c are stopped gracefully (SIGTERM, `docker stop`) while the other two take a + * steady load: not one request may fail during the handoff, and each exits by itself within + * the 15 s grace period. One of them owns the database after step 3, so one of the stops is a + * real handoff. + * 6. No instance logged a migration error (#309), and the release still has exactly one run. + * + * Every docker command and request is bounded, and a failure prints each instance's state and log. + * + * node scripts/failover-smoke.ts --image [--port ] + */ +import { execFile } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +if (process.env.GITHUB_ACTIONS !== "true") { + console.error("failover-smoke runs in CI only (.github/workflows/docker.yml), never locally"); + process.exit(2); +} + +const arg = (name: string): string | undefined => { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? undefined : process.argv[i + 1]; +}; +const image = arg("image") ?? "cloudhal:ci"; +const port = Number(arg("port") ?? 28787); +const id = `cloudhal-failover-${process.pid}`; +const net = id; +const store = `${id}-store`; +type Name = "a" | "b" | "c"; +const NAMES: Name[] = ["a", "b", "c"]; +const ctr = (n: Name) => `${id}-${n}`; +const offset = { a: 0, b: 2, c: 4 } as const; +// 127.0.0.1, never localhost (#306): on GitHub's runners localhost resolves to ::1 first. +const studio = (n: Name) => `http://127.0.0.1:${port + offset[n]}`; +const site = (n: Name) => `http://127.0.0.1:${port + offset[n] + 1}`; +/** One public origin for the installation: every instance gets the same config (RFC-0047 §2). */ +const ORIGIN = studio("a"); +const NEW_TITLE = "Released during the outage"; +const HOME_H1 = /]*>Failover Site<\/h1>/; +const STORE_IMAGE = /image: (chrislusf\/seaweedfs:\S+)/.exec( + readFileSync( + path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker/compose.yml"), + "utf8", + ), +)?.[1]; +if (!STORE_IMAGE) throw new Error("compose.yml names no SeaweedFS image"); + +const run = promisify(execFile); +/** A docker command, bounded (#306). */ +async function docker(args: string[], timeout = 120_000): Promise { + const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); + return stdout.trim(); +} +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const t0 = Date.now(); +const elapsed = () => `${((Date.now() - t0) / 1000).toFixed(1)}s`; +const step = (text: string) => console.log(`✓ [${elapsed()}] ${text}`); +function expect(ok: boolean, what: string, detail?: unknown): void { + if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); +} + +/** Secrets go to `docker run` in 0600 files, so a failed command never prints them. */ +const envDir = mkdtempSync(path.join(os.tmpdir(), "cloudhal-failover-")); +function envFile(name: string, env: Record): string { + const file = path.join(envDir, `${name}.env`); + writeFileSync( + file, + Object.entries(env) + .map(([k, v]) => `${k}=${v}\n`) + .join(""), + { mode: 0o600 }, + ); + return file; +} + +async function secrets(): Promise> { + const text = await docker(["run", "--rm", image, "secrets"]); + return Object.fromEntries( + text + .split("\n") + .filter((l) => l.includes("=") && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ); +} + +async function startStore(env: Record): Promise { + await docker(["network", "create", net]); + const config = JSON.stringify({ + identities: [ + { + name: "cloudhal", + credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], + actions: ["Admin", "Read", "Write", "List", "Tagging"], + }, + ], + }); + await docker([ + ...["run", "-d", "--name", store, "--network", net, "--network-alias", "seaweedfs"], + ...["--env-file", envFile("store", { S3_CONFIG: config }), "--entrypoint", "/bin/sh"], + STORE_IMAGE as string, + "-c", + 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', + ]); +} + +/** An instance as compose.yml runs it, its Durable Objects on its own volume. */ +async function startInstance(n: Name, env: Record): Promise { + const file = envFile(n, { + ...env, + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", + CLOUDHAL_CLUSTER_ADVERTISE: `${ctr(n)}:7000`, + CLOUDHAL_SITE_NAME: "Failover Site", + CLOUDHAL_BASE_URL: ORIGIN, + }); + await docker([ + ...["run", "-d", "--name", ctr(n), "--network", net, "--read-only", "--tmpfs", "/tmp"], + ...["--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], + ...["--stop-timeout", "15", "-v", `${ctr(n)}:/data`, "--env-file", file], + ...["-p", `127.0.0.1:${port + offset[n]}:8787`, "-p", `127.0.0.1:${port + offset[n] + 1}:8788`], + image, + ]); +} + +async function waitHealthy(n: Name, seconds = 180): Promise { + const deadline = Date.now() + seconds * 1000; + while (Date.now() < deadline) { + const [status, running] = ( + await docker(["inspect", "--format", "{{.State.Health.Status}} {{.State.Running}}", ctr(n)]) + ).split(" "); + if (status === "healthy") return; + if (running !== "true") throw new Error(`${ctr(n)} stopped while starting`); + await sleep(2000); + } + throw new Error(`${ctr(n)} did not become healthy within ${seconds} s`); +} + +interface Res { + status: number; + text: string; + body: unknown; + headers: Headers; +} +/** A request, bounded at 10 s; a network error answers status 0 with the error as text. */ +async function req(url: string, init: RequestInit = {}): Promise { + try { + const res = await fetch(url, { ...init, signal: AbortSignal.timeout(10_000) }); + const text = await res.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // not JSON + } + return { status: res.status, text, body, headers: res.headers }; + } catch (e) { + const err = e as { name?: string; cause?: { code?: string } }; + const text = err.cause?.code ?? err.name ?? String(e); + return { status: 0, text, body: text, headers: new Headers() }; + } +} + +async function until( + what: string, + seconds: number, + check: () => Promise, +): Promise { + const deadline = Date.now() + seconds * 1000; + while (Date.now() < deadline) { + const v = await check().catch(() => undefined); + if (v !== undefined) return v; + await sleep(1000); + } + throw new Error(`${what} within ${seconds} s`); +} + +const env = await secrets(); +const siteId = env.CLOUDHAL_SITE_ID as string; +const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; +let cookie = ""; +let releaseId = ""; +const api = (n: Name, p: string, init: RequestInit = {}) => + req(`${studio(n)}${p}`, { + ...init, + headers: { origin: ORIGIN, cookie, ...(init.headers as Record) }, + }); +const post = (n: Name, p: string, body: unknown, headers: Record = {}) => + api(n, p, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify(body), + }); + +/** What every instance must answer while it serves: the site, Studio's API and a database read. */ +async function serves(n: Name, postTitle?: string): Promise { + const home = await req(`${site(n)}/`); + if (home.status !== 200 || !HOME_H1.test(home.text)) return `site / ${home.status}`; + const post = await req(`${site(n)}/posts/hello-world`); + if (post.status !== 200) return `site /posts/hello-world ${post.status}`; + if (postTitle && !post.text.includes(postTitle)) return `the post is not "${postTitle}"`; + const sites = await req(`${studio(n)}/api/admin/sites`, { headers: admin }); + const listed = (sites.body as { sites?: { id: string }[] }).sites ?? []; + if (sites.status !== 200 || !listed.some((s) => s.id === siteId)) + return `studio /api/admin/sites ${sites.status}`; + return undefined; +} + +async function firstSiteAndPublish(): Promise { + await until("the entrypoint did not create the site", 120, async () => { + const r = await req(`${studio("a")}/api/admin/sites`, { headers: admin }); + const sites = (r.body as { sites?: { id: string }[] }).sites ?? []; + return sites.some((s) => s.id === siteId) ? true : undefined; + }); + const before = await req(`${site("a")}/`); + expect(before.status === 503, "the site answers 503 before the first publish", before.status); + const signUp = await post( + "a", + "/api/auth/sign-up/email", + { name: "Failover Owner", email: "owner@example.com", password: "failover-test-password" }, + { "x-cloudhal-setup-token": env.CLOUDHAL_SETUP_TOKEN as string }, + ); + expect(signUp.status === 200, "sign-up of the first owner", signUp.body); + cookie = + signUp.headers + .getSetCookie() + .map((c) => c.split(";")[0] as string) + .find((c) => c.includes("better-auth.session_token=")) ?? ""; + expect(cookie !== "", "sign-up set a session cookie"); + const published = await post("a", `/api/sites/${siteId}/snapshots`, { publish: true }); + expect(published.status === 201, "publish", published.body); +} + +/** The starter post retitled in a draft, in a release due at `at`; returns the release id. */ +async function scheduleRelease(at: number): Promise { + const list = await api("a", `/api/sites/${siteId}/entries?collection=posts`); + const entry = (list.body as { id: string; slug: string }[]).find?.( + (e) => e.slug === "hello-world", + ); + expect(list.status === 200 && entry !== undefined, "the starter post", list.status); + const saved = await api("a", `/api/sites/${siteId}/entries/${entry?.id}`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ...entry, title: NEW_TITLE }), + }); + expect(saved.status === 200, "the draft change", saved.body); + const when = { at: new Date(at).toISOString() }; + const draft = await post("a", `/api/sites/${siteId}/releases`, { + title: "Failover", + nodeIds: [entry?.id], + when, + }); + const rel = (draft.body as { release?: { id: string; rev: number } }).release; + expect(draft.status === 201 && rel !== undefined, "the draft release", draft.body); + const done = await post("a", `/api/sites/${siteId}/releases/${rel?.id}/schedule`, { + when, + rev: rel?.rev, + }); + const state = (done.body as { release?: { state?: string } }).release?.state; + expect(done.status === 200 && state === "scheduled", "the release is scheduled", done.body); + return rel?.id as string; +} + +async function runsOf(n: Name): Promise<{ state: string; startedAt?: string; trigger?: string }[]> { + const r = await api(n, `/api/sites/${siteId}/runs?releaseId=${releaseId}`); + expect(r.status === 200, "the release's runs", r.body); + return (r.body as { runs: { state: string; startedAt?: string; trigger?: string }[] }).runs; +} + +/** Steady load on `targets` while `victim` stops gracefully: not one request may fail. */ +async function handoff(victim: Name, targets: Name[]): Promise { + const failures: string[] = []; + let requests = 0; + let stopping = true; + const loop = async (n: Name) => { + while (stopping) { + const why = await serves(n, NEW_TITLE); + requests++; + if (why && failures.length < 50) failures.push(`${elapsed()} ${n}: ${why}`); + await sleep(100); + } + }; + const loops = targets.map(loop); + await sleep(3000); + const started = Date.now(); + await docker(["stop", "--timeout", "15", ctr(victim)], 60_000); + const took = (Date.now() - started) / 1000; + // the handoff runs on after the victim exits: its leases move to the survivors + await sleep(25_000); + stopping = false; + await Promise.all(loops); + const exit = await docker(["inspect", "--format", "{{.State.ExitCode}}", ctr(victim)]); + expect(failures.length === 0, `requests failed while ${victim} stopped`, failures); + expect(exit !== "137" && took < 15, `${victim} exits by itself within 15 s`, { exit, took }); + step(`${victim} stopped on SIGTERM in ${took.toFixed(1)} s; ${requests} rounds, none failed`); +} + +async function diagnostics(): Promise { + const out = (what: string, text: string) => console.error(`--- ${what}\n${text}`); + const safe = async (f: () => Promise) => f().catch((e: Error) => `error: ${e.message}`); + out("containers", await safe(() => docker(["ps", "-a", "--filter", `name=${id}`], 30_000))); + for (const n of NAMES) { + for (const u of [`${studio(n)}/api/health`, `${site(n)}/`]) + out(`${n} ${u}`, String((await req(u)).status)); + if (releaseId) { + const r = await api(n, `/api/sites/${siteId}/releases/${releaseId}`); + out(`${n} release`, r.text.slice(0, 2000)); + out(`${n} runs`, (await api(n, `/api/sites/${siteId}/runs?releaseId=${releaseId}`)).text); + } + const status = await req(`${studio(n)}/api/admin/schedules/status`, { headers: admin }); + out(`${n} scheduler`, status.text.slice(0, 2000)); + } + for (const name of [...NAMES.map(ctr), store]) + out( + `${name} logs`, + await safe(() => dockerOutput(["logs", "--tail", "150", "--timestamps", name])), + ); +} +/** `docker logs` writes the container's stderr to its own stderr. */ +async function dockerOutput(args: string[]): Promise { + const { stdout, stderr } = await run("docker", args, { encoding: "utf8", timeout: 30_000 }); + return `${stdout}${stderr}`; +} + +async function main(): Promise { + await startStore(env); + await startInstance("a", env); + await waitHealthy("a"); + await firstSiteAndPublish(); + await Promise.all([startInstance("b", env), startInstance("c", env)]); + await Promise.all([waitHealthy("b"), waitHealthy("c")]); + for (const n of NAMES) expect((await serves(n, "Hello, world")) === undefined, `${n} serves`); + step("three instances on SeaweedFS serve the published site"); + + const due = Date.now() + 80_000; + releaseId = await scheduleRelease(due); + expect( + (await serves("b", NEW_TITLE)) === `the post is not "${NEW_TITLE}"`, + "the change waits for its release", + ); + step(`a release of a changed post is due at ${new Date(due).toISOString()}`); + + await sleep(Math.max(0, due - 10_000 - Date.now())); + await docker(["kill", "--signal", "KILL", ctr("a")], 30_000); + const killed = Date.now(); + step("a (the first instance) is killed with SIGKILL, 10 s before the release is due"); + await until("b and c did not serve the published site and Studio", 60, async () => { + const why = [await serves("b"), await serves("c")].filter(Boolean); + return why.length === 0 ? true : undefined; + }); + step( + `b and c serve the site and Studio again ${((Date.now() - killed) / 1000).toFixed(1)} s after the kill`, + ); + + await until("the release did not run", 180, async () => { + const r = await api("b", `/api/sites/${siteId}/releases/${releaseId}`); + return (r.body as { state?: string }).state === "published" ? true : undefined; + }); + const runs = await runsOf("b"); + expect(runs.length === 1 && runs[0]?.state === "succeeded", "exactly one succeeded run", runs); + expect(Date.parse(runs[0]?.startedAt ?? "") >= due, "the release did not run early", runs); + for (const n of ["b", "c"] as const) + expect((await serves(n, NEW_TITLE)) === undefined, `${n} serves the released change`); + step(`the release due during the outage ran exactly once (${runs[0]?.trigger}) and is live`); + + await docker(["start", ctr("a")]); + await waitHealthy("a"); + await until("a did not serve the released change after rejoining", 60, async () => + (await serves("a", NEW_TITLE)) === undefined ? true : undefined, + ); + step("a starts again on its volume, rejoins and serves the released change"); + + await handoff("b", ["a", "c"]); + await docker(["start", ctr("b")]); + await waitHealthy("b"); + await handoff("c", ["a", "b"]); + + const logs = await Promise.all(NAMES.map((n) => dockerOutput(["logs", ctr(n)]))); + const errs = logs.flatMap((l) => l.split("\n")).filter((l) => l.includes('migration "')); + expect(errs.length === 0, "an instance logged a migration error", errs); + expect((await runsOf("a")).length === 1, "the release still has exactly one run"); + step("no instance logged a migration error; the release still has exactly one run"); + console.log("\nCluster failover test passed."); +} + +try { + await main(); +} catch (e) { + console.error(`\n✗ [${elapsed()}] ${e instanceof Error ? e.message : String(e)}`); + await diagnostics().catch((d: Error) => console.error(`diagnostics failed: ${d.message}`)); + process.exitCode = 1; +} finally { + for (const name of [...NAMES.map(ctr), store]) + await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); + for (const n of NAMES) await docker(["volume", "rm", ctr(n)], 30_000).catch(() => undefined); + await docker(["network", "rm", net], 30_000).catch(() => undefined); + rmSync(envDir, { recursive: true, force: true }); +} From 4360189aadef45e5a7de144807ebfbac70ecdbaa Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:03:23 +0300 Subject: [PATCH 2/2] fix(storage): retry D1 reads lost in transit while the database moves (#290) The failover test's first run found it: while c, the database's owner, stopped gracefully, a's site Worker got "D1_ERROR: Network connection lost" on its state read and answered RFC-0043's unavailable page (503) once. A request on its way to a Durable Object that moves is lost; the next one reaches the new owner, and Cloudflare's guidance is to retry such errors when the statement is idempotent. D1Driver now retries get and all of a read-only statement (SELECT, or WITH without a write, never RETURNING) on a lost connection or an object reset, about 2 s in all; overload, other errors, writes and batches fail as before. The failover test now records a failed answer's status, retry-after and x-cloudhal-* headers and the start of its body, and prints 300 log lines. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/d1-read-retry.md | 5 ++ docs/guides/self-host.md | 2 +- packages/storage/src/sql/d1-retry.ts | 68 ++++++++++++++++++ packages/storage/src/sql/d1.ts | 26 +++++-- packages/storage/test/d1-retry.test.ts | 99 ++++++++++++++++++++++++++ scripts/failover-smoke.ts | 20 ++++-- 6 files changed, 211 insertions(+), 9 deletions(-) create mode 100644 .changeset/d1-read-retry.md create mode 100644 packages/storage/src/sql/d1-retry.ts create mode 100644 packages/storage/test/d1-retry.test.ts diff --git a/.changeset/d1-read-retry.md b/.changeset/d1-read-retry.md new file mode 100644 index 00000000..e770a74c --- /dev/null +++ b/.changeset/d1-read-retry.md @@ -0,0 +1,5 @@ +--- +"@cloudhal/storage": patch +--- + +`D1Driver` retries a read-only `get` or `all`, about 2 s in all, when D1 lost the request in transit ("Network connection lost", a Durable Object reset). This happens when D1's object moves: on Cloudflare after a deploy or an eviction, and in a self-host cluster on every graceful handoff (RFC-0047 §7). The cluster failover test (#290) found it as one 503 page during a SIGTERM. Writes and batches are never retried, because a lost write may still have been applied. `readRetryDelaysMs: []` turns the retries off. diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index 6eac84dd..98834613 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -138,7 +138,7 @@ CI runs it against SeaweedFS and RustFS. Instances with the same `.env` and store form one installation. Each Durable Object, including the database, runs on one instance at a time, and any instance routes requests to it. A load balancer in front can send both hosts to any instance. - **Network:** the cluster port 7000 must be reachable between instances only, on a private network. Instances authenticate each other with the cluster key, but their traffic is not encrypted, so use a VPC, WireGuard, Tailscale or Docker Swarm's `encrypted` overlay. -- **Stopping:** on SIGTERM an instance hands its objects to the others and exits within 8 s. `stop_grace_period: 15s` in the compose file allows for that. +- **Stopping:** on SIGTERM an instance hands its objects to the others and exits within 8 s. `stop_grace_period: 15s` in the compose file allows for that. A database read that was on its way to the stopping instance is retried on the new owner, so pages and Studio keep answering. A write caught in that moment fails once, and Studio shows the error. - **A killed instance:** its objects move once its lease expires, about 20 s later. Until then, requests that need one of its objects (the database among them) fail, so run at least two instances behind a readiness-aware load balancer. - **Readiness:** use `GET /ready` on port 7000 as the readiness probe of a rolling restart. diff --git a/packages/storage/src/sql/d1-retry.ts b/packages/storage/src/sql/d1-retry.ts new file mode 100644 index 00000000..60c4cc3c --- /dev/null +++ b/packages/storage/src/sql/d1-retry.ts @@ -0,0 +1,68 @@ +/** + * Bounded retries of D1 reads that failed in transit (#290). D1 is one Durable Object. When the + * object moves, a request that was on its way gets "Network connection lost" or a reset, and the + * next one reaches the new owner. That move happens on Cloudflare (a deploy, an eviction) and in a + * self-host cluster on every graceful handoff (RFC-0047 §7). Cloudflare's guidance is to retry + * such errors when the statement is idempotent. Only reads are retried here: a lost write may + * still have been applied, so writes and batches fail as before and their callers decide. + */ + +/** Waits before the 2nd, 3rd, … attempt: about 2 s in all, longer than a graceful handoff. */ +export const D1_READ_RETRY_DELAYS_MS: readonly number[] = [50, 150, 300, 600, 900]; + +/** The messages of errors that never reached the database, or lost it while it moved. */ +const TRANSIENT = [ + "network connection lost", + "durable object reset", + "storage caused object to be reset", + "cannot resolve durable object due to transient issue", + "internal error in durable object storage", +]; + +/** Whether `error` (or its cause) is a D1 or Durable Object error worth retrying. */ +export function isTransientD1Error(error: unknown): boolean { + for (let e: unknown = error, depth = 0; e && depth < 4; depth++) { + const err = e as { + message?: unknown; + retryable?: unknown; + overloaded?: unknown; + cause?: unknown; + }; + if (err.overloaded === true) return false; + if (err.retryable === true) return true; + const message = typeof err.message === "string" ? err.message.toLowerCase() : ""; + if (TRANSIENT.some((t) => message.includes(t))) return true; + e = err.cause; + } + return false; +} + +/** + * A statement that only reads: it starts with `SELECT`, or with `WITH` and changes nothing. + * `RETURNING` is a write's clause, so it never counts as a read. + */ +export function isReadOnlySql(sql: string): boolean { + const head = sql.trimStart().slice(0, 6).toLowerCase(); + if (head === "select") return !/\breturning\b/i.test(sql); + if (head.startsWith("with") && !/\w/.test(head.charAt(4))) + return !/\b(?:insert|update|delete|replace|returning)\b/i.test(sql); + return false; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** Runs `read`, again after each delay while it fails with a transient error. */ +export async function retryRead( + read: () => Promise, + delays: readonly number[] = D1_READ_RETRY_DELAYS_MS, +): Promise { + for (let attempt = 0; ; attempt++) { + try { + return await read(); + } catch (error) { + const wait = delays[attempt]; + if (wait === undefined || !isTransientD1Error(error)) throw error; + await sleep(wait); + } + } +} diff --git a/packages/storage/src/sql/d1.ts b/packages/storage/src/sql/d1.ts index 33231dfe..978d1440 100644 --- a/packages/storage/src/sql/d1.ts +++ b/packages/storage/src/sql/d1.ts @@ -7,14 +7,30 @@ import { type SqlValue, StorageError, } from "../types.ts"; +import { isReadOnlySql, retryRead } from "./d1-retry.ts"; -/** Cloudflare D1 adapter. Expects the `D1Database` binding from the Worker environment. */ +export interface D1DriverOptions { + /** Waits between attempts of a read that failed in transit (`d1-retry.ts`); `[]` turns it off. */ + readonly readRetryDelaysMs?: readonly number[]; +} + +/** + * Cloudflare D1 adapter. Expects the `D1Database` binding from the Worker environment. `get` and + * `all` of a read-only statement are retried, bounded, when D1 lost the request in transit (its + * object moving to another instance or machine); writes never are. + */ export class D1Driver implements SqlDriver { readonly name = "d1"; readonly #db: D1Database; + readonly #delays: readonly number[] | undefined; - constructor(db: D1Database) { + constructor(db: D1Database, options: D1DriverOptions = {}) { this.#db = db; + this.#delays = options.readRetryDelaysMs; + } + + #read(sql: string, read: () => Promise): Promise { + return isReadOnlySql(sql) ? retryRead(read, this.#delays) : read(); } #prepare(sql: string, params: readonly SqlValue[] = []): D1PreparedStatement { @@ -26,7 +42,8 @@ export class D1Driver implements SqlDriver { sql: string, params?: readonly SqlValue[], ): Promise { - const row = await this.#prepare(sql, params).first(); + const statement = this.#prepare(sql, params); + const row = await this.#read(sql, () => statement.first()); return row ?? undefined; } @@ -34,7 +51,8 @@ export class D1Driver implements SqlDriver { sql: string, params?: readonly SqlValue[], ): Promise { - const res = await this.#prepare(sql, params).all(); + const statement = this.#prepare(sql, params); + const res = await this.#read(sql, () => statement.all()); return res.results; } diff --git a/packages/storage/test/d1-retry.test.ts b/packages/storage/test/d1-retry.test.ts new file mode 100644 index 00000000..aceba7e9 --- /dev/null +++ b/packages/storage/test/d1-retry.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "vitest"; +import { D1Driver } from "../src/sql/d1.ts"; +import { isReadOnlySql, isTransientD1Error, retryRead } from "../src/sql/d1-retry.ts"; + +/** What workerd's D1 binding threw on a read during a graceful handoff (#290). */ +const lost = () => + Object.assign(new Error("D1_ERROR: Network connection lost."), { + cause: new Error("Network connection lost."), + }); + +/** A D1 binding whose statements fail `failures` times, then answer. */ +function fakeD1(failures: number, error: () => Error = lost) { + const calls = { first: 0, all: 0, run: 0 }; + let left = failures; + const answer = (kind: keyof typeof calls, value: T) => { + calls[kind]++; + if (left > 0) { + left--; + throw error(); + } + return value; + }; + const statement = { + bind: () => statement, + first: async () => answer("first", { n: 1 }), + all: async () => answer("all", { results: [{ n: 1 }], success: true, meta: {} }), + run: async () => answer("run", { results: [], success: true, meta: { changes: 1 } }), + }; + const db = { prepare: () => statement } as unknown as D1Database; + return { db, calls }; +} + +describe("D1 read retries (#290)", () => { + it("knows reads from writes", () => { + expect(isReadOnlySql("SELECT 1")).toBe(true); + expect(isReadOnlySql(" \n select * from sites")).toBe(true); + expect(isReadOnlySql("WITH x AS (SELECT 1) SELECT * FROM x")).toBe(true); + expect(isReadOnlySql("WITH x AS (SELECT 1) DELETE FROM t WHERE id IN x")).toBe(false); + expect(isReadOnlySql("INSERT INTO t VALUES (1) RETURNING id")).toBe(false); + expect(isReadOnlySql("UPDATE t SET a = 1")).toBe(false); + expect(isReadOnlySql("SELECT 1; DELETE FROM t RETURNING id")).toBe(false); + }); + + it("retries lost connections and resets, never overload or other errors", () => { + expect(isTransientD1Error(lost())).toBe(true); + expect( + isTransientD1Error(new Error("Durable Object reset because its code was updated.")), + ).toBe(true); + expect(isTransientD1Error(Object.assign(new Error("x"), { retryable: true }))).toBe(true); + expect( + isTransientD1Error(Object.assign(new Error("x"), { retryable: true, overloaded: true })), + ).toBe(false); + expect(isTransientD1Error(new Error("D1_ERROR: no such table: sites"))).toBe(false); + expect(isTransientD1Error(undefined)).toBe(false); + }); + + it("a read that fails in transit succeeds on a later attempt", async () => { + const { db, calls } = fakeD1(2); + const sql = new D1Driver(db, { readRetryDelaysMs: [0, 0, 0] }); + expect(await sql.get("SELECT 1 AS n")).toEqual({ n: 1 }); + expect(calls.first).toBe(3); + const again = fakeD1(1); + expect(await new D1Driver(again.db, { readRetryDelaysMs: [0] }).all("SELECT 1 AS n")).toEqual([ + { n: 1 }, + ]); + expect(again.calls.all).toBe(2); + }); + + it("is bounded, and leaves writes and other errors alone", async () => { + const { db, calls } = fakeD1(10); + await expect(new D1Driver(db, { readRetryDelaysMs: [0, 0] }).get("SELECT 1")).rejects.toThrow( + "Network connection lost", + ); + expect(calls.first).toBe(3); + const write = fakeD1(1); + await expect( + new D1Driver(write.db, { readRetryDelaysMs: [0, 0] }).all( + "INSERT INTO t VALUES (1) RETURNING id", + ), + ).rejects.toThrow("Network connection lost"); + expect(write.calls.all).toBe(1); + const other = fakeD1(1, () => new Error("D1_ERROR: no such table: t")); + await expect( + new D1Driver(other.db, { readRetryDelaysMs: [0, 0] }).get("SELECT * FROM t"), + ).rejects.toThrow("no such table"); + expect(other.calls.first).toBe(1); + }); + + it("waits the given delays between attempts", async () => { + let n = 0; + const started = Date.now(); + const v = await retryRead(async () => { + if (n++ < 2) throw lost(); + return "ok"; + }, [20, 20]); + expect(v).toBe("ok"); + expect(Date.now() - started).toBeGreaterThanOrEqual(35); + }); +}); diff --git a/scripts/failover-smoke.ts b/scripts/failover-smoke.ts index 1c9eeb06..6c9e44e2 100644 --- a/scripts/failover-smoke.ts +++ b/scripts/failover-smoke.ts @@ -209,17 +209,29 @@ const post = (n: Name, p: string, body: unknown, headers: Record body: JSON.stringify(body), }); +/** + * A failed answer, with what tells its cause apart: the status, `retry-after` and the + * `x-cloudhal-*` headers (RFC-0043's status pages), and the start of the body. + */ +function failed(what: string, r: Res): string { + const headers = [...r.headers] + .filter(([k]) => k === "retry-after" || k.startsWith("x-cloudhal")) + .map(([k, v]) => `${k}: ${v}`); + const text = r.text.replace(/\s+/g, " ").slice(0, 160); + return `${what} ${r.status}${headers.length ? ` [${headers.join(", ")}]` : ""} ${text}`; +} + /** What every instance must answer while it serves: the site, Studio's API and a database read. */ async function serves(n: Name, postTitle?: string): Promise { const home = await req(`${site(n)}/`); - if (home.status !== 200 || !HOME_H1.test(home.text)) return `site / ${home.status}`; + if (home.status !== 200 || !HOME_H1.test(home.text)) return failed("site /", home); const post = await req(`${site(n)}/posts/hello-world`); - if (post.status !== 200) return `site /posts/hello-world ${post.status}`; + if (post.status !== 200) return failed("site /posts/hello-world", post); if (postTitle && !post.text.includes(postTitle)) return `the post is not "${postTitle}"`; const sites = await req(`${studio(n)}/api/admin/sites`, { headers: admin }); const listed = (sites.body as { sites?: { id: string }[] }).sites ?? []; if (sites.status !== 200 || !listed.some((s) => s.id === siteId)) - return `studio /api/admin/sites ${sites.status}`; + return failed("studio /api/admin/sites", sites); return undefined; } @@ -330,7 +342,7 @@ async function diagnostics(): Promise { for (const name of [...NAMES.map(ctr), store]) out( `${name} logs`, - await safe(() => dockerOutput(["logs", "--tail", "150", "--timestamps", name])), + await safe(() => dockerOutput(["logs", "--tail", "300", "--timestamps", name])), ); } /** `docker logs` writes the container's stderr to its own stderr. */