diff --git a/pkgs/id/nix-common.nix b/pkgs/id/nix-common.nix index 6732d4ff5f..d148c47993 100644 --- a/pkgs/id/nix-common.nix +++ b/pkgs/id/nix-common.nix @@ -94,6 +94,7 @@ let # Web development tools bun # JavaScript bundler and runtime (required for web builds) typescript # TypeScript for type checking # nodepackages remoed 2026-04-03 + wrangler # Cloudflare Worker CLI (worker-poc dev, #2271) # E2E testing (Playwright) — use playwright-driver.browsers for # pre-patched browser binaries that work with Playwright's CDP protocol. diff --git a/pkgs/id/tests/worker_poc_reference.rs b/pkgs/id/tests/worker_poc_reference.rs new file mode 100644 index 0000000000..de629d5847 --- /dev/null +++ b/pkgs/id/tests/worker_poc_reference.rs @@ -0,0 +1,170 @@ +//! Native reference runner for the #2271 Worker-isolate PoC. +//! +//! Drives the checked-in example guests through the native wasmtime host +//! (`crate::sandbox` via the public `id::sandbox` API) over the exact +//! scripted sequences the isolate side runs in +//! `pkgs/id/worker-poc/compare/isolate-runner.mjs`, and emits one JSON line +//! per step: `{world, step, event, view, records, snapshot_hex}`. Step 0 is +//! the freshly instantiated state (event `null`); step N is the state after +//! the Nth scripted event. +//! +//! The comparison harness (`worker-poc/compare/compare.mjs`) diffs these +//! lines against the isolate host's, per step — that diff is the #2271 +//! journal-equality evidence. This test also asserts the native host agrees +//! with itself across a forced cold start (fresh instance + `restore` of +//! the mid-sequence snapshot) for both worlds. +//! +//! Run standalone to regenerate the reference file: +//! WORKER_POC_REFERENCE_OUT=worker-poc/compare/native-reference.jsonl \ +//! cargo test --test worker_poc_reference -- --nocapture + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use id::sandbox::{Sandbox, SandboxLimits}; + +const COUNTER_WASM: &[u8] = include_bytes!("../examples/roc-counter/counter.wasm"); +const TIC_TAC_TOE_WASM: &[u8] = include_bytes!("../examples/tic-tac-toe/tic-tac-toe.wasm"); + +/// The #2271 scripted sequences, shared verbatim with the isolate runner. +/// Tic-tac-toe: X plays 0, O plays 4, X plays 1, O retries the occupied 4 +/// (ignored), 9 is not a move (ignored), O plays 8, X plays 2 and wins, +/// 3 after the win is ignored. +fn sequences() -> Vec<(&'static str, &'static [u8], Vec<&'static [u8]>, usize)> { + vec![ + ("roc-counter", COUNTER_WASM, vec![b"inc", b"inc", b"inc"], 2), + ( + "tic-tac-toe", + TIC_TAC_TOE_WASM, + vec![b"0", b"4", b"1", b"4", b"9", b"8", b"2", b"3"], + 5, + ), + ] +} + +fn hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push_str(&format!("{byte:02x}")); + } + out +} + +fn json_escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for ch in text.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + ch if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)), + ch => out.push(ch), + } + } + out +} + +fn step_line( + world: &str, + step: usize, + event: Option<&[u8]>, + instance: &mut id::sandbox::WorldInstance, +) -> String { + let view = String::from_utf8(instance.view().unwrap()).unwrap(); + let records = instance + .records() + .unwrap() + .map(|bytes| String::from_utf8(bytes).unwrap()); + let snapshot = instance.snapshot().unwrap(); + let event_json = match event { + Some(event) => format!( + "\"{}\"", + json_escape(&String::from_utf8(event.to_vec()).unwrap()) + ), + None => "null".to_string(), + }; + let records_json = match &records { + Some(records) => format!("\"{}\"", json_escape(records)), + None => "null".to_string(), + }; + let snapshot_json = match &snapshot { + Some(snapshot) => format!("\"{}\"", hex(snapshot)), + None => "null".to_string(), + }; + format!( + "{{\"world\":\"{world}\",\"step\":{step},\"event\":{event_json},\"view\":\"{}\",\"records\":{records_json},\"snapshot_hex\":{snapshot_json}}}", + json_escape(&view) + ) +} + +/// Run one sequence; when `cold_start_after` is `Some(step)`, restart from +/// that step's snapshot in a fresh instance before continuing. +fn run_sequence( + world: &str, + wasm: &[u8], + events: &[&[u8]], + cold_start_after: Option, +) -> Vec { + let runner = Sandbox::compile(wasm, SandboxLimits::default()).unwrap(); + let mut instance = runner.instantiate(0).unwrap(); + let mut lines = vec![step_line(world, 0, None, &mut instance)]; + for (index, event) in events.iter().enumerate() { + let step = index + 1; + if cold_start_after == Some(step - 1) { + let snapshot = instance.snapshot().unwrap().unwrap(); + instance = runner.instantiate(0).unwrap(); + instance.restore(&snapshot).unwrap(); + } + instance.update(1, event).unwrap(); + lines.push(step_line(world, step, Some(event), &mut instance)); + } + lines +} + +#[test] +fn worker_poc_reference_sequences() { + let mut all_lines: Vec = Vec::new(); + for (world, wasm, events, cold_start_after) in sequences() { + let uninterrupted = run_sequence(world, wasm, &events, None); + let cold_started = run_sequence(world, wasm, &events, Some(cold_start_after)); + assert_eq!( + uninterrupted, cold_started, + "native host diverged across a forced cold start after step {cold_start_after} in {world}" + ); + for line in &uninterrupted { + println!("{line}"); + } + all_lines.extend(uninterrupted); + } + + // The counter must actually count; guards against a vacuous equality + // pass over a guest that never mutated. + let counter_final = all_lines + .iter() + .filter(|line| line.contains("\"world\":\"roc-counter\"")) + .last() + .unwrap(); + assert!( + counter_final.contains("count=3"), + "counter final step does not show count=3: {counter_final}" + ); + // Tic-tac-toe: X completes the top row (0,1,2); the final records must + // name X the winner with five plays on the board. + let ttt_final = all_lines + .iter() + .filter(|line| line.contains("\"world\":\"tic-tac-toe\"")) + .last() + .unwrap(); + assert!( + ttt_final.contains("\\\"winner\\\":\\\"X\\\""), + "tic-tac-toe final step does not record X as winner: {ttt_final}" + ); + + if let Ok(path) = std::env::var("WORKER_POC_REFERENCE_OUT") { + let mut text = all_lines.join("\n"); + text.push('\n'); + std::fs::write(&path, text).unwrap(); + eprintln!("wrote {} reference lines to {path}", all_lines.len()); + } +} diff --git a/pkgs/id/worker-poc/.gitignore b/pkgs/id/worker-poc/.gitignore new file mode 100644 index 0000000000..b75a0fa9c3 --- /dev/null +++ b/pkgs/id/worker-poc/.gitignore @@ -0,0 +1 @@ +.wrangler/ diff --git a/pkgs/id/worker-poc/README.md b/pkgs/id/worker-poc/README.md new file mode 100644 index 0000000000..aae8c9cdf3 --- /dev/null +++ b/pkgs/id/worker-poc/README.md @@ -0,0 +1,89 @@ +# worker-poc — plaza worlds in a Worker isolate (#2271) + +PoC for developing-today/code#2271 (from the #2057 design): run one example +world **unmodified** in a Worker isolate (workerd / Durable Object with a +SQLite journal) and prove **journal equality** against the native wasmtime +host (`pkgs/id/src/sandbox.rs`): per-step `(view, records, snapshot)` + +snapshot hash over an identical scripted input sequence, including a forced +cold start mid-sequence. + +Pre-registered semantic differences (findings note on #2271, posted before +implementation): no fuel metering in Workers (CPU-time bound instead), and +the hosted loader refuses over-ceiling / `portability=native` manifests up +front where the native host traps at run time. Equality is claimed on state +evolution only, never on execution-budget behaviour. + +## Layout + +- `src/guest.ts` — `PlazaGuest`: drives only the `plaza_*` exports, with the + native host's alloc/free and output discipline (see the ABI table in the + file header). Bytes path (Node) and module path (workerd) both supported. +- `src/manifest.ts` — hosted loader: refuses `portability=native` and + declared memory over the 64MB hosted ceiling (#2057), naming the reason. +- `src/worker.ts` — one Durable Object per world; its SQLite `journal` table + is the source of truth. `POST /step` applies + journals (snapshot, view, + records, hash); `POST /cold-start` drops the in-memory guest so the next + request restores from the journal via `plaza_restore`. +- `compare/` — the journal-equality harness. `isolate-runner.mjs` runs + both scripted sequences through `PlazaGuest` (each also with a forced + cold start mid-sequence; the two runs must agree), and `compare.mjs` + diffs the per-step lines against the native reference + (`../../tests/worker_poc_reference.rs`, which drives the same sequences + through the native wasmtime host and likewise asserts its own + cold-start equality). Regenerate the reference and compare: + + ```sh + cd pkgs/id + WORKER_POC_REFERENCE_OUT=worker-poc/compare/native-reference.jsonl \ + cargo test --test worker_poc_reference -- --nocapture + cd worker-poc && npm run compare + ``` + +- `smoke/counter-smoke.mjs` — Node smoke over the prebuilt + `../examples/roc-counter/counter.wasm`: seed + `inc`×3 with per-step + view/records/snapshot-hash, a guest-level cold start (restore the step-2 + snapshot into a fresh instance, hash must match the uninterrupted run), + and both loader-refusal assertions. Run: `npm run smoke` + (Node ≥ 22, no install needed for the smoke). + +## Status vs #2271 acceptance + +- [x] Scaffold: TS isolate host instantiating the prebuilt counter guest, + driving only the `plaza_*` ABI (this change). +- [x] Counter pipeline smoke green on the isolate side (2026-11-01, laptop + Node 24): seed 0 + `inc`×3 → `count=0..3` in view and records, per-step + snapshot hashes recorded in the run; guest-level cold start (restore + step-2 snapshot, apply `inc`) reproduces the step-3 snapshot hash + `4e07408562…` exactly. +- [x] DO host hardened per Codex review on this PR (2026-11-01): SQLite + BLOB snapshots normalized to Uint8Array before plaza_restore, all + request handling serialized (shared lazy-init promise; update -> hash + -> journal insert is one unit), step inputs validated before any guest + mutation with the guest discarded on journal failure, guest output + pointers normalized unsigned, wrangler declared in nix-common.nix. + Smoke PASS + tsc clean after the fixes. +- [x] Counter sequence compared against the native reference runner + (2026-11-01): `compare/compare.mjs` diffs the isolate host against + `tests/worker_poc_reference.rs` (native `Sandbox` over the same + scripted sequence) — all steps equal in (view, records, snapshot + sha256). +- [x] tic-tac-toe scripted sequence (0,4,1,4-occupied,9-not-a-move,8, + 2-X-wins,3-after-win) equal on isolate and native hosts per step + (2026-11-01, same harness): final records + `{"board":"XXX-O---O","plays":5,"winner":"X"}` on both hosts; each + host also asserts its own forced cold start mid-sequence (native + after step 5, isolate after step 5) changes nothing. +- [x] Durable Object forced cold start mid-sequence under workerd + (2026-11-01): `compare/do-cold-start.mjs` drives the counter + through the real DO host — `/cold-start` after step 2 restores + step 2 from the SQLite journal, a full `wrangler dev` restart + (fresh DO instance) restores it again, and step 3's snapshot hash + equals the native reference hash. Full harness run: + `compare: PASS (13 steps equal)`, `do-cold-start: PASS`. +- [x] Hosted-loader refusals: `portability=native` and >64MB declared + memory, each with the reason named (asserted in the smoke). +- [x] Findings note with the pre-registered differences posted on #2271. + +Nothing here changes the native sandbox, the guest examples, or the plaza +ABI, and the native `WorldManifest` portability field is a separate Rust +follow-up that does not gate this PoC. diff --git a/pkgs/id/worker-poc/compare/compare.mjs b/pkgs/id/worker-poc/compare/compare.mjs new file mode 100644 index 0000000000..65717c4026 --- /dev/null +++ b/pkgs/id/worker-poc/compare/compare.mjs @@ -0,0 +1,58 @@ +// #2271 journal-equality harness: native wasmtime host vs Worker isolate. +// +// Compares, per step, (view, records, snapshot) over the scripted +// sequences for roc-counter and tic-tac-toe. The snapshot is compared by +// sha256 of the raw bytes (the native side emits hex; both sides are +// hashed here). Equality must hold after every step, and each side must +// already have proven equality across its own forced cold start +// mid-sequence (asserted inside both runners). +// +// Native reference first (from pkgs/id): +// WORKER_POC_REFERENCE_OUT=worker-poc/compare/native-reference.jsonl \ +// cargo test --test worker_poc_reference -- --nocapture +// Then: +// node compare/compare.mjs [path-to-native-reference.jsonl] +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { runIsolateSequences } from "./isolate-runner.mjs"; + +const nativePath = process.argv[2] ?? new URL("./native-reference.jsonl", import.meta.url).pathname; +const sha256hex = (hexStr) => + hexStr === null ? null : createHash("sha256").update(Buffer.from(hexStr, "hex")).digest("hex"); + +const nativeLines = readFileSync(nativePath, "utf8") + .trim() + .split("\n") + .map((l) => JSON.parse(l)); +const isolateLines = await runIsolateSequences(); + +let failures = 0; +if (nativeLines.length !== isolateLines.length) { + console.error(`FAIL: step count differs (native ${nativeLines.length}, isolate ${isolateLines.length})`); + failures++; +} +for (let i = 0; i < Math.min(nativeLines.length, isolateLines.length); i++) { + const n = nativeLines[i]; + const s = isolateLines[i]; + const diffs = []; + if (n.world !== s.world || n.step !== s.step || n.event !== s.event) + diffs.push(`key native=${n.world}/${n.step}/${n.event} isolate=${s.world}/${s.step}/${s.event}`); + if (n.view !== s.view) diffs.push(`view native=${JSON.stringify(n.view)} isolate=${JSON.stringify(s.view)}`); + if (n.records !== s.records) + diffs.push(`records native=${JSON.stringify(n.records)} isolate=${JSON.stringify(s.records)}`); + if (sha256hex(n.snapshot_hex) !== sha256hex(s.snapshot_hex)) + diffs.push(`snapshot sha256 native=${sha256hex(n.snapshot_hex)} isolate=${sha256hex(s.snapshot_hex)}`); + if (diffs.length) { + failures++; + console.error(`DIVERGENCE at ${n.world} step ${n.step}: ${diffs.join("; ")}`); + } else { + console.log( + `equal ${n.world} step=${n.step} event=${JSON.stringify(n.event)} view=${JSON.stringify(n.view)} records=${JSON.stringify(n.records)} snapshot_sha256=${sha256hex(n.snapshot_hex)}`, + ); + } +} +if (failures) { + console.error(`compare: FAIL (${failures} divergence(s))`); + process.exit(1); +} +console.log(`compare: PASS (${nativeLines.length} steps equal on native and isolate hosts, cold starts included)`); diff --git a/pkgs/id/worker-poc/compare/do-cold-start.mjs b/pkgs/id/worker-poc/compare/do-cold-start.mjs new file mode 100644 index 0000000000..0a47d2d8df --- /dev/null +++ b/pkgs/id/worker-poc/compare/do-cold-start.mjs @@ -0,0 +1,119 @@ +// DO-level forced cold start for #2271, under `wrangler dev` (local +// workerd, SQLite-backed Durable Object journal). +// +// Runs the roc-counter sequence against the real Worker/DO host: +// GET /state -> step 0 +// POST /step inc x2 -> steps 1, 2 +// POST /cold-start -> in-memory guest dropped; GET /state must +// restore step 2 from the SQLite journal +// wrangler dev restart -> a genuinely fresh DO instance; GET /state +// must again restore step 2 from the journal +// POST /step inc -> step 3; its snapshotHash must equal the +// native reference hash for counter step 3 +// (compare/native-reference.jsonl). +// +// Usage: node compare/do-cold-start.mjs [path-to-native-reference.jsonl] +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; + +const PORT = 8791; +const BASE = `http://127.0.0.1:${PORT}`; +const WORLD = `do-cold-start-${process.pid}`; +const url = (path) => `${BASE}${path}?world=${WORLD}`; + +const nativePath = process.argv[2] ?? new URL("./native-reference.jsonl", import.meta.url).pathname; +const native = readFileSync(nativePath, "utf8").trim().split("\n").map((l) => JSON.parse(l)); +const nativeStep3 = native.find((l) => l.world === "roc-counter" && l.step === 3); +const expectedHash = createHash("sha256").update(Buffer.from(nativeStep3.snapshot_hex, "hex")).digest("hex"); +console.log(`expected counter step-3 snapshot sha256 (native): ${expectedHash}`); + +let child = null; +function startDev() { + child = spawn("wrangler", ["dev", "--port", String(PORT), "--local"], { + cwd: new URL("..", import.meta.url).pathname, + stdio: ["ignore", "pipe", "pipe"], + detached: true, // own process group, so stopDev can reap workerd too + }); + child.stderr.on("data", (d) => process.stderr.write(`[wrangler] ${d}`)); +} +async function waitReady(tries = 60) { + for (let i = 0; i < tries; i++) { + try { + const res = await fetch(url("/state")); + if (res.ok) return await res.json(); + } catch {} + await new Promise((r) => setTimeout(r, 2000)); + } + throw new Error("wrangler dev did not become ready"); +} +async function stopDev() { + if (!child) return; + const pid = child.pid; + const done = new Promise((r) => child.once("exit", r)); + try { process.kill(-pid, "SIGTERM"); } catch { child.kill("SIGTERM"); } + await Promise.race([ + done, + new Promise((r) => setTimeout(r, 5000)).then(() => { + try { process.kill(-pid, "SIGKILL"); } catch {} + }), + ]); + child = null; + // Wait until the port is actually free, so the next dev instance binds + // instead of queueing behind a dying workerd. + for (let i = 0; i < 30; i++) { + try { + await fetch(url("/state")); + } catch { + return; + } + await new Promise((r) => setTimeout(r, 1000)); + } +} +const step = async () => { + const res = await fetch(url("/step"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ participant: 1, event: "inc" }), + }); + if (!res.ok) throw new Error(`POST /step -> ${res.status}`); + return res.json(); +}; +const state = async () => { + const res = await fetch(url("/state")); + if (!res.ok) throw new Error(`GET /state -> ${res.status}`); + return res.json(); +}; +function assertEq(actual, expected, what) { + if (actual !== expected) throw new Error(`FAIL: ${what}: got ${JSON.stringify(actual)}, want ${JSON.stringify(expected)}`); + console.log(`ok: ${what} = ${JSON.stringify(actual)}`); +} + +try { + startDev(); + const s0 = await waitReady(); + assertEq(s0.step, 0, "initial step"); + const s1 = await step(); + const s2 = await step(); + assertEq(s2.step, 2, "step after inc x2"); + + const cold = await (await fetch(url("/cold-start"), { method: "POST" })).json(); + assertEq(cold.journaledStep, 2, "journaled step at /cold-start"); + const restored = await state(); + assertEq(restored.step, 2, "step restored after /cold-start"); + assertEq(restored.snapshotHash, s2.snapshotHash, "snapshot hash restored after /cold-start"); + assertEq(restored.view, s2.view, "view restored after /cold-start"); + + await stopDev(); + startDev(); + const revived = await waitReady(); + assertEq(revived.step, 2, "step restored after wrangler restart (fresh DO instance)"); + assertEq(revived.snapshotHash, s2.snapshotHash, "snapshot hash restored after wrangler restart"); + + const s3 = await step(); + assertEq(s3.step, 3, "final step"); + assertEq(s3.snapshotHash, expectedHash, "DO step-3 snapshot hash equals native reference"); + console.log("do-cold-start: PASS"); +} finally { + await stopDev(); +} diff --git a/pkgs/id/worker-poc/compare/isolate-runner.mjs b/pkgs/id/worker-poc/compare/isolate-runner.mjs new file mode 100644 index 0000000000..21759c4285 --- /dev/null +++ b/pkgs/id/worker-poc/compare/isolate-runner.mjs @@ -0,0 +1,88 @@ +// Isolate-side runner for the #2271 comparison harness. +// +// Drives the checked-in example guests through PlazaGuest (the Worker +// isolate host) over the exact scripted sequences the native reference +// runner uses (pkgs/id/tests/worker_poc_reference.rs), and emits one JSON +// object per step: {world, step, event, view, records, snapshot_hex}. +// Step 0 is the freshly instantiated state (event null); step N is the +// state after the Nth scripted event. +// +// Each sequence is run twice: uninterrupted, and with a forced cold start +// mid-sequence (fresh PlazaGuest restored from the mid-sequence snapshot). +// Both runs must produce identical lines — the cold start is part of the +// #2271 pass condition. `runIsolateSequences()` returns the uninterrupted +// lines for comparison against the native reference. +import { readFileSync } from "node:fs"; +import { PlazaGuest } from "../src/guest.ts"; + +const enc = new TextEncoder(); +const dec = new TextDecoder(); +const hex = (b) => [...b].map((x) => x.toString(16).padStart(2, "0")).join(""); + +const SEQUENCES = [ + { + world: "roc-counter", + wasm: "../../examples/roc-counter/counter.wasm", + events: ["inc", "inc", "inc"], + coldStartAfter: 2, + }, + { + world: "tic-tac-toe", + wasm: "../../examples/tic-tac-toe/tic-tac-toe.wasm", + // X:0, O:4, X:1, O retries occupied 4 (ignored), 9 not a move + // (ignored), O:8, X:2 wins, 3 after the win (ignored). + events: ["0", "4", "1", "4", "9", "8", "2", "3"], + coldStartAfter: 5, + }, +]; + +function stepLine(world, step, event, guest) { + const snapshot = guest.snapshot(); + const records = guest.records(); + return { + world, + step, + event, + view: dec.decode(guest.view()), + records: records ? dec.decode(records) : null, + snapshot_hex: snapshot ? hex(snapshot) : null, + }; +} + +async function runSequence({ world, wasm, events, coldStartAfter }, coldStart) { + const bytes = readFileSync(new URL(wasm, import.meta.url)); + let guest = await PlazaGuest.instantiate(bytes, 0); + const lines = [stepLine(world, 0, null, guest)]; + for (let i = 0; i < events.length; i++) { + const step = i + 1; + if (coldStart && step - 1 === coldStartAfter) { + const snapshot = guest.snapshot(); + guest = await PlazaGuest.instantiate(bytes, 0); + guest.restore(snapshot); + } + guest.update(1, enc.encode(events[i])); + lines.push(stepLine(world, step, events[i], guest)); + } + return lines; +} + +export async function runIsolateSequences() { + const all = []; + for (const seq of SEQUENCES) { + const uninterrupted = await runSequence(seq, false); + const coldStarted = await runSequence(seq, true); + const a = uninterrupted.map((l) => JSON.stringify(l)); + const b = coldStarted.map((l) => JSON.stringify(l)); + if (a.join("\n") !== b.join("\n")) { + throw new Error( + `isolate host diverged across a forced cold start after step ${seq.coldStartAfter} in ${seq.world}`, + ); + } + all.push(...uninterrupted); + } + return all; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + for (const line of await runIsolateSequences()) console.log(JSON.stringify(line)); +} diff --git a/pkgs/id/worker-poc/compare/native-reference.jsonl b/pkgs/id/worker-poc/compare/native-reference.jsonl new file mode 100644 index 0000000000..583e252513 --- /dev/null +++ b/pkgs/id/worker-poc/compare/native-reference.jsonl @@ -0,0 +1,13 @@ +{"world":"roc-counter","step":0,"event":null,"view":"{\"kind\":\"screen\",\"version\":1,\"width\":20,\"height\":3,\"rows\":[\"+-counter----------+\",\"| count=0 |\",\"+------------------+\"],\"styles\":[[],[],[]]}","records":"{\"count\":0}","snapshot_hex":"30"} +{"world":"roc-counter","step":1,"event":"inc","view":"{\"kind\":\"screen\",\"version\":1,\"width\":20,\"height\":3,\"rows\":[\"+-counter----------+\",\"| count=1 |\",\"+------------------+\"],\"styles\":[[],[],[]]}","records":"{\"count\":1}","snapshot_hex":"31"} +{"world":"roc-counter","step":2,"event":"inc","view":"{\"kind\":\"screen\",\"version\":1,\"width\":20,\"height\":3,\"rows\":[\"+-counter----------+\",\"| count=2 |\",\"+------------------+\"],\"styles\":[[],[],[]]}","records":"{\"count\":2}","snapshot_hex":"32"} +{"world":"roc-counter","step":3,"event":"inc","view":"{\"kind\":\"screen\",\"version\":1,\"width\":20,\"height\":3,\"rows\":[\"+-counter----------+\",\"| count=3 |\",\"+------------------+\"],\"styles\":[[],[],[]]}","records":"{\"count\":3}","snapshot_hex":"33"} +{"world":"tic-tac-toe","step":0,"event":null,"view":"--------- plays=0 next=X","records":"{\"board\":\"---------\",\"plays\":0,\"winner\":\"\"}","snapshot_hex":"2d2d2d2d2d2d2d2d2d"} +{"world":"tic-tac-toe","step":1,"event":"0","view":"X-------- plays=1 next=O","records":"{\"board\":\"X--------\",\"plays\":1,\"winner\":\"\"}","snapshot_hex":"582d2d2d2d2d2d2d2d"} +{"world":"tic-tac-toe","step":2,"event":"4","view":"X---O---- plays=2 next=X","records":"{\"board\":\"X---O----\",\"plays\":2,\"winner\":\"\"}","snapshot_hex":"582d2d2d4f2d2d2d2d"} +{"world":"tic-tac-toe","step":3,"event":"1","view":"XX--O---- plays=3 next=O","records":"{\"board\":\"XX--O----\",\"plays\":3,\"winner\":\"\"}","snapshot_hex":"58582d2d4f2d2d2d2d"} +{"world":"tic-tac-toe","step":4,"event":"4","view":"XX--O---- plays=3 next=O","records":"{\"board\":\"XX--O----\",\"plays\":3,\"winner\":\"\"}","snapshot_hex":"58582d2d4f2d2d2d2d"} +{"world":"tic-tac-toe","step":5,"event":"9","view":"XX--O---- plays=3 next=O","records":"{\"board\":\"XX--O----\",\"plays\":3,\"winner\":\"\"}","snapshot_hex":"58582d2d4f2d2d2d2d"} +{"world":"tic-tac-toe","step":6,"event":"8","view":"XX--O---O plays=4 next=X","records":"{\"board\":\"XX--O---O\",\"plays\":4,\"winner\":\"\"}","snapshot_hex":"58582d2d4f2d2d2d4f"} +{"world":"tic-tac-toe","step":7,"event":"2","view":"XXX-O---O plays=5 winner=X","records":"{\"board\":\"XXX-O---O\",\"plays\":5,\"winner\":\"X\"}","snapshot_hex":"5858582d4f2d2d2d4f"} +{"world":"tic-tac-toe","step":8,"event":"3","view":"XXX-O---O plays=5 winner=X","records":"{\"board\":\"XXX-O---O\",\"plays\":5,\"winner\":\"X\"}","snapshot_hex":"5858582d4f2d2d2d4f"} diff --git a/pkgs/id/worker-poc/package.json b/pkgs/id/worker-poc/package.json new file mode 100644 index 0000000000..45048561df --- /dev/null +++ b/pkgs/id/worker-poc/package.json @@ -0,0 +1 @@ +{"description":"PoC (#2271): plaza_* example worlds running unmodified in a Worker isolate, journal equality vs the native wasmtime host.","devDependencies":{"typescript":"^5.6.0","wrangler":"^3.90.0"},"name":"id-worker-poc","private":true,"scripts":{"dev":"wrangler dev","smoke":"node smoke/counter-smoke.mjs","typecheck":"tsc --noEmit","compare":"node compare/compare.mjs","do-cold-start":"node compare/do-cold-start.mjs","participant-clamp":"node smoke/participant-clamp.mjs"},"type":"module"} diff --git a/pkgs/id/worker-poc/smoke/counter-smoke.mjs b/pkgs/id/worker-poc/smoke/counter-smoke.mjs new file mode 100644 index 0000000000..b9a9fe9398 --- /dev/null +++ b/pkgs/id/worker-poc/smoke/counter-smoke.mjs @@ -0,0 +1,71 @@ +// Counter pipeline smoke for the Worker isolate host (#2271, acceptance 1 + 4 +// + a guest-level preview of 3). Runs the prebuilt, unmodified counter.wasm +// through PlazaGuest under plain Node (>=22 strips the .ts types natively): +// +// node smoke/counter-smoke.mjs +// +// Sequence: seed 0, then inc x3 from participant 1. After every step it +// prints (view, records, snapshot sha256). It then forces a cold start at +// the guest level — fresh instance, plaza_restore from the step-2 snapshot — +// applies the remaining inc, and asserts the final snapshot hash equals the +// uninterrupted run's. Finally it asserts both hosted-loader refusals name +// their reasons (portability=native; declared memory over the 64MB ceiling). +import { readFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { PlazaGuest } from "../src/guest.ts"; +import { assertHostable, loadHostedGuest } from "../src/manifest.ts"; + +const wasmPath = new URL("../../examples/roc-counter/counter.wasm", import.meta.url); +const bytes = readFileSync(wasmPath); +const enc = new TextEncoder(); +const dec = new TextDecoder(); +const hash = (b) => createHash("sha256").update(b).digest("hex"); + +function stepLine(label, guest, step) { + const view = dec.decode(guest.view()); + const records = guest.records(); + const snapshot = guest.snapshot(); + console.log( + `${label} step=${step} view=${JSON.stringify(view)} records=${JSON.stringify(records ? dec.decode(records) : null)} snapshot_sha256=${snapshot ? hash(snapshot) : null}`, + ); + return snapshot; +} + +// Uninterrupted run. +const guest = await loadHostedGuest({ name: "roc-counter", portability: "portable" }, bytes, 0); +const snapshots = []; +stepLine("run", guest, 0); +for (let i = 1; i <= 3; i++) { + guest.update(1, enc.encode("inc")); + snapshots[i] = stepLine("run", guest, i); +} + +// Guest-level cold start: restore the step-2 snapshot into a fresh instance. +const revived = await PlazaGuest.instantiate(bytes, 0); +revived.restore(snapshots[2]); +revived.update(1, enc.encode("inc")); +const revivedSnap = stepLine("cold", revived, 3); +if (hash(revivedSnap) !== hash(snapshots[3])) { + console.error("FAIL: cold-start snapshot hash differs from the uninterrupted run"); + process.exit(1); +} +console.log("cold-start equality: OK (step-3 snapshot hash matches)"); + +// Hosted-loader refusals (acceptance 4). +for (const [manifest, needle] of [ + [{ name: "native-world", portability: "native" }, "portability=native"], + [{ name: "fat-world", wasm_memory_bytes: 128 * 1024 * 1024 }, "exceeds hosted ceiling"], +]) { + try { + assertHostable(manifest); + console.error(`FAIL: manifest ${manifest.name} was not refused`); + process.exit(1); + } catch (err) { + if (!String(err.message).includes(needle)) { + console.error(`FAIL: refusal for ${manifest.name} did not name '${needle}': ${err.message}`); + process.exit(1); + } + console.log(`refusal OK: ${err.message}`); + } +} +console.log("counter smoke: PASS"); diff --git a/pkgs/id/worker-poc/smoke/participant-clamp.mjs b/pkgs/id/worker-poc/smoke/participant-clamp.mjs new file mode 100644 index 0000000000..14ec72e27f --- /dev/null +++ b/pkgs/id/worker-poc/smoke/participant-clamp.mjs @@ -0,0 +1,28 @@ +// Participant clamp regression (#2271, Codex P2 on PR #3726): the native +// host clamps participant IDs to i32::MAX (sandbox.rs: +// i32::try_from(participant).unwrap_or(i32::MAX)); PlazaGuest used to wrap +// them with `| 0`, so 4294967296 became participant 0. roc-chat routes +// participant 0 through its host-event handler (input not appended), while +// any real participant appends — so the wrap is observable in the view: +// +// node smoke/participant-clamp.mjs +import { readFileSync } from "node:fs"; +import assert from "node:assert/strict"; +import { loadHostedGuest } from "../src/manifest.ts"; + +const bytes = readFileSync(new URL("../../examples/roc-chat/roc-chat.wasm", import.meta.url)); +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +async function viewAfter(participant, event) { + const guest = await loadHostedGuest({ name: "roc-chat", portability: "portable" }, bytes, 0); + guest.update(participant, enc.encode(event)); + return dec.decode(guest.view()); +} + +const atMax = await viewAfter(2147483647, "x"); +const aboveMax = await viewAfter(4294967296, "x"); +const atZero = await viewAfter(0, "x"); +assert.equal(aboveMax, atMax, "participant 4294967296 must behave as i32::MAX (clamped, not wrapped)"); +assert.notEqual(aboveMax, atZero, "clamped participant must not collapse into participant 0"); +console.log(`participant-clamp: ok (i32::MAX view ${JSON.stringify(atMax)}; participant 0 view ${JSON.stringify(atZero)})`); diff --git a/pkgs/id/worker-poc/src/guest.ts b/pkgs/id/worker-poc/src/guest.ts new file mode 100644 index 0000000000..485c5c06d3 --- /dev/null +++ b/pkgs/id/worker-poc/src/guest.ts @@ -0,0 +1,136 @@ +// PlazaGuest: a TypeScript host for plaza_* ABI guests (pkgs/id/src/sandbox.rs +// is the native reference). The guest receives NO imports; the host drives +// only the plaza_* exports and keeps the model pointer inside guest memory, +// exactly like the native WorldInstance. +// +// ABI (sandbox.rs:3-7, 199-235): +// plaza_init(i64) -> i32 model ptr +// plaza_update(i32, i32, i32, i32) -> i32 (model, participant, event ptr, event len) +// plaza_view(i32) -> i32 output ptr; length via plaza_out_len() +// plaza_records(i32) -> i32 optional +// plaza_snapshot(i32) -> i32 optional, paired with restore +// plaza_restore(i32, i32) -> i32 (snapshot ptr, len) -> model +// plaza_alloc(i32) -> i32 / plaza_free(i32, i32) +// Input discipline mirrors copy_input/free_input: allocate max(len, 1), +// pass the logical length, free with the allocation length. + +export interface GuestLimits { + messageBytes: number; +} + +export const DEFAULT_LIMITS: GuestLimits = { messageBytes: 1024 * 1024 }; + +type PlazaExports = { + memory: WebAssembly.Memory; + plaza_alloc: (len: number) => number; + plaza_free: (ptr: number, len: number) => void; + plaza_init: (seed: bigint) => number; + plaza_update: (model: number, participant: number, ptr: number, len: number) => number; + plaza_view: (model: number) => number; + plaza_records?: (model: number) => number; + plaza_snapshot?: (model: number) => number; + plaza_restore?: (ptr: number, len: number) => number; + plaza_out_len: () => number; +}; + +export class PlazaGuest { + private ex: PlazaExports; + private model: number; + private limits: GuestLimits; + + private constructor(ex: PlazaExports, model: number, limits: GuestLimits) { + this.ex = ex; + this.model = model; + this.limits = limits; + } + + static async instantiate( + bytes: ArrayBuffer | Uint8Array, + seed: number | bigint, + limits: GuestLimits = DEFAULT_LIMITS, + ): Promise { + const module = await WebAssembly.compile(bytes as BufferSource); + return PlazaGuest.fromModule(module, seed, limits); + } + + // workerd path: wrangler's CompiledWasm rule hands us a module, not bytes. + static async fromModule( + module: WebAssembly.Module, + seed: number | bigint, + limits: GuestLimits = DEFAULT_LIMITS, + ): Promise { + const instance = await WebAssembly.instantiate(module, {}); + const ex = instance.exports as unknown as PlazaExports; + for (const name of ["memory", "plaza_alloc", "plaza_free", "plaza_init", "plaza_update", "plaza_view", "plaza_out_len"] as const) { + if (ex[name] === undefined) throw new Error(`guest must export \`${name}\``); + } + if ((ex.plaza_snapshot === undefined) !== (ex.plaza_restore === undefined)) { + throw new Error("guest must export both `plaza_snapshot` and `plaza_restore`, or neither"); + } + const model = ex.plaza_init(BigInt(seed)); + return new PlazaGuest(ex, model, limits); + } + + private copyInput(input: Uint8Array): { ptr: number; len: number; allocationLen: number } { + if (input.length > this.limits.messageBytes) { + throw new Error(`guest message exceeds ${this.limits.messageBytes} bytes`); + } + const allocationLen = Math.max(input.length, 1); + const ptr = this.ex.plaza_alloc(allocationLen); + if (input.length > 0) { + new Uint8Array(this.ex.memory.buffer, ptr, input.length).set(input); + } + return { ptr, len: input.length, allocationLen }; + } + + private readOutput(outputPtr: number): Uint8Array { + const len = this.ex.plaza_out_len(); + if (len < 0) throw new Error("guest returned a negative output length"); + if (len > this.limits.messageBytes) throw new Error(`guest output exceeds ${this.limits.messageBytes} bytes`); + const mem = new Uint8Array(this.ex.memory.buffer); + // Normalize the i32 pointer to unsigned before the bounds check and the + // slice, as sandbox.rs does: a negative pointer must fail the bounds + // check, never slice from the end of memory. + const ptr = outputPtr >>> 0; + if (ptr + len > mem.length) throw new Error("guest returned output outside linear memory"); + return mem.slice(ptr, ptr + len); + } + + update(participant: number, event: Uint8Array): void { + const { ptr, len, allocationLen } = this.copyInput(event); + try { + // Clamp to i32::MAX as the native host does (sandbox.rs: + // i32::try_from(participant).unwrap_or(i32::MAX)): `participant | 0` + // alone wraps IDs above the i32 range (4294967296 becomes 0, which + // guests route differently), changing state evolution vs native. + const clamped = Math.min(participant, 2147483647); + this.model = this.ex.plaza_update(this.model, clamped | 0, ptr, len); + } finally { + this.ex.plaza_free(ptr, allocationLen); + } + } + + view(): Uint8Array { + return this.readOutput(this.ex.plaza_view(this.model)); + } + + records(): Uint8Array | null { + if (!this.ex.plaza_records) return null; + return this.readOutput(this.ex.plaza_records(this.model)); + } + + snapshot(): Uint8Array | null { + if (!this.ex.plaza_snapshot) return null; + return this.readOutput(this.ex.plaza_snapshot(this.model)); + } + + restore(snapshot: Uint8Array): void { + if (!this.ex.plaza_restore) throw new Error("guest exports no `plaza_restore`"); + const { ptr, len, allocationLen } = this.copyInput(snapshot); + try { + this.model = this.ex.plaza_restore(ptr, len); + } finally { + this.ex.plaza_free(ptr, allocationLen); + } + } +} diff --git a/pkgs/id/worker-poc/src/manifest.ts b/pkgs/id/worker-poc/src/manifest.ts new file mode 100644 index 0000000000..4f2e4ad4e0 --- /dev/null +++ b/pkgs/id/worker-poc/src/manifest.ts @@ -0,0 +1,48 @@ +// Hosted-loader manifest checks for the Worker isolate host (#2271, #2057). +// Pre-registered difference (findings note on #2271): the hosted loader +// refuses up front, naming the reason; the native host traps at run time. +import { PlazaGuest, DEFAULT_LIMITS, type GuestLimits } from "./guest.ts"; + +export const HOSTED_MEMORY_CEILING_BYTES = 64 * 1024 * 1024; // 64MB, #2057 hosted ceiling + +export interface HostedManifest { + name: string; + portability?: "portable" | "native"; + wasm_memory_bytes?: number; +} + +export function assertHostable(manifest: HostedManifest): void { + if (manifest.portability === "native") { + throw new Error( + `manifest ${manifest.name}: portability=native is not hostable in a Worker isolate`, + ); + } + if ( + manifest.wasm_memory_bytes !== undefined && + manifest.wasm_memory_bytes > HOSTED_MEMORY_CEILING_BYTES + ) { + throw new Error( + `manifest ${manifest.name}: declared memory ${manifest.wasm_memory_bytes} exceeds hosted ceiling ${HOSTED_MEMORY_CEILING_BYTES} (64MB)`, + ); + } +} + +export async function loadHostedGuest( + manifest: HostedManifest, + bytes: ArrayBuffer | Uint8Array, + seed: number | bigint, + limits: GuestLimits = DEFAULT_LIMITS, +): Promise { + assertHostable(manifest); + return PlazaGuest.instantiate(bytes, seed, limits); +} + +export async function loadHostedModule( + manifest: HostedManifest, + module: WebAssembly.Module, + seed: number | bigint, + limits: GuestLimits = DEFAULT_LIMITS, +): Promise { + assertHostable(manifest); + return PlazaGuest.fromModule(module, seed, limits); +} diff --git a/pkgs/id/worker-poc/src/worker.ts b/pkgs/id/worker-poc/src/worker.ts new file mode 100644 index 0000000000..656ee7b372 --- /dev/null +++ b/pkgs/id/worker-poc/src/worker.ts @@ -0,0 +1,204 @@ +// Worker isolate host for plaza_* worlds (#2271 PoC). +// +// One Durable Object per world. The DO's SQLite storage is the journal and +// the source of truth: every applied event is journaled with the resulting +// snapshot, so a forced cold start (fresh isolate / evicted DO instance) +// restores from the latest journaled snapshot via plaza_restore and state +// evolution continues identically. The guest module itself is imported as a +// compiled Wasm binding (COUNTER_WASM) — in the PoC that is the prebuilt, +// unmodified pkgs/id/examples/roc-counter/counter.wasm. +// +// Routes (on the DO, forwarded by the worker fetch handler): +// POST /step {participant: number, event: string} +// -> {step, view, records, snapshotHash} +// GET /state -> {step, view, records, snapshotHash} +// POST /cold-start -> drops the in-memory guest; the next request lazily +// restores from the journal (this is the forced cold start). +// +// Concurrency: Durable Objects interleave requests at every await, so all +// request handling is serialized through a per-object promise chain. Lazy +// guest initialization is shared through one promise, and a /step runs its +// update -> hash -> journal-insert as one serialized unit, so journal order +// always matches guest evolution order. +import { PlazaGuest } from "./guest.ts"; +import { loadHostedModule, type HostedManifest } from "./manifest.ts"; +// @ts-expect-error CompiledWasm import: wrangler supplies a WebAssembly.Module. +import COUNTER_WASM from "../../examples/roc-counter/counter.wasm"; + +interface SqlStorage { + exec(query: string, ...params: unknown[]): { toArray(): Record[] }; +} +interface DOState { + storage: { sql: SqlStorage }; + blockConcurrencyWhile(fn: () => Promise): Promise; +} +interface Env { + WORLD: { idFromName(name: string): unknown; get(id: unknown): { fetch(req: Request): Promise } }; +} + +const MANIFEST: HostedManifest = { name: "roc-counter", portability: "portable" }; +const SEED = 0; +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = await crypto.subtle.digest("SHA-256", bytes as BufferSource); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +// workerd returns SQLite BLOB columns as ArrayBuffer; the Node sqlite driver +// returns Uint8Array. Normalize before handing bytes to the guest. +function asBytes(value: unknown): Uint8Array { + if (value instanceof Uint8Array) return value; + if (value instanceof ArrayBuffer) return new Uint8Array(value); + throw new Error("journal snapshot is not a byte buffer"); +} + +export class WorldObject { + private sql: SqlStorage; + private guest: PlazaGuest | null = null; + private guestPromise: Promise | null = null; + private step = 0; + private chain: Promise = Promise.resolve(); + + constructor(state: DOState) { + this.sql = state.storage.sql; + this.sql.exec( + `CREATE TABLE IF NOT EXISTS journal ( + step INTEGER PRIMARY KEY, + participant INTEGER NOT NULL, + event TEXT NOT NULL, + snapshot BLOB NOT NULL, + view TEXT NOT NULL, + records TEXT, + snapshot_hash TEXT NOT NULL + )`, + ); + } + + // Run `fn` after every previously queued request has finished, so awaits + // inside one request can never interleave with another request's work. + private serialized(fn: () => Promise): Promise { + const run = this.chain.then(fn, fn); + this.chain = run.then( + () => undefined, + () => undefined, + ); + return run; + } + + // Lazy (re)instantiation: fresh init from the seed, or plaza_restore from + // the latest journaled snapshot when the journal is non-empty. This is the + // cold-start path — it runs identically after a real eviction. Concurrent + // callers share the one in-flight promise, so a guest is never built twice. + private ensureGuest(): Promise { + if (this.guest) return Promise.resolve(this.guest); + if (!this.guestPromise) { + this.guestPromise = (async () => { + const rows = this.sql + .exec(`SELECT step, snapshot FROM journal ORDER BY step DESC LIMIT 1`) + .toArray(); + const guest = await loadHostedModule(MANIFEST, COUNTER_WASM as WebAssembly.Module, SEED); + if (rows.length > 0) { + guest.restore(asBytes(rows[0].snapshot)); + this.step = rows[0].step as number; + } + this.guest = guest; + return guest; + })(); + // A failed initialization must not poison later requests. + this.guestPromise.catch(() => { + this.guestPromise = null; + }); + } + return this.guestPromise; + } + + private dropGuest(): void { + this.guest = null; + this.guestPromise = null; + } + + async fetch(req: Request): Promise { + return this.serialized(() => this.handle(req)); + } + + private async handle(req: Request): Promise { + const url = new URL(req.url); + if (req.method === "POST" && url.pathname === "/cold-start") { + this.dropGuest(); // force the next request through ensureGuest()'s restore path + return Response.json({ cold: true, journaledStep: this.step }); + } + if (req.method === "POST" && url.pathname === "/step") { + // Validate before touching the guest: a malformed request must never + // mutate state it cannot journal. + const body = (await req.json().catch(() => null)) as + | { participant?: unknown; event?: unknown } + | null; + const participant = body?.participant; + const event = body?.event; + if ( + typeof participant !== "number" || + !Number.isInteger(participant) || + participant < 0 || + typeof event !== "string" || + event.length === 0 + ) { + return Response.json( + { error: "step requires a non-negative integer participant and a non-empty string event" }, + { status: 400 }, + ); + } + const guest = await this.ensureGuest(); + guest.update(participant, enc.encode(event)); + const view = guest.view(); + const records = guest.records(); + const snapshot = guest.snapshot(); + if (!snapshot) throw new Error("guest exports no snapshot; journaling requires the snapshot/restore pair"); + const snapshotHash = await sha256Hex(snapshot); + const nextStep = this.step + 1; + try { + this.sql.exec( + `INSERT INTO journal (step, participant, event, snapshot, view, records, snapshot_hash) VALUES (?, ?, ?, ?, ?, ?, ?)`, + nextStep, participant, event, snapshot, dec.decode(view), + records ? dec.decode(records) : null, snapshotHash, + ); + } catch (err) { + // The guest advanced but nothing was journaled: discard it, so the + // next request restores from the journal and the unjournaled event + // cannot contaminate later snapshots. + this.dropGuest(); + throw err; + } + this.step = nextStep; + return Response.json({ + step: this.step, + view: dec.decode(view), + records: records ? dec.decode(records) : null, + snapshotHash, + }); + } + const guest = await this.ensureGuest(); + if (req.method === "GET" && url.pathname === "/state") { + const view = guest.view(); + const records = guest.records(); + const snapshot = guest.snapshot(); + return Response.json({ + step: this.step, + view: dec.decode(view), + records: records ? dec.decode(records) : null, + snapshotHash: snapshot ? await sha256Hex(snapshot) : null, + }); + } + return new Response("not found", { status: 404 }); + } +} + +export default { + async fetch(req: Request, env: Env): Promise { + const url = new URL(req.url); + const name = url.searchParams.get("world") ?? "default"; + const stub = env.WORLD.get(env.WORLD.idFromName(name)); + return stub.fetch(req); + }, +}; diff --git a/pkgs/id/worker-poc/tsconfig.json b/pkgs/id/worker-poc/tsconfig.json new file mode 100644 index 0000000000..242a9589ce --- /dev/null +++ b/pkgs/id/worker-poc/tsconfig.json @@ -0,0 +1 @@ +{"compilerOptions":{"allowImportingTsExtensions":true,"lib":["ES2022","DOM"],"module":"ESNext","moduleResolution":"bundler","noEmit":true,"skipLibCheck":true,"strict":true,"target":"ES2022","types":[]},"include":["src/**/*.ts"]} \ No newline at end of file diff --git a/pkgs/id/worker-poc/wrangler.toml b/pkgs/id/worker-poc/wrangler.toml new file mode 100644 index 0000000000..4773cb9760 --- /dev/null +++ b/pkgs/id/worker-poc/wrangler.toml @@ -0,0 +1,18 @@ +name = "id-worker-poc" +main = "src/worker.ts" +compatibility_date = "2024-11-01" + +# The prebuilt, unmodified example guest, compiled by wrangler's CompiledWasm +# rule and imported in src/worker.ts. +[[rules]] +type = "CompiledWasm" +globs = ["**/*.wasm"] +fallthrough = true + +[[durable_objects.bindings]] +name = "WORLD" +class_name = "WorldObject" + +[[migrations]] +tag = "v1-sqlite" +new_sqlite_classes = ["WorldObject"]