|
14 | 14 | // GET /state -> {step, view, records, snapshotHash} |
15 | 15 | // POST /cold-start -> drops the in-memory guest; the next request lazily |
16 | 16 | // restores from the journal (this is the forced cold start). |
| 17 | +// |
| 18 | +// Concurrency: Durable Objects interleave requests at every await, so all |
| 19 | +// request handling is serialized through a per-object promise chain. Lazy |
| 20 | +// guest initialization is shared through one promise, and a /step runs its |
| 21 | +// update -> hash -> journal-insert as one serialized unit, so journal order |
| 22 | +// always matches guest evolution order. |
17 | 23 | import { PlazaGuest } from "./guest.ts"; |
18 | 24 | import { loadHostedModule, type HostedManifest } from "./manifest.ts"; |
19 | 25 | // @ts-expect-error CompiledWasm import: wrangler supplies a WebAssembly.Module. |
@@ -40,10 +46,20 @@ async function sha256Hex(bytes: Uint8Array): Promise<string> { |
40 | 46 | return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); |
41 | 47 | } |
42 | 48 |
|
| 49 | +// workerd returns SQLite BLOB columns as ArrayBuffer; the Node sqlite driver |
| 50 | +// returns Uint8Array. Normalize before handing bytes to the guest. |
| 51 | +function asBytes(value: unknown): Uint8Array { |
| 52 | + if (value instanceof Uint8Array) return value; |
| 53 | + if (value instanceof ArrayBuffer) return new Uint8Array(value); |
| 54 | + throw new Error("journal snapshot is not a byte buffer"); |
| 55 | +} |
| 56 | + |
43 | 57 | export class WorldObject { |
44 | 58 | private sql: SqlStorage; |
45 | 59 | private guest: PlazaGuest | null = null; |
| 60 | + private guestPromise: Promise<PlazaGuest> | null = null; |
46 | 61 | private step = 0; |
| 62 | + private chain: Promise<unknown> = Promise.resolve(); |
47 | 63 |
|
48 | 64 | constructor(state: DOState) { |
49 | 65 | this.sql = state.storage.sql; |
@@ -60,51 +76,109 @@ export class WorldObject { |
60 | 76 | ); |
61 | 77 | } |
62 | 78 |
|
| 79 | + // Run `fn` after every previously queued request has finished, so awaits |
| 80 | + // inside one request can never interleave with another request's work. |
| 81 | + private serialized<T>(fn: () => Promise<T>): Promise<T> { |
| 82 | + const run = this.chain.then(fn, fn); |
| 83 | + this.chain = run.then( |
| 84 | + () => undefined, |
| 85 | + () => undefined, |
| 86 | + ); |
| 87 | + return run; |
| 88 | + } |
| 89 | + |
63 | 90 | // Lazy (re)instantiation: fresh init from the seed, or plaza_restore from |
64 | 91 | // the latest journaled snapshot when the journal is non-empty. This is the |
65 | | - // cold-start path — it runs identically after a real eviction. |
66 | | - private async ensureGuest(): Promise<PlazaGuest> { |
67 | | - if (this.guest) return this.guest; |
68 | | - const rows = this.sql |
69 | | - .exec(`SELECT step, snapshot FROM journal ORDER BY step DESC LIMIT 1`) |
70 | | - .toArray(); |
71 | | - const guest = await loadHostedModule(MANIFEST, COUNTER_WASM as WebAssembly.Module, SEED); |
72 | | - if (rows.length > 0) { |
73 | | - guest.restore(rows[0].snapshot as Uint8Array); |
74 | | - this.step = rows[0].step as number; |
| 92 | + // cold-start path — it runs identically after a real eviction. Concurrent |
| 93 | + // callers share the one in-flight promise, so a guest is never built twice. |
| 94 | + private ensureGuest(): Promise<PlazaGuest> { |
| 95 | + if (this.guest) return Promise.resolve(this.guest); |
| 96 | + if (!this.guestPromise) { |
| 97 | + this.guestPromise = (async () => { |
| 98 | + const rows = this.sql |
| 99 | + .exec(`SELECT step, snapshot FROM journal ORDER BY step DESC LIMIT 1`) |
| 100 | + .toArray(); |
| 101 | + const guest = await loadHostedModule(MANIFEST, COUNTER_WASM as WebAssembly.Module, SEED); |
| 102 | + if (rows.length > 0) { |
| 103 | + guest.restore(asBytes(rows[0].snapshot)); |
| 104 | + this.step = rows[0].step as number; |
| 105 | + } |
| 106 | + this.guest = guest; |
| 107 | + return guest; |
| 108 | + })(); |
| 109 | + // A failed initialization must not poison later requests. |
| 110 | + this.guestPromise.catch(() => { |
| 111 | + this.guestPromise = null; |
| 112 | + }); |
75 | 113 | } |
76 | | - this.guest = guest; |
77 | | - return guest; |
| 114 | + return this.guestPromise; |
| 115 | + } |
| 116 | + |
| 117 | + private dropGuest(): void { |
| 118 | + this.guest = null; |
| 119 | + this.guestPromise = null; |
78 | 120 | } |
79 | 121 |
|
80 | 122 | async fetch(req: Request): Promise<Response> { |
| 123 | + return this.serialized(() => this.handle(req)); |
| 124 | + } |
| 125 | + |
| 126 | + private async handle(req: Request): Promise<Response> { |
81 | 127 | const url = new URL(req.url); |
82 | 128 | if (req.method === "POST" && url.pathname === "/cold-start") { |
83 | | - this.guest = null; // force the next request through ensureGuest()'s restore path |
| 129 | + this.dropGuest(); // force the next request through ensureGuest()'s restore path |
84 | 130 | return Response.json({ cold: true, journaledStep: this.step }); |
85 | 131 | } |
86 | | - const guest = await this.ensureGuest(); |
87 | 132 | if (req.method === "POST" && url.pathname === "/step") { |
88 | | - const { participant, event } = (await req.json()) as { participant: number; event: string }; |
| 133 | + // Validate before touching the guest: a malformed request must never |
| 134 | + // mutate state it cannot journal. |
| 135 | + const body = (await req.json().catch(() => null)) as |
| 136 | + | { participant?: unknown; event?: unknown } |
| 137 | + | null; |
| 138 | + const participant = body?.participant; |
| 139 | + const event = body?.event; |
| 140 | + if ( |
| 141 | + typeof participant !== "number" || |
| 142 | + !Number.isInteger(participant) || |
| 143 | + participant < 0 || |
| 144 | + typeof event !== "string" || |
| 145 | + event.length === 0 |
| 146 | + ) { |
| 147 | + return Response.json( |
| 148 | + { error: "step requires a non-negative integer participant and a non-empty string event" }, |
| 149 | + { status: 400 }, |
| 150 | + ); |
| 151 | + } |
| 152 | + const guest = await this.ensureGuest(); |
89 | 153 | guest.update(participant, enc.encode(event)); |
90 | 154 | const view = guest.view(); |
91 | 155 | const records = guest.records(); |
92 | 156 | const snapshot = guest.snapshot(); |
93 | 157 | if (!snapshot) throw new Error("guest exports no snapshot; journaling requires the snapshot/restore pair"); |
94 | 158 | const snapshotHash = await sha256Hex(snapshot); |
95 | | - this.step += 1; |
96 | | - this.sql.exec( |
97 | | - `INSERT INTO journal (step, participant, event, snapshot, view, records, snapshot_hash) VALUES (?, ?, ?, ?, ?, ?, ?)`, |
98 | | - this.step, participant, event, snapshot, dec.decode(view), |
99 | | - records ? dec.decode(records) : null, snapshotHash, |
100 | | - ); |
| 159 | + const nextStep = this.step + 1; |
| 160 | + try { |
| 161 | + this.sql.exec( |
| 162 | + `INSERT INTO journal (step, participant, event, snapshot, view, records, snapshot_hash) VALUES (?, ?, ?, ?, ?, ?, ?)`, |
| 163 | + nextStep, participant, event, snapshot, dec.decode(view), |
| 164 | + records ? dec.decode(records) : null, snapshotHash, |
| 165 | + ); |
| 166 | + } catch (err) { |
| 167 | + // The guest advanced but nothing was journaled: discard it, so the |
| 168 | + // next request restores from the journal and the unjournaled event |
| 169 | + // cannot contaminate later snapshots. |
| 170 | + this.dropGuest(); |
| 171 | + throw err; |
| 172 | + } |
| 173 | + this.step = nextStep; |
101 | 174 | return Response.json({ |
102 | 175 | step: this.step, |
103 | 176 | view: dec.decode(view), |
104 | 177 | records: records ? dec.decode(records) : null, |
105 | 178 | snapshotHash, |
106 | 179 | }); |
107 | 180 | } |
| 181 | + const guest = await this.ensureGuest(); |
108 | 182 | if (req.method === "GET" && url.pathname === "/state") { |
109 | 183 | const view = guest.view(); |
110 | 184 | const records = guest.records(); |
|