Public: anyone can read this; the crew can change it.

A Worker-shaped hosted app under celld dev, measured against a Bun app: one example, one test, one table #16694

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/491-a-worker-shaped-hosted-app-under-celld-d → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/491-a-worker-shaped-hosted-app-under-celld-d was merged into main as 37adabf.

Review

Sign in to review this change.
9 files changed +235 −21
docs/research/celld.md +17
@@ -71,3 +71,20 @@ celld's `@cloudflare/sandbox` support with `CELLD_CONTAINER_RUNTIME=runsc` would
7171 - `charts/app` is a Helm chart that deploys the forge. The first draft called it a "k3s chart"; nothing in the repository names k3s, so the row says Helm.
7272 - `docs/SPIKE-CLOUDFLARE.md` says the front door is tested and nothing is applied, and that the bodies behind it are a Container or Fly, with Firecracker only a verdict. The first draft listed all three as behind it.
7373 - `docs/EXTRACT.md` does not mention Firecracker. It says apps need a bubblewrap or microVM sandbox before friends share a box. The first draft cited it for what Firecracker would give crew runs; the sentence now says what it does say.
74
75 ## Measured (#491, §6B)
76 **Nothing was measured, and the table below is empty on purpose.** The run that built the example had a sandbox that reaches the forge and the package registry only; `github.com` was refused, so `scripts/celld.ts` could not fetch the pinned v0.6.1 release (nor was `esbuild` on `PATH`). The example, the test and the harness are in place; the figures need one run on a machine that can download the release. Run `bun test test/celld-counter.test.ts` there (it prints a skip reason otherwise), then fill the table by timing the same `forge.json` `run` command against a Bun hello app on the same machine.

The table is the deliverable and it is blank. Fill it from a real run against a Bun hello app on the same machine, then base the recommendation on those figures.

77
78 | | Bun hello app | `examples/celld-counter` under `celld dev` |
79 |---|---|---|
80 | Cold start to first 200 | not measured | not measured |
81 | p50 of 1,000 GETs | not measured | not measured |
82 | p99 of 1,000 GETs | not measured | not measured |
83 | RSS idle | not measured | not measured |
84 | RSS after 1,000 requests | not measured | not measured |
85
86 What is known without running it:
87 - **State directory (the risk in the issue).** `celld dev` is documented to keep state in `.celld/dev` and no flag to move it was found in the brief's sources. The example symlinks `.celld` to `$FORGE_APP_DATA/celld` in its `run`, so state lands inside `FORGE_APP_DATA`; the symlink itself sits in the checkout. This is still unverified against a real binary (this run could not reach GitHub, so `celld dev` with no directory argument and a symlinked `.celld` were not exercised; the test now asserts the symlink and a non-empty `data/celld` once it can run): if celld resolves or refuses the symlink, that is the finding and the app would write outside `FORGE_APP_DATA`.
88 - **Binary on `PATH`.** `run` says `celld`, so a worker app kind would have to put the pinned binary on the app's `PATH`; the app's env (`childEnv`) keeps only the forge's `PATH`.
89
90 **Recommendation: don't open a `worker` app kind yet.** Not because the numbers are bad, but because there are none, and the one structural risk (state placement) is untested. Run the test once on a networked machine; open the kind only if the state lands in `FORGE_APP_DATA` and the idle RSS and cold start are within a small multiple of Bun's.
examples/celld-counter/README.md added +15
@@ -0,0 +1,15 @@
1 # celld-counter
2
3 A Cloudflare-Worker-shaped app: one SQLite-backed Durable Object counter.
4 `GET /` renders the count; `POST /` adds one, for a same-origin request only
5 (`Origin` host must equal `Host`). It sends CSP, `X-Content-Type-Options` and
6 `Referrer-Policy`. No dependencies.
7
8 Run: `celld` v0.6.1 on `PATH` (`scripts/celld.ts` fetches the pinned, checksummed
9 release), then `PORT=8080 FORGE_APP_DATA=/some/dir sh -c "$(jq -r .app.run forge.json)"`.
10
11 **State directory.** `celld dev` keeps state in `.celld/dev` under its working
12 directory and this was not found to take a path flag, so `forge.json` `run`
13 symlinks `.celld` to `$FORGE_APP_DATA/celld`; state lands inside `FORGE_APP_DATA`.
14 The only thing written outside it is that symlink, in the checkout. Not yet
15 verified against a real binary (see `docs/research/celld.md`, Measured).
examples/celld-counter/forge.json added +7
@@ -0,0 +1,7 @@
1 {
2 "app": {
3 "run": "mkdir -p \"$FORGE_APP_DATA/celld\" && ln -sfn \"$FORGE_APP_DATA/celld\" .celld && exec celld dev --port $PORT",
4 "install": "",
5 "health": "/healthz"
6 }
7 }
examples/celld-counter/worker.js added +56
@@ -0,0 +1,56 @@
1 // A SQLite-backed Durable Object counter. GET / renders the count; POST /
2 // increments it for a same-origin request only.
3 const HEADERS = {
4 "content-type": "text/html; charset=utf-8",
5 "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
6 "x-content-type-options": "nosniff",
7 "referrer-policy": "same-origin",
8 "cache-control": "no-store",
9 };
10
11 export class Counter {
12 constructor(ctx) {
13 this.sql = ctx.storage.sql;
14 this.sql.exec("CREATE TABLE IF NOT EXISTS n (id INTEGER PRIMARY KEY CHECK (id = 1), v INTEGER NOT NULL)");
15 this.sql.exec("INSERT OR IGNORE INTO n (id, v) VALUES (1, 0)");
16 }
17 read() {
18 return this.sql.exec("SELECT v FROM n WHERE id = 1").one().v;
19 }
20 async fetch(request) {
21 if (request.method === "POST") this.sql.exec("UPDATE n SET v = v + 1 WHERE id = 1");
22 return new Response(String(this.read()));
23 }
24 }
25
26 function sameOrigin(request) {
27 const origin = request.headers.get("origin");
28 if (!origin) return false;
29 try {
30 return new URL(origin).host === request.headers.get("host");
31 } catch {
32 return false;
33 }
34 }
35
36 const page = (n) =>
37 `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Counter</title>` +
38 `<style>body{font:1.2rem system-ui;margin:3rem auto;max-width:20rem}</style>` +
39 `<h1>Count: <output>${Number(n) | 0}</output></h1><form method="post" action="/"><button>Add one</button></form>`;
40
41 export default {

/healthz returns only x-content-type-options. Spread HEADERS so every response carries the CSP and Referrer-Policy as well.

42 async fetch(request, env) {
43 const url = new URL(request.url);
44 if (url.pathname === "/healthz") return new Response("ok", { headers: HEADERS });
45 if (url.pathname !== "/") return new Response("not found", { status: 404, headers: HEADERS });
46 if (request.method !== "GET" && request.method !== "POST")
47 return new Response("method not allowed", { status: 405, headers: { ...HEADERS, allow: "GET, POST" } });
48 if (request.method === "POST" && !sameOrigin(request))
49 return new Response("cross-origin request refused", { status: 403, headers: HEADERS });
50 const stub = env.COUNTER.get(env.COUNTER.idFromName("main"));
51 const res = await stub.fetch(new Request("http://do/", { method: request.method }));
52 const n = await res.text();
53 if (request.method === "POST") return new Response(null, { status: 303, headers: { ...HEADERS, location: "/" } });
54 return new Response(page(n), { headers: HEADERS });
55 },
56 };
examples/celld-counter/wrangler.json added +7
@@ -0,0 +1,7 @@
1 {
2 "name": "celld-counter",
3 "main": "worker.js",
4 "compatibility_date": "2025-01-01",
5 "durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter" }] },
6 "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }]
7 }
scripts/test-honesty-allow.json +1 −1
@@ -188,7 +188,6 @@
188188 "test/following.test.ts": {"wait":6},
189189 "test/footing.test.ts": {"wait":4},
190190 "test/forge-archive.test.ts": {"wait":1},
191 "test/forge-cloudflare-celld.test.ts": {"wait":1},
192191 "test/forge-origin-oauth.test.ts": {"timeout":1,"wait":1},
193192 "test/forge-origin-retry.test.ts": {"timeout":1},
194193 "test/forge-origin.test.ts": {"timeout":1},
@@ -218,6 +217,7 @@
218217 "test/helpers/apps-forge.ts": {"wait":2},
219218 "test/helpers/cell-looks-e2e.ts": {"wait":2},
220219 "test/helpers/cell-probe.ts": {"wait":1},
220 "test/helpers/celld_serve.ts": {"wait":1},
221221 "test/helpers/checks-forge.ts": {"wait":2},
222222 "test/helpers/chrome.ts": {"wait":6},
223223 "test/helpers/handover-roll.ts": {"wait":6},
test/celld-counter.test.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * examples/celld-counter booted the way src/apps/process.ts boots an app: the
3 * forge.json `run` under /bin/sh -c, an explicit env with PORT and
4 * FORGE_APP_DATA. Skips, saying why, when celld cannot be fetched or esbuild is
5 * missing. Not in the forge.json gate: it needs a GitHub download.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { cpSync, lstatSync, mkdirSync, readdirSync, readlinkSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { celld } from "../scripts/celld";
12 import { freePort, until } from "./helpers/celld_serve";
13
14 const example = join(import.meta.dir, "../examples/celld-counter");
15
16 let skip = "";
17 let bin = "";
18 if (!Bun.which("esbuild")) skip = "esbuild is not on PATH (celld bundles with it)";
19 else
20 try {
21 bin = await celld();
22 } catch (e) {
23 skip = `celld cannot be fetched: ${(e as Error).message}`;
24 }
25 if (skip) console.warn(`celld-counter skipped: ${skip}`);
26
27 let root = "";
28 let app = "";
29 let data = "";
30 let proc: ReturnType<typeof Bun.spawn> | undefined;
31 let base = "";
32
33 async function start(): Promise<void> {
34 const port = freePort();
35 base = `http://127.0.0.1:${port}`;
36 const run = (await Bun.file(join(example, "forge.json")).json()).app.run as string;
37 proc = Bun.spawn(["/bin/sh", "-c", run], {
38 cwd: app,
39 env: {
40 PATH: `${join(root, "bin")}:${process.env["PATH"] ?? "/usr/bin:/bin"}`,
41 HOME: process.env["HOME"] ?? "/",
42 PORT: String(port),
43 HOST: "127.0.0.1",
44 NODE_ENV: "production",
45 FORGE_APP_DATA: data,
46 },
47 stdout: "ignore",
48 stderr: "ignore",
49 });
50 expect((await until(base, "/healthz")).status).toBe(200);
51 }
52
53 async function stop(): Promise<void> {
54 proc?.kill("SIGKILL");
55 await proc?.exited;
56 proc = undefined;
57 }
58
59 async function count(): Promise<number> {
60 const html = await (await until(base, "/")).text();
61 return Number(/<output>(\d+)<\/output>/.exec(html)?.[1]);
62 }
63
64 const post = (origin: string) =>
65 fetch(base + "/", { method: "POST", headers: { origin }, redirect: "manual" });
66
67 describe.skipIf(skip !== "")("celld-counter", () => {
68 beforeAll(() => {
69 root = mkdtempSync(join(tmpdir(), "forge-celld-counter-"));
70 app = join(root, "app");
71 data = join(root, "data");
72 cpSync(example, app, { recursive: true });
73 mkdirSync(data);
74 mkdirSync(join(root, "bin"));
75 symlinkSync(bin, join(root, "bin", "celld"));
76 });
77 afterAll(async () => {
78 await stop();
79 rmSync(root, { recursive: true, force: true });
80 });
81
82 test("/ answers with the security headers", async () => {
83 await start();
84 const res = await until(base, "/");
85 expect(res.status).toBe(200);
86 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
87 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
88 expect(res.headers.get("referrer-policy")).toBe("same-origin");
89 const health = await until(base, "/healthz");
90 expect(health.headers.get("content-security-policy")).toContain("default-src 'none'");
91 expect(health.headers.get("referrer-policy")).toBe("same-origin");
92 });
93
94 test("a cross-origin POST is refused; a same-origin one counts", async () => {
95 const before = await count();
96 expect((await post("https://evil.example")).status).toBe(403);
97 expect(await count()).toBe(before);
98 expect((await post(base)).status).toBe(303);
99 expect(await count()).toBe(before + 1);
outdated

The test name says 'in FORGE_APP_DATA' but nothing asserts it. After the restart, read data/celld (non-empty) and check that .celld in the app dir is a symlink to it.

100 });
101
102 test("the count survives a stop and start, in FORGE_APP_DATA", async () => {
103 const before = await count();
104 await stop();
105 await start();
106 expect(await count()).toBe(before);
107 expect(lstatSync(join(app, ".celld")).isSymbolicLink()).toBe(true);
108 expect(readlinkSync(join(app, ".celld"))).toBe(join(data, "celld"));
109 expect(readdirSync(join(data, "celld"), { recursive: true }).length).toBeGreaterThan(0);
110 });
111 });
test/forge-cloudflare-celld.test.ts +2 −20
@@ -9,13 +9,7 @@ import { cpSync, mkdtempSync, rmSync } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { celld } from "../scripts/celld";
12
13 function freePort(): number {
14 const s = Bun.serve({ port: 0, fetch: () => new Response() });
15 const port = s.port as number;
16 s.stop(true);
17 return port;
18 }
12 import { freePort, until } from "./helpers/celld_serve";
1913
2014 let skip = "";
2115 let bin = "";
@@ -34,18 +28,6 @@ let proc: ReturnType<typeof Bun.spawn> | undefined;
3428 let dir = "";
3529 let base = "";
3630
37 async function until(path: string): Promise<Response> {
38 const end = Date.now() + 60_000;
39 for (;;) {
40 try {
41 return await fetch(base + path);
42 } catch (e) {
43 if (Date.now() > end) throw e;
44 await Bun.sleep(100);
45 }
46 }
47 }
48
4931 beforeAll(async () => {
5032 if (skip) return;
5133 stub = Bun.serve({
@@ -83,7 +65,7 @@ afterAll(async () => {
8365
8466 describe.skipIf(!!skip)("forge-cloudflare worker on celld", () => {
8567 test("a GET and a POST reach the body, told https", async () => {
86 const get = await until("/a/b?x=1");
68 const get = await until(base, "/a/b?x=1");
8769 expect(get.status).toBe(200);
8870 expect(await get.text()).toBe("body ok");
8971 const post = await fetch(`${base}/post`, { method: "POST", body: "hello" });
test/helpers/celld_serve.ts added +19
@@ -0,0 +1,19 @@
1 /**
2 * What the two celld tests share: a free loopback port (the forge's own), and a GET that waits for
3 * a booting server.
4 */
5
6 export { freePort } from "../../src/apps/process";
7
8 /** GET `base + path`, retrying while the connection is refused, for up to a minute. */
9 export async function until(base: string, path: string): Promise<Response> {
10 const end = Date.now() + 60_000;
11 for (;;) {
12 try {
13 return await fetch(base + path);
14 } catch (e) {
15 if (Date.now() > end) throw e;
16 await Bun.sleep(100); // real-timer: a child process is booting; there is no clock to step
17 }
18 }
19 }

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs