Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/d1-read-retry.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 11 additions & 1 deletion .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/**"
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions deploy/docker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 4 additions & 2 deletions docs/guides/self-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,12 @@ 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.
- **A killed instance:** its objects move once its lease expires, about 20 s later.
- **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.

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
Expand Down
68 changes: 68 additions & 0 deletions packages/storage/src/sql/d1-retry.ts
Original file line number Diff line number Diff line change
@@ -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<T>(
read: () => Promise<T>,
delays: readonly number[] = D1_READ_RETRY_DELAYS_MS,
): Promise<T> {
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);
}
}
}
26 changes: 22 additions & 4 deletions packages/storage/src/sql/d1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(sql: string, read: () => Promise<T>): Promise<T> {
return isReadOnlySql(sql) ? retryRead(read, this.#delays) : read();
}

#prepare(sql: string, params: readonly SqlValue[] = []): D1PreparedStatement {
Expand All @@ -26,15 +42,17 @@ export class D1Driver implements SqlDriver {
sql: string,
params?: readonly SqlValue[],
): Promise<T | undefined> {
const row = await this.#prepare(sql, params).first<T>();
const statement = this.#prepare(sql, params);
const row = await this.#read(sql, () => statement.first<T>());
return row ?? undefined;
}

async all<T extends Record<string, unknown>>(
sql: string,
params?: readonly SqlValue[],
): Promise<T[]> {
const res = await this.#prepare(sql, params).all<T>();
const statement = this.#prepare(sql, params);
const res = await this.#read(sql, () => statement.all<T>());
return res.results;
}

Expand Down
99 changes: 99 additions & 0 deletions packages/storage/test/d1-retry.test.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(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);
});
});
Loading