The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Promises in game code: pending jobs run at the end of the entry that queued them; a message without move means no stick (#54)
Evan (Yifeng) Wang716f1d359c6f
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 37432c5..1515376 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -47,14 +47,76 @@ runtime, and drives the engine directly, the way a UE game drives its actors:| Scene binding | `packages/scene/src/engine.ts` `SceneBinding` | Keeps the engine in step with a DSL scene. Objects report their own changes (core.ts change tracking: transforms, visibility, power, shadow flag, mesh geometry / material, add / remove), so a sync visits only what changed. Lights, cameras and materials are compared against what was last sent. || World | `renderer/src/world.rs` | The engine's objects, resources, environment and settings, and what changed since the last commit: parameter changes (power, light / material parameters, environment, camera) or structural ones. Asset paths must stay inside the asset root (game code is untrusted on nodes). || Live commit | `renderer/src/live.rs` `LiveCore::commit`, `tables.rs` | Parameter changes rewrite GPU table entries in place (materials, lights, object power, emitter CDF, wetness / rain / fog, camera), and so does hiding or showing a volume, a light without a card or a particle system that is not light-sampled by its own `visible`. Anything structural rebuilds the GPU scene from the world, in memory; history survives, validated per pixel. |-| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers; what needs the outside is asked of the app, "The host channel"). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |-| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, `hostMessages(list, ts)` (the app's messages), and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. |+| Scene runtime | `renderer/src/script.rs` `ScriptHost` | QuickJS (rquickjs) with no I/O (no fs, network or timers; what needs the outside is asked of the app, "The host channel"). Loads a bundle (one script) or ES modules (`game.js` + `threert-runtime.js`, the cloud layout). Memory capped at 1 GiB. Time budgets: setup 120 s, event 1 s, frame 50 ms; the interrupt handler aborts overruns. Every entry ends by running the promise jobs it left, inside its budget ("Promises", below). The time the engine spends inside a voxel call (`voxelExplode`, `voxelEdit`, `voxelFrame`) is the engine's, not the script's: the deadline moves by it as measured, up to 250 ms an entry; past that it counts against the script, and a voxel call made after the deadline throws "interrupted" at once. A prelude adds `TextEncoder`, `structuredClone`, `atob` and `console`. |+| Node host | `packages/gameplay/src/node-host.ts` | `globalThis.__threert`: `setup(room, seed)`, `event(type, payload, ts)` (local authority: execute + commit), `commit(writes, seq)` / `setState(state, seq)` (room authority), `state()`, `frame(dt, now)`, `hostMessages(list, ts)` (the app's messages), `sync()` (the engine follows the scene once more: after an entry's promise jobs), and the editor's `outline()`, `inspect(name)`, `edit(name, path, value)`. || World handlers | `packages/gameplay/src/world.ts` | `on[type](world, ev)`: an event handled on this node, changing the scene at once. `WorldContext`: `scene`, `camera`, read-only `state`, `object(id)`, `time`, `now`, `random()`, `emit(type, payload)`. || Frame scripts | `packages/gameplay/src/frame.ts` | `FrameContext`: `time`, `dt`, `snap`, `now`, read-only `state`, `scene`, `camera`, `object(id)`, `random()`, `input`. || Host channel | `packages/gameplay/src/host.ts`, `input.ts`, `hud.ts`; `renderer/src/host.rs`, `script.rs` (`__host_post`, `GameSession::take_posts` / `host_messages`) | Messages between game code and the app that embeds the engine: the app's input every frame (`f.input`), sockets and HTTP the app owns (`net.*`), the HUD the app draws (`hud.set`), how the game was opened (`launch`). See "The host channel" below. || Game session | `renderer/src/script.rs` `GameSession` | A runtime + its live view: events, clicks (CPU pick → `click {target, point, ray: {origin, direction}}`, with `instanceId` on an `InstancedMesh`; `ray` is the view ray, for a `Raycaster`), frame script, the physics world's ticks, editor edits, each followed by a commit. Shared by `play`, `live` and the playground. || Physics | `renderer/physics-core` (`Physics` on Rapier, `bridge::Bridge`), `renderer/src/physics.rs`, `packages/scene` (`Object3D.physics`, joints, `Raycaster.intersectPhysics`, `Shapecaster`) | The session's physics world, made by the first physics call (none: nothing runs). The engine steps it at 1 / 60 s after the frame script (at most 5 ticks a frame; offline renders step to their scene time) and places the objects of the bodies that moved: instances, so a move is a TLAS transform. Scripts cannot step it. See "Physics" below. |+### Promises++QuickJS has no event loop of its own: a promise's callbacks are jobs that somebody has to run. The runtime runs them+at the end of every entry into the script (`ScriptHost::enter`: the loading of the bundle, setup, an event, a frame,+a batch of host messages, `commit` / `setState`, `seek`, an editor call), until none is left: a `.then` callback, the+code after an `await`, and the jobs those queue in turn. That is when a browser runs them: when the script that was+called has returned.++```ts+// A request as a promise (what a library makes of `net.fetch`): the app's answer is a later message.+const answers = new Map<string, (m: HostEvents["net.fetched"]) => void>();+host.on("net.fetched", (m) => answers.get(m.id)?.(m));+const fetched = (id: string, url: string) =>+ new Promise<HostEvents["net.fetched"]>((resolve) => {+ answers.set(id, resolve);+ host.post({ t: "net.fetch", id, url });+ });++async function load(url: string, scene: Scene) {+ const m = await fetched("level", url); // goes on in the entry of the batch that brings `net.fetched`+ scene.add(build(JSON.parse(m.body))); // in the engine when that entry returns+}+host.on("launch", (m, world) => void load(String(m.params.level), world.scene)); // the listener returns no promise+```++- **A promise resolves at the end of the entry that resolved it.** `Promise.resolve(x).then(f)` in a frame script+ runs `f` in that frame, before the frame's physics ticks and its commit; so does the code after an `await` of a+ promise that is settled by then, in a frame script, a handler, a world handler, a listener or setup.+- **There are still no timers and no I/O**, so nothing resumes on its own. A promise only the app can settle (the+ request above) stays pending through the frames in between, and its awaiter runs in the entry that settles it: a+ host message, an event, a frame. One that nothing settles never goes on.+- **The jobs run when the entry's own code is over**, not inside it. For the code after an `await` the event has+ ended: `Math.random` and `Date` are the host's again, a `world` shows the state as it was, and its `emit` throws+ (the handler's emits were taken when it returned; start a state transaction while a handler or a listener runs,+ for example in the listener that hears the answer). The scene is the scene: what the jobs changed in it goes to the+ engine when they have run (the runtime calls the node host's `sync()` after them; the entry's own sync came+ before), so the commit that follows the entry applies it.+- **`setup`, handlers, world handlers and host listeners return no promise themselves.** An `async` function as one+ of them is the error it was (`handlers must be synchronous`, `world handlers must be synchronous`, `host listeners+ must be synchronous`), and an `async` setup is one now too (`setup must be synchronous: it returns { scene, camera+ }, not a promise`): setup is not awaited, a scene is built when it returns. What any of them starts and does not+ wait for (`void load()`, a `.then`) runs as above; from setup that is at the end of the setup entry, and may add to+ the scene setup returned. A frame script's return value is not looked at.+- **Inside the entry's budget.** The deadline of the entry holds for its jobs: one that spins is interrupted, and a+ chain that never ends (`const again = () => Promise.resolve().then(again)`, an `async` loop of awaits) is ended+ when the time is up. The entry then fails as one that overran does (`interrupted`). The jobs not run stay queued+ and run after the next entry, so a chain that queues itself for ever fails every entry until the script stops it.+- **Errors.** What a callback throws rejects its promise. A promise rejected that nothing has handled when the+ entry's jobs have run is reported once, as an error line with its reason: `unhandled rejection: TypeError: ... (at+ ...)` in the game's log (stderr `[game error]`, the log sink), and for an event in the event's log (`✗ unhandled+ rejection: ...`). At most eight an entry by their reasons; the rest are counted. One that gets its handler later+ in the same entry (a `catch` added by a later job, an `await` in a `try`) is not reported; one handled in a later+ entry was.+- **In a browser** (`renderer/web`, the three.js view) the page's engine runs the jobs, at the same point, so game+ code behaves the same there. Nothing calls `sync()` after them: what they changed in the scene goes to the engine+ with the next entry's sync (the next frame's, where frames run).+- Checked: `renderer/src/script.rs` tests (a `.then` chain and an `await` in a frame, an event and a batch of host+ messages run within the entry, and what they changed is synced after them; a promise a later host message resolves;+ a chain that never ends; rejections reported once), `packages/gameplay/test/promises.test.ts` (the node host's+ `sync`, `emit` after the handler, what stays synchronous), and `node tools/host-echo.ts` (`games/host/echo.game.ts`+ awaits its page as the promise above, in `live`, `play` and Chrome).+## Entry points```@@ -116,7 +178,9 @@ export default defineGame({event; then the handler's transaction; then what the world handler emitted, in order; then the frame script showsthe new state. A room that is the authority runs `handlers` on its own, so neither may rely on the other having run.- **`keys`** map to either; `describe()` lists them as `on`; a game of world handlers only needs no `handlers`.-- **Synchronous:** no await, as for handlers.+- **Synchronous**, as handlers are: a world handler returns no promise (an `async` function as one is an error).+ What it starts with promises runs when the event is over ("Promises", above): the scene it changes there is+ synced, but `world.emit` throws.- **A world handler that throws** does not stop the world, as a frame script that throws does not: what it had changedis synced, the event's handler and the next tick run all the same, and the error is in the event's log.- **In a room:** they do not run. A node that follows a room gets committed state, not events; an event with a world@@ -303,7 +367,9 @@ export default defineGame({context as their second argument (`scene`, `camera`, the committed `state`, `object(id)`, `time`, `now`,`random()`, `emit`, `input`). What they change in the scene reaches the engine when the batch returns, once.What they `emit` are state transactions, run after the batch's listeners, followed by the frame script as after- any event. A listener that throws does not stop the batch: the error is logged and the next listener runs.+ any event. A listener that throws does not stop the batch: the error is logged and the next listener runs. A+ listener returns no promise; the code after an `await` it started runs at the end of the batch's entry, or of the+ later entry that settles what it waits for ("Promises", above).- **The same object is `globalThis.__threert_host`** (`{ post, on, launch }`), for a library that does not import`@threert/gameplay`. A second copy of the package in one runtime finds the first's channel.- **It is not one of the four channels** of "The runtime's shape" below: those are between the script and the@@ -401,7 +467,7 @@ Game code reads it as `f.input` in the frame script and `world.input` in world h| `input.down(key)` | the key is held || `input.pressed(key)`, `input.released(key)` | it went down / up since the last frame || `input.axis(negative, positive)` | -1, 0 or 1 from two keys |-| `input.move` | `{ x, y }`: the app's move stick if it sent one, else W A S D; x right, y forward, never longer than 1 |+| `input.move` | `{ x, y }`: the app's move stick if its last message had one, else W A S D; x right, y forward, never longer than 1 || `input.look` | `{ dx, dy }`, radians to turn this frame: right and down are positive || `input.button(n)` | mouse button `n` is held (0 left, 1 middle, 2 right); the same as `down("Mouse<n>")`, and `pressed("Mouse0")` is its edge || `input.pointer` | `{ u, v }`, 0..1 from the picture's top left; (0.5, 0.5) while captured |@@ -418,7 +484,7 @@ The message, every field optional but `t`:| `dx`, `dy` | look since the last message, radians || `wheel` | notches since the last message || `captured` | the pointer is captured |-| `move: [x, y] \| null` | a move stick (gamepad, touch), each -1..1; `null` or left out: none |+| `move: [x, y] \| null` | a move stick (gamepad, touch), each -1..1; `null` or left out: none, and `input.move` is the keys' (the one field a message does not keep from the message before: an app with a stick sends it every frame) |- **Keys are named by their place on a US keyboard**, not by what the layout prints (W A S D stay where they are onAZERTY): `"A"`–`"Z"`, `"0"`–`"9"`, `"Space"`, `"Shift"`, `"Ctrl"`, `"Alt"`, `"Meta"`, `"Tab"`, `"Enter"`,diff --git a/games/host/echo.game.ts b/games/host/echo.game.tsindex 07552b4..01833d8 100644--- a/games/host/echo.game.ts+++ b/games/host/echo.game.ts@@ -9,24 +9,41 @@// state in `frame` like anything else that happens in the game.// - An app without a network never answers. The game then stays as it started: the cube on the ground, the HUD// saying "offline".+// - The request is written the way a library would wrap it, as a promise (`fetched`): the app's answer, a later+// message, resolves it, and the code after the `await` runs in that message's entry (docs/RUNTIME.md "Promises").//// node tools/bundle-game.ts games/host/echo.game.ts -o out/bundles/host-echo.js// renderer/target/release/threert-render play out/bundles/host-echo.js --launch '{"url":"wss://echo.example/socket"}'// node tools/host-echo.ts (the channel checked: this script as the app, then the window's real sockets)import { BoxGeometry, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera, Scene, SkyAtmosphere } from "@threert/scene";-import { defineGame, host, hud } from "@threert/gameplay";+import { defineGame, host, hud, type HostEvents } from "@threert/gameplay";/** How many messages the game answers before it closes the socket. */export const ROUNDS = 3;const SOCKET = "echo";let status = "offline";+/** `net.fetch` as a promise of its answer. (No timers: it settles when the app answers, in a message.) */+const answers = new Map<string, (m: HostEvents["net.fetched"]) => void>();+host.on("net.fetched", (m) => answers.get(m.id)?.(m));+const fetched = (id: string, url: string) =>+ new Promise<HostEvents["net.fetched"]>((resolve) => {+ answers.set(id, resolve);+ host.post({ t: "net.fetch", id, url });+ });++async function page(url: string): Promise<void> {+ const m = await fetched("page", url);+ console.log(`echo fetched ${m.status} ${JSON.stringify(m.body.slice(0, 40))}${m.error ? ` ${m.error}` : ""}`);+}+host.on("launch", (m) => {if (typeof m.params.url === "string") {status = "connecting";host.post({ t: "net.open", id: SOCKET, url: m.params.url });}- if (typeof m.params.fetch === "string") host.post({ t: "net.fetch", id: "page", url: m.params.fetch });+ // (A listener returns no promise itself: what it starts goes on after it.)+ if (typeof m.params.fetch === "string") void page(m.params.fetch);});host.on("net.opened", (m) => {status = "open";@@ -46,7 +63,6 @@ host.on("net.closed", (m) => {status = `closed (${m.code})`;console.log(`echo closed ${m.code} ${m.reason}`);});-host.on("net.fetched", (m) => console.log(`echo fetched ${m.status} ${JSON.stringify(m.body.slice(0, 40))}${m.error ? ` ${m.error}` : ""}`));export default defineGame({state: { received: 0 },diff --git a/packages/gameplay/src/game.ts b/packages/gameplay/src/game.tsindex fb0d183..2a8176d 100644--- a/packages/gameplay/src/game.ts+++ b/packages/gameplay/src/game.ts@@ -30,7 +30,8 @@ export interface GameDefinition<S = JsonObject> {seed?: number;/** Initial JSON state. */state: S;- /** Builds the scene (render nodes, the editor). Deterministic per seed: no Math.random / Date beyond ctx. */+ /** Builds the scene (render nodes, the editor). Deterministic per seed: no Math.random / Date beyond ctx.+ * Synchronous: it returns the scene, not a promise of one (an `async` setup is an error). */setup(ctx: SetupContext): SetupResult;handlers: Record<string, Handler<S>>;/** Handles "tick" events (`{dt}` payload, seconds) unless a "tick" handler exists. */@@ -107,6 +108,11 @@ export function buildScene(game: GameDefinition<unknown>, opts: { roomId: string// Event ids start at 1, so stream 0 is reserved for setup.const random = seededRandom(seed, 0);const r = withDeterminism(opts.ts ?? 0, random, () => game.setup({ roomId: opts.roomId, seed, random }));+ // (Nothing waits for a promise here: a scene is built when setup returns. What setup starts with promises runs+ // after it and may add to the scene it returned.)+ if (typeof (r as unknown as PromiseLike<unknown> | undefined)?.then === "function") {+ throw new Error("setup must be synchronous: it returns { scene, camera }, not a promise (setup is not awaited; build the scene, and add what arrives later to it)");+ }return { ...r, seed };}diff --git a/packages/gameplay/src/host.ts b/packages/gameplay/src/host.tsindex 6cd79aa..1f6b491 100644--- a/packages/gameplay/src/host.ts+++ b/packages/gameplay/src/host.ts@@ -13,6 +13,9 @@// batch returns. `world.emit(type, payload)` starts a state transaction.// - A listener that throws does not stop the batch: the next listener and the next message run all the same, and// the error is logged.+// - A listener returns no promise (an `async` function as one is an error). What it starts with promises goes on when+// the batch's entry is over, or the later entry that settles what it waits for (docs/RUNTIME.md "Promises"): a+// request wrapped as a promise that the app's answer resolves is awaited that way.// - An app may implement none of it. A post nobody takes is dropped (`post` returns false when no app is there),// and a game must not wait for an answer in order to go on.// - The same object is `globalThis.__threert_host`, for a library that does not import this package.diff --git a/packages/gameplay/src/input.ts b/packages/gameplay/src/input.tsindex d85bbcc..ba25983 100644--- a/packages/gameplay/src/input.ts+++ b/packages/gameplay/src/input.ts@@ -24,7 +24,8 @@// - A frame without an input message: what was held stays held, nothing is pressed or released, `look` and `wheel`// are 0.-/** The app's input message: everything optional but `t`; a field left out keeps (state) or is 0 (deltas). */+/** The app's input message: everything optional but `t`; a field left out keeps (state) or is 0 (deltas), except+ * `move`: a message without it says there is no stick. */export interface InputMessage {t: "input";/** Every key and mouse button held now (the names above). */@@ -133,7 +134,8 @@ export class InputState implements Input {this.wheel += finite(m.wheel);if (m.u !== undefined || m.v !== undefined) this.pointer = { u: finite(m.u, this.pointer.u), v: finite(m.v, this.pointer.v) };if (m.captured !== undefined) this.captured = m.captured === true;- if (m.move !== undefined) this.stick = Array.isArray(m.move) ? [Math.max(-1, Math.min(1, finite(m.move[0]))), Math.max(-1, Math.min(1, finite(m.move[1])))] : null;+ // (Null or left out: no stick, and `move` is the keys'. An app with a stick sends it in every message.)+ this.stick = Array.isArray(m.move) ? [Math.max(-1, Math.min(1, finite(m.move[0]))), Math.max(-1, Math.min(1, finite(m.move[1])))] : null;}/** A frame script ran: what was pressed, released, turned and scrolled is over. */diff --git a/packages/gameplay/src/node-host.ts b/packages/gameplay/src/node-host.tsindex 4a4f5dc..aa4c838 100644--- a/packages/gameplay/src/node-host.ts+++ b/packages/gameplay/src/node-host.ts@@ -13,6 +13,9 @@// hostMessages(list, ts) the app's messages (host.ts), a batch in one entry: `input` is kept for `f.input`// and `world.input` (input.ts), the others go to their `host.on` listeners, which// change the scene as world handlers do+// sync() the engine follows the scene once more: the renderer calls it when promise jobs+// ran after an entry (a `.then` callback, the code after an `await`: they run when+// the entry is over, after its own sync), so what they changed is in the same commit// seek(time, now) the frame script's clock set to `time`, the scene shown settled at that moment (an// offline render at a scene time: the timeline a frame script draws)// outline() / inspect(name) / edit(name, path, value) the editor: the live scene, not a document (name "" = the@@ -42,6 +45,7 @@ export interface NodeHost {state(): string;frame(dt: number, now: number): void;hostMessages(list: string, ts: number): void;+ sync(): void;seek(time: number, now: number): void;outline(): string;inspect(name: string): string;@@ -198,6 +202,8 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):for (const error of withDeterminism(ts, random, () => channel.deliver(m, world))) console.error(`host message ${m.t}: ${error}`);}if (!ctx) return;+ // (The batch's listeners have run: what they emitted is taken below, and a later `emit` on their world throws.)+ ctx.close();// As after a world handler: the engine follows the scene as the listeners left it; the state events they// emitted are transactions, and the frame script then shows the new state.if (!ctx.emits.length) {@@ -210,6 +216,11 @@ export function installNodeHost(game: GameDefinition<unknown>, engine?: Engine):refresh(ts);},+ sync() {+ // (Before setup there is no scene to follow: jobs a bundle left while loading.)+ binding?.sync();+ },+seek(time, now) {live().frames.seek(time);refresh(now, true);diff --git a/packages/gameplay/src/world.ts b/packages/gameplay/src/world.tsindex 2c0b622..633bc80 100644--- a/packages/gameplay/src/world.ts+++ b/packages/gameplay/src/world.ts@@ -24,7 +24,12 @@// runs `handlers` on its own, so neither may depend on the other having run.// - `world.emit(type, payload)` starts a state transaction (`handlers[type]`, as `tx.emit` does from a handler): on// this node when it is the authority, as it is wherever world handlers run today.-// - Synchronous, as handlers are: no await. `Math.random` and `Date` are the event's (`world.random`, `world.now`).+// - Synchronous, as handlers are: the handler itself returns no promise (an `async` function as a world handler is+// an error). `Math.random` and `Date` are the event's (`world.random`, `world.now`).+// - What it starts with promises (`load().then(...)`, an `async` function it calls and does not wait for) runs when+// the event's entry into the script is over, as in a browser (docs/RUNTIME.md "Promises"): the scene is still the+// scene and what that code changes reaches the engine, but the event is over. `world.emit` throws there, and+// `Math.random` and `Date` are the host's.// - A world handler that throws does not stop the world: what it had changed is synced, the event's handler and the// engine's next tick run all the same, and the error is in the event's log.// - Where they do not run: in a room. A node that follows a room gets committed state (`commit`, `setState`), not@@ -55,7 +60,8 @@ export interface WorldContext<S> {object(id: string): Object3D | undefined;/** Random stream of this event (seeded from the room seed and the event; `Math.random` in the handler is this). */random(): number;- /** Starts a state transaction: `handlers[type]` runs with `payload` after this handler and the event's own. */+ /** Starts a state transaction: `handlers[type]` runs with `payload` after this handler and the event's own.+ * Throws once the handler has returned (code after an `await`, a `world` kept for later): its emits were taken. */emit(type: string, payload?: unknown): void;/** What the player holds and moves (input.ts), as of the app's last input message. */readonly input: Input;@@ -69,9 +75,12 @@ export type WorldHandler<S> = (world: WorldContext<S>, ev: any) => void;const WORLD_STREAM = 0x40000000;/** The context of what runs on this node for `event` (a world handler, the listeners of a batch of host messages),- * with the state events it emits and its random stream. */-export function worldContext<S>(frames: FrameRunner<S>, seed: number, event: { id: number; ts: number }): { world: WorldContext<S>; emits: { type: string; payload: Json }[]; random: () => number } {+ * with the state events it emits and its random stream. `close()` when what it is for has run and its emits are+ * taken: an `emit` after that (from a promise's callback, which runs when the entry is over) would be lost, so it+ * throws. */+export function worldContext<S>(frames: FrameRunner<S>, seed: number, event: { id: number; ts: number }): { world: WorldContext<S>; emits: { type: string; payload: Json }[]; random: () => number; close: () => void } {const emits: { type: string; payload: Json }[] = [];+ let closed = false;const random = seededRandom(seed, (event.id + WORLD_STREAM) >>> 0);const world: WorldContext<S> = {scene: frames.scene,@@ -83,13 +92,14 @@ export function worldContext<S>(frames: FrameRunner<S>, seed: number, event: { irandom,emit(type, payload = {}) {if (typeof type !== "string" || !type) throw new TypeError("emit: event type must be a non-empty string");+ if (closed) throw new Error(`emit(${type}): the handler or listener this world was given to has returned (code after an await runs when its entry is over); emit while it runs, or from a host listener`);const text = JSON.stringify(payload) as string | undefined;if (text === undefined) throw new TypeError(`emit(${type}): the payload must be plain JSON`);emits.push({ type, payload: JSON.parse(text) as Json });},input: frames.input,};- return { world, emits, random };+ return { world, emits, random, close: () => void (closed = true) };}/**@@ -97,7 +107,7 @@ export function worldContext<S>(frames: FrameRunner<S>, seed: number, event: { i* emitted before is dropped with it, as a failed transaction's emits are).*/export function runWorldHandler<S>(handler: WorldHandler<S>, frames: FrameRunner<S>, seed: number, event: GameEvent): { emits: { type: string; payload: Json }[]; error?: string } {- const { world, emits, random } = worldContext(frames, seed, event);+ const { world, emits, random, close } = worldContext(frames, seed, event);try {withDeterminism(event.ts, random, () => {const r: unknown = handler(world, structuredClone(event.payload));@@ -108,5 +118,7 @@ export function runWorldHandler<S>(handler: WorldHandler<S>, frames: FrameRunnerreturn { emits };} catch (e) {return { emits: [], error: e instanceof Error ? (e.stack ?? e.message) : String(e) };+ } finally {+ close();}}diff --git a/packages/gameplay/test/host.test.ts b/packages/gameplay/test/host.test.tsindex a90864a..8b8e527 100644--- a/packages/gameplay/test/host.test.ts+++ b/packages/gameplay/test/host.test.ts@@ -180,6 +180,16 @@ test("input: mouse buttons are keys, the pointer, capture, a stick", () => {assert.deepEqual(i.move, { x: 0.3 / Math.hypot(0.3, 1), y: -1 / Math.hypot(0.3, 1) });i.apply({ t: "input", move: null });assert.deepEqual(i.move, { x: -1, y: 0 });+ // A message that leaves the stick out says the same as null: the stick of a message before is not kept. A frame+ // without a message keeps what the last one said.+ i.apply({ t: "input", move: [0, 1] });+ i.endFrame();+ assert.deepEqual(i.move, { x: 0, y: 1 }, "the stick, while no message says otherwise");+ i.apply({ t: "input", dx: 0.1 });+ assert.deepEqual(i.move, { x: -1, y: 0 }, "left out: no stick, the keys drive `move`");+ i.apply({ t: "input", move: [5, 0], keys: [] });+ i.apply({ t: "input", keys: ["W"] });+ assert.deepEqual(i.move, { x: 0, y: 1 });// Numbers that are not numbers are nothing.i.endFrame();i.apply({ t: "input", dx: Number.NaN, wheel: "x" as never, keys: [7 as never, "B"] });diff --git a/packages/gameplay/test/promises.test.ts b/packages/gameplay/test/promises.test.tsnew file mode 100644index 0000000..d16aaea--- /dev/null+++ b/packages/gameplay/test/promises.test.ts@@ -0,0 +1,184 @@+// Promises in game code (docs/RUNTIME.md "Promises"): a `.then` callback and the code after an `await` run when the+// entry that settled their promise is over (here Node's engine runs them, as a browser's does; in the renderer the+// script host runs them at the end of the entry, renderer/src/script.rs), and the node host's `sync` then has the+// engine follow what they changed. Handlers, world handlers, listeners and setup stay synchronous themselves.+import { test } from "node:test";+import assert from "node:assert/strict";+import { BoxGeometry, Mesh, MeshStandardMaterial, PerspectiveCamera, RecordingEngine, Scene } from "@threert/scene";+import { defineGame, host, type GameDefinition, type HostEvents, type WorldContext } from "../src/index.ts";+import * as gameplay from "../src/index.ts";++type AnyGame = GameDefinition<unknown>;+const installNodeHost = <S>(g: GameDefinition<S>, engine?: RecordingEngine) => gameplay.installNodeHost(g as AnyGame, engine);+const kinds = (calls: [string, ...unknown[]][]) => calls.map((c) => c[0]);+/** The entry is over: the engine runs the jobs it left, to the end of their chains. */+const jobs = () => new Promise<void>((r) => setImmediate(r));++function scene() {+ const scene = new Scene(), camera = new PerspectiveCamera(50, 16 / 9);+ const ground = new Mesh(new BoxGeometry(10, 0.1, 10), new MeshStandardMaterial({ name: "ground" }));+ ground.id = "ground";+ scene.add(camera, ground);+ return { scene, camera };+}++test("what promise jobs change in the scene after an entry reaches the engine with the node host's sync", async () => {+ const trace: string[] = [];+ const ground = (w: { object(id: string): unknown }) => w.object("ground") as Mesh;+ const g = defineGame({+ state: {},+ setup: scene,+ handlers: {},+ frame(f) {+ if (f.dt === 0) return;+ void Promise.resolve(0.5).then((p) => p / 2).then((p) => { ground(f).power = p; trace.push("frame then"); });+ },+ on: {+ click(world) {+ void (async () => {+ await null;+ ground(world).visible = await Promise.resolve(false);+ trace.push("click await");+ })();+ },+ },+ });+ const off = host.on("custom", (_m, world) => void Promise.resolve().then(() => { ground(world).power = 0.75; trace.push("listener then"); }));+ const engine = new RecordingEngine();+ const h = installNodeHost(g, engine);+ h.sync();+ assert.deepEqual(engine.take(), [], "before setup there is nothing to follow");+ h.setup("node");+ engine.take();+ for (const [enter, said, sent] of [+ [() => h.frame(1 / 60, 0), "frame then", "power"],+ [() => h.event("click", "{}", 0), "click await", "visible"],+ [() => h.hostMessages(JSON.stringify([{ t: "custom" }]), 0), "listener then", "power"],+ ] as const) {+ enter();+ assert.deepEqual([trace, engine.take()], [[], []], `${said}: nothing of it within the entry`);+ await jobs();+ assert.deepEqual(trace.splice(0), [said]);+ assert.deepEqual(engine.take(), [], "the scene has it, the engine not yet");+ h.sync();+ assert.deepEqual(kinds(engine.take()), [sent], said);+ h.sync();+ assert.deepEqual(engine.take(), [], "and once");+ }+ off();+});++test("a request as a promise the app's later message resolves: its awaiter goes on in that message's entry", async () => {+ const posts: { t: string; id: string; url: string }[] = [];+ const g0 = globalThis as { __host_post?: (text: string) => unknown };+ g0.__host_post = (text) => void posts.push(JSON.parse(text));+ // What a library makes of `net.fetch`: the answer comes in a host message, some frames later.+ const waiting = new Map<string, (m: HostEvents["net.fetched"]) => void>();+ const off = host.on("net.fetched", (m) => waiting.get(m.id)?.(m));+ const fetched = (url: string) => new Promise<HostEvents["net.fetched"]>((resolve) => {+ const id = `request ${waiting.size}`;+ waiting.set(id, resolve);+ host.post({ t: "net.fetch", id, url });+ });+ const trace: string[] = [];+ const g = defineGame({+ state: {},+ setup: scene,+ handlers: {},+ on: {+ load(world) {+ void (async () => {+ const m = await fetched("https://example.org/level");+ const box = new Mesh(new BoxGeometry(1, 1, 1), new MeshStandardMaterial({ name: m.body }));+ world.scene.add(box);+ trace.push(`loaded ${m.status} ${m.body}`);+ })();+ },+ },+ });+ try {+ const engine = new RecordingEngine();+ const h = installNodeHost(g, engine);+ h.setup("node");+ engine.take();+ h.event("load", "{}", 0);+ assert.deepEqual(posts, [{ t: "net.fetch", id: "request 0", url: "https://example.org/level" }]);+ // No timers: frames pass and nothing resumes it.+ for (let k = 0; k < 3; k++) {+ h.frame(1 / 60, 0);+ await jobs();+ }+ assert.deepEqual([trace, engine.take()], [[], []]);+ h.hostMessages(JSON.stringify([{ t: "net.fetched", id: "request 0", status: 200, body: "crate" }]), 0);+ await jobs();+ assert.deepEqual(trace, ["loaded 200 crate"]);+ h.sync();+ assert.deepEqual(kinds(engine.take()), ["geometry", "material", "object", "transform"]);+ } finally {+ off();+ delete g0.__host_post;+ }+});++test("the event is over when its handler returns: an emit from a promise's callback throws, and is not lost in silence", async () => {+ const errors: string[] = [];+ let kept: WorldContext<{ n: number }> | null = null;+ const g = defineGame<{ n: number }>({+ state: { n: 0 },+ setup: scene,+ handlers: { count(tx) { tx.state.n += 1; } },+ on: {+ click(world) {+ kept = world;+ world.emit("count");+ void Promise.resolve().then(() => world.emit("count")).catch((e: Error) => errors.push(e.message));+ },+ },+ });+ const off = host.on("custom", (_m, world: WorldContext<{ n: number }>) => {+ world.emit("count");+ void (async () => {+ await null;+ world.emit("count");+ })().catch((e: Error) => errors.push(e.message));+ });+ const h = installNodeHost(g, new RecordingEngine());+ h.setup("node");+ h.event("click", "{}", 0);+ h.hostMessages(JSON.stringify([{ t: "custom" }]), 0);+ await jobs();+ off();+ assert.equal(JSON.parse(h.state()).state.n, 2, "what each emitted while it ran");+ assert.equal(errors.length, 2);+ for (const e of errors) assert.match(e, /^emit\(count\): the handler or listener this world was given to has returned/);+ assert.throws(() => kept!.emit("count"), /has returned/, "a world kept for later");+ assert.equal(JSON.parse(h.state()).state.n, 2);+});++test("handlers, world handlers, listeners and setup return no promise: an async function as one is an error", () => {+ const g = defineGame<{ n: number }>({+ state: { n: 0 },+ setup: scene,+ handlers: { slow: (async () => {}) as never },+ on: { later: (async () => {}) as never },+ });+ const h = installNodeHost(g, new RecordingEngine());+ h.setup("node");+ assert.match(JSON.parse(h.event("slow", "{}", 0)).log[0], /✗ slow: error Error: handlers must be synchronous/);+ assert.match(JSON.parse(h.event("later", "{}", 0)).log[0], /✗ later \(world\): error Error: world handlers must be synchronous/);+ const off = host.on("custom", (async () => {}) as never);+ const said: string[] = [];+ const error = console.error;+ console.error = (...a: unknown[]) => void said.push(a.map(String).join(" "));+ try {+ h.hostMessages(JSON.stringify([{ t: "custom" }]), 0);+ } finally {+ console.error = error;+ off();+ }+ assert.match(said.join("\n"), /host message custom: Error: host listeners must be synchronous/);+ // Setup is not awaited: a scene is built when it returns.+ const later = defineGame({ state: {}, setup: (async () => scene()) as never, handlers: {} });+ assert.throws(() => installNodeHost(later, new RecordingEngine()).setup("node"), /setup must be synchronous: it returns \{ scene, camera \}, not a promise/);+ assert.throws(() => gameplay.buildScene(later as AnyGame, { roomId: "room" }), /setup must be synchronous/);+});diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex 103698a..8463e5b 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -8,10 +8,14 @@//! monotonic clock, the engine API and the host channel's queue (`__host_post`: messages for the app that embeds the//! session, which may answer with `host_messages`; docs/RUNTIME.md "The host channel"). Memory is capped and every//! call runs under a time budget (the interrupt handler aborts it).+//!+//! Promises: the engine has no event loop of its own, so every entry into the script (`ScriptHost::enter`) ends by+//! running the promise jobs it left (a `.then` callback, the code after an `await`), within the entry's budget, as a+//! browser does when a script returns. docs/RUNTIME.md "Promises".use crate::world::World;use anyhow::{anyhow, Result};-use rquickjs::{CatchResultExt, Context, Ctx, Exception, Function, Module, Object, Runtime, TypedArray, Value};+use rquickjs::{CatchResultExt, Coerced, Context, Ctx, Exception, Function, Module, Object, Persistent, Runtime, TypedArray, Value};use std::cell::RefCell;use std::rc::Rc;use std::sync::atomic::{AtomicU64, Ordering};@@ -142,8 +146,49 @@ impl Drop for Lent<'_> {}}+/// The promises rejected with no handler in the entry running now, each with its reason: one that gets a handler+/// before the entry's jobs have all run is taken off again, and what is left then is reported (`ScriptHost::enter`).+/// They are kept alive here, and none outlives its entry. Past `MAX_TRACKED` of them at once (a script that rejects+/// without end) the rest are only counted.+#[derive(Default)]+struct Rejections {+ list: Vec<(Persistent<Value<'static>>, Persistent<Value<'static>>)>,+ more: usize,+}+type Rejected = Rc<RefCell<Rejections>>;++/// The most unhandled rejections one entry reports by their reasons (the rest are counted), and the most it tracks.+const MAX_REJECTIONS: usize = 8;+const MAX_TRACKED: usize = 4096;++/// A game log line (`console.*`, an unhandled rejection): stderr, and the sink if there is one.+fn game_log(level: &str, msg: &str) {+ eprintln!("[game{}] {msg}", if level == "info" { String::new() } else { format!(" {level}") });+ if let Some(sink) = LOG_SINK.read().ok().and_then(|s| *s) {+ sink(level, msg);+ }+}++/// A rejection's reason as one line: what `String(reason)` says (an error's name and message), and where an error+/// was thrown (the first line of its stack).+fn reason_text<'js>(ctx: &Ctx<'js>, reason: &Value<'js>) -> String {+ let Ok(Coerced(text)) = reason.get::<Coerced<String>>() else {+ // (Its `toString` threw, or the entry's time was up.)+ ctx.catch();+ return "a value that cannot be shown".into();+ };+ let stack = reason.as_object().and_then(|o| o.get::<_, Option<String>>("stack").unwrap_or_else(|_| {+ ctx.catch();+ None+ }));+ match stack.as_deref().and_then(|s| s.lines().map(str::trim).find(|l| !l.is_empty() && *l != text)) {+ Some(at) => format!("{text} ({at})"),+ None => text,+ }+}+pub struct ScriptHost {- _rt: Runtime,+ rt: Runtime,ctx: Context,/// The deadline of the entry running now and the engine time lent to it (`Budget`).budget: Arc<Budget>,@@ -158,6 +203,15 @@ pub struct ScriptHost {pub physics: Rc<RefCell<Option<crate::physics::PhysicsWorld>>>,/// What the game posted for the app (`host.post`: JSON texts), until `take_posts`.posts: Rc<RefCell<Vec<String>>>,+ /// The promises rejected with no handler in the entry running now (`Rejected`); empty between entries.+ rejected: Rejected,+}++impl Drop for ScriptHost {+ fn drop(&mut self) {+ // (Values of the script engine must be gone before its runtime is.)+ self.rejected.borrow_mut().list.clear();+ }}pub struct EventOut {@@ -385,19 +439,29 @@ impl ScriptHost {let budget = Arc::new(Budget { epoch, deadline: AtomicU64::new(0), lent: AtomicU64::new(0) });let b = budget.clone();rt.set_interrupt_handler(Some(Box::new(move || b.up())));+ // A promise rejected with no handler is noted, and taken off again if it gets one (`then` / `catch` / `await`+ // on it later in the entry: `async` code that throws before its caller has the promise is such a case).+ let rejected = Rejected::default();+ let r = rejected.clone();+ rt.set_host_promise_rejection_tracker(Some(Box::new(move |ctx, promise, reason, handled| {+ let promise = Persistent::save(&ctx, promise);+ let mut r = r.borrow_mut();+ if handled {+ r.list.retain(|(p, _)| *p != promise);+ } else if r.list.len() < MAX_TRACKED {+ r.list.push((promise, Persistent::save(&ctx, reason)));+ } else {+ r.more += 1;+ }+ })));let ctx = Context::full(&rt)?;let world = Rc::new(RefCell::new(World::default()));let voxels = Rc::new(RefCell::new(crate::voxel::VoxelWorld::default()));- let mut h = ScriptHost { _rt: rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default(), posts: Default::default() };+ let mut h = ScriptHost { rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default(), posts: Default::default(), rejected };let (w, v, ph, d2, posts) = (h.world.clone(), h.voxels.clone(), h.physics.clone(), h.budget.clone(), h.posts.clone());- let info: String = h.call(SETUP_MS, |ctx| {+ let (info, rejections) = h.enter(SETUP_MS, |ctx| {let g = ctx.globals();- g.set("__host_log", Function::new(ctx.clone(), |level: String, msg: String| {- eprintln!("[game{}] {msg}", if level == "info" { String::new() } else { format!(" {level}") });- if let Some(sink) = LOG_SINK.read().ok().and_then(|s| *s) {- sink(&level, &msg);- }- })?)?;+ g.set("__host_log", Function::new(ctx.clone(), |level: String, msg: String| game_log(&level, &msg))?)?;g.set("__host_now", Function::new(ctx.clone(), move || epoch.elapsed().as_secs_f64() * 1000.0)?)?;// The host channel, script to app: a message's JSON text onto the queue the app drains. False when the// queue is full (nobody drains it); a message past the size bound is the script's error.@@ -415,19 +479,102 @@ impl ScriptHost {install_engine(ctx, &w, &v, &ph, &d2)?;ctx.eval::<(), _>(PRELUDE)?;code(ctx)?;- host(ctx)?.get::<_, Function>("describe")?.call(())- })?;+ host(ctx)?.get::<_, Function>("describe")?.call::<_, String>(())+ });+ // (A module that throws as it loads rejects its promise: the error returned says it, once.)+ let info = info?;+ for line in &rejections {+ game_log("error", line);+ }h.info = serde_json::from_str(&info)?;Ok(h)}- /// Runs `f` in the engine under a time budget; JS exceptions become errors with their message and stack.+ /// Runs `f` in the engine under a time budget, then the promise jobs it left (`enter`); JS exceptions become+ /// errors with their message and stack, and the entry's unhandled rejections are error lines of the game's log.fn call<T>(&self, budget_ms: u64, f: impl for<'js> FnOnce(&Ctx<'js>) -> rquickjs::Result<T>) -> Result<T> {+ let (r, rejections) = self.enter(budget_ms, f);+ for line in &rejections {+ game_log("error", line);+ }+ r+ }++ /// One entry into the script: `f` under a time budget, then the promise jobs the entry left (`run_jobs`), within+ /// the same budget, whether `f` threw or not. Returns `f`'s result (its own error first, else the jobs': the entry+ /// fails when its time is up with jobs still to run, as it does when `f` overruns) and the entry's unhandled+ /// rejections as lines for its log.+ fn enter<T>(&self, budget_ms: u64, f: impl for<'js> FnOnce(&Ctx<'js>) -> rquickjs::Result<T>) -> (Result<T>, Vec<String>) {self.budget.lent.store(0, Ordering::Relaxed);self.budget.deadline.store(self.epoch.elapsed().as_micros() as u64 + budget_ms * 1000, Ordering::Relaxed);let r = self.ctx.with(|ctx| f(&ctx).catch(&ctx).map_err(|e| anyhow!("{e}")));+ let jobs = self.run_jobs();+ let rejections = self.take_rejections();self.budget.deadline.store(0, Ordering::Relaxed);- r+ (r.and_then(|v| jobs.map(|()| v)), rejections)+ }++ /// Runs the pending promise jobs until none is left: the callbacks of promises the entry settled, the code after+ /// an `await`, and the jobs those queue in turn. The script engine has no event loop, so without this nothing+ /// after a promise ever ran. What they changed in the scene is sent to the engine by the node host's `sync`+ /// (the entry's own sync ran before them), so the commit that follows the entry applies it.+ ///+ /// The entry's deadline holds: a job that spins is interrupted like any script, and a chain that queues itself+ /// for ever is ended here when the time is up. The jobs not run stay queued, and run after the next entry.+ fn run_jobs(&self) -> Result<()> {+ loop {+ let mut ran = false;+ while self.rt.is_job_pending() {+ if self.budget.up() {+ return Err(anyhow!("interrupted (the script's time is up with promise jobs still to run)"));+ }+ // (A job fails only on what a script cannot catch, the interrupt: what a callback throws rejects its+ // promise.)+ if self.rt.execute_pending_job().is_err() {+ return Err(self.ctx.with(|ctx| match Err::<(), _>(rquickjs::Error::Exception).catch(&ctx) {+ Err(e) => anyhow!("{e}"),+ Ok(()) => anyhow!("a promise job failed"),+ }));+ }+ ran = true;+ }+ if !ran {+ return Ok(());+ }+ // (Bundles built before `sync` existed, the scripts of tests, and a bundle still loading have none.)+ self.ctx.with(|ctx| {+ let sync = || -> rquickjs::Result<()> {+ let Some(host) = ctx.globals().get::<_, Option<Object>>("__threert")? else { return Ok(()) };+ match host.get::<_, Option<Function>>("sync")? {+ Some(f) => f.call(()),+ None => Ok(()),+ }+ };+ sync().catch(&ctx).map_err(|e| anyhow!("{e}"))+ })?;+ }+ }++ /// The entry's unhandled rejections (promises rejected that no `then`, `catch` or `await` had taken up when the+ /// entry's jobs had run), each once, as error lines naming their reasons.+ fn take_rejections(&self) -> Vec<String> {+ let Rejections { list, more } = std::mem::take(&mut *self.rejected.borrow_mut());+ if list.is_empty() {+ return Vec::new();+ }+ self.ctx.with(|ctx| {+ let more = more + list.len().saturating_sub(MAX_REJECTIONS);+ let mut lines: Vec<String> = Vec::new();+ for (k, (_promise, reason)) in list.into_iter().enumerate() {+ if k < MAX_REJECTIONS {+ lines.push(format!("unhandled rejection: {}", reason.restore(&ctx).map_or_else(|_| "a value that cannot be shown".into(), |r| reason_text(&ctx, &r))));+ }+ }+ if more > 0 {+ lines.push(format!("unhandled rejection: {more} more in the same entry"));+ }+ lines+ })}fn call_host<T: for<'js> rquickjs::FromJs<'js>>(&self, budget_ms: u64, name: &str, args: impl for<'js> rquickjs::function::IntoArgs<'js>) -> Result<T> {@@ -494,9 +641,21 @@ impl ScriptHost {pub fn event(&self, kind: &str, payload: &serde_json::Value) -> Result<EventOut> {let t = Instant::now();let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_millis() as f64);- let json: String = self.call_host(EVENT_MS, "event", (kind, payload.to_string(), ts))?;+ let (json, rejections) = self.enter(EVENT_MS, |ctx| host(ctx)?.get::<_, Function>("event")?.call::<_, String>((kind, payload.to_string(), ts)));+ let json = match json {+ Ok(json) => json,+ Err(e) => {+ for line in &rejections {+ game_log("error", line);+ }+ return Err(e);+ }+ };let v: serde_json::Value = serde_json::from_str(&json)?;- Ok(EventOut { log: serde_json::from_value(v["log"].clone()).unwrap_or_default(), seq: v["seq"].as_i64().unwrap_or(-1), ms: t.elapsed().as_secs_f64() * 1000.0 })+ // (An event's unhandled rejections are lines of its log, as its handlers' errors are.)+ let mut log: Vec<String> = serde_json::from_value(v["log"].clone()).unwrap_or_default();+ log.extend(rejections.iter().map(|l| format!("✗ {l}")));+ Ok(EventOut { log, seq: v["seq"].as_i64().unwrap_or(-1), ms: t.elapsed().as_secs_f64() * 1000.0 })}/// State writes another authority (the room) committed.@@ -1105,6 +1264,175 @@ mod tests {assert!(old.take_posts().is_empty());}+ // The game above with what a game written with promises leaves behind in each entry: a `.then` chain and an+ // `async` function (`left`), and a request the app answers in a later message (`ask`: the host channel's+ // `net.fetch` as a library wraps it). `sync` is the node host's: the engine follows what the jobs changed.+ const PROMISES: &str = r#"+ const trace = [], waiting = new Map();+ let syncs = 0, dim = 1;+ const left = (name) => {+ Promise.resolve(1).then((v) => v + 1).then((v) => { trace.push(name + " then " + v); dim = dim / 2; });+ (async () => { await null; const v = await Promise.resolve(3); trace.push(name + " await " + v); })();+ };+ const ask = (id) => new Promise((resolve) => { waiting.set(id, resolve); __host_post(JSON.stringify({ t: "ask", id })); });+ Object.assign(globalThis.__threert, {+ event: (type, payload, ts) => {+ if (type === "ask") (async () => { const v = await ask("a"); trace.push("answered " + v); dim = 0.75; })();+ else if (type === "reject") Promise.resolve().then(() => { throw new TypeError("thrown in a job"); });+ else left(type);+ return JSON.stringify({ log: ["ok " + type], seq: 1 });+ },+ frame: (dt) => left("frame"),+ hostMessages: (list) => { for (const m of JSON.parse(list)) if (m.t === "answer") waiting.get(m.id)(m.value); else left(m.t); },+ sync: () => { syncs++; __engine.power(4, dim); },+ });+ globalThis.took = () => JSON.stringify([trace.splice(0), syncs]);+ "#;++ fn promises() -> ScriptHost {+ let h = ScriptHost::new(&format!("{GAME}{PROMISES}")).unwrap();+ h.setup("room", None).unwrap();+ h.world.borrow_mut().take_changes();+ h+ }++ /// What the script traced since the last look, and how often the node host's `sync` has run.+ fn took(h: &ScriptHost) -> (Vec<String>, u32) {+ serde_json::from_str(&h.call(100, |ctx| ctx.eval::<String, _>("took()")).unwrap()).unwrap()+ }++ /// The script engine has no event loop: each entry runs the promise jobs it left before it returns (a `.then`+ /// chain to its end, an `async` function past its awaits), then has the node host sync, so what the jobs changed+ /// in the scene is in the world the entry's commit applies. An entry that left none syncs nothing more.+ #[test]+ fn promise_jobs_run_in_the_entry_that_left_them() {+ let h = promises();+ let power = |h: &ScriptHost| {+ let mut w = h.world.borrow_mut();+ (w.objects[&4].power, w.take_changes().powers.contains(&4))+ };+ h.frame(1.0 / 60.0).unwrap();+ assert_eq!(took(&h), (vec!["frame then 2".to_string(), "frame await 3".into()], 1), "a frame script");+ assert_eq!(power(&h), (0.5, true), "what a job changed is synced after it");+ let e = h.event("click", &serde_json::json!({})).unwrap();+ assert_eq!(e.log, vec!["ok click"]);+ assert_eq!(took(&h), (vec!["click then 2".to_string(), "click await 3".into()], 2), "an event's handler");+ assert_eq!(power(&h), (0.25, true));+ h.host_messages(&[serde_json::json!({ "t": "note" }), serde_json::json!({ "t": "more" })]).unwrap();+ assert_eq!(took(&h), (["note then 2", "note await 3", "more then 2", "more await 3"].map(String::from).to_vec(), 3), "a batch's listeners: one sync for the batch");+ assert_eq!(power(&h), (0.0625, true));+ // Entries that leave no job: no second sync, nothing changed.+ h.commit(&serde_json::json!([]), 1).unwrap();+ h.set_state(&serde_json::json!({}), 1).unwrap();+ h.edit("sign", "node.visible", &serde_json::json!(true)).unwrap();+ assert_eq!(took(&h), (vec![], 3));+ assert_eq!(power(&h), (0.0625, false));+ // The loading of a bundle is an entry too (a module's top-level code, a library that starts with a promise).+ let h = ScriptHost::new(&format!("{GAME} globalThis.loaded = 0; Promise.resolve().then(() => {{ loaded = 1; }});")).unwrap();+ assert_eq!(h.call(100, |ctx| ctx.eval::<i32, _>("loaded")).unwrap(), 1);+ }++ /// No timers and no I/O: a promise only the app can resolve (its answer is a later host message) stays pending+ /// through the frames in between, and its awaiter runs in the entry of the message that resolves it.+ #[test]+ fn a_promise_a_later_host_message_resolves_resumes_its_awaiter_in_that_entry() {+ let h = promises();+ h.event("ask", &serde_json::json!({})).unwrap();+ assert_eq!(h.take_posts(), vec![serde_json::json!({ "t": "ask", "id": "a" })]);+ for _ in 0..3 {+ h.frame(1.0 / 60.0).unwrap();+ }+ let (trace, syncs) = took(&h);+ assert!(!trace.iter().any(|l| l.starts_with("answered")), "nothing resumes it between entries: {trace:?}");+ h.world.borrow_mut().take_changes();+ h.host_messages(&[serde_json::json!({ "t": "answer", "id": "a", "value": 7 })]).unwrap();+ assert_eq!(took(&h), (vec!["answered 7".to_string()], syncs + 1));+ assert_eq!(h.world.borrow().objects[&4].power, 0.75, "and what it changed is in the world when the entry returns");+ assert!(h.world.borrow_mut().take_changes().powers.contains(&4));+ }++ /// The jobs run within the entry's budget: a chain that queues itself for ever is ended when the time is up and+ /// the entry fails as one that spins does; so does a job that spins. The chain is still queued (the next entry+ /// runs into it) until the script stops it; then the host is as before.+ #[test]+ fn an_endless_chain_of_jobs_is_ended_by_the_budget() {+ let h = promises();+ let t = Instant::now();+ let err = h.call(FRAME_MS, |ctx| ctx.eval::<(), _>("globalThis.on = true; globalThis.turns = 0; const again = () => { turns++; if (on) Promise.resolve().then(again); }; again();")).unwrap_err();+ let ms = t.elapsed().as_millis();+ assert!(format!("{err}").contains("interrupted"), "{err}");+ assert!((FRAME_MS as u128..FRAME_MS as u128 + 500).contains(&ms), "ended after {ms} ms");+ let turns = |h: &ScriptHost| h.call(FRAME_MS, |ctx| ctx.eval::<f64, _>("turns"));+ assert!(format!("{}", turns(&h).unwrap_err()).contains("interrupted"), "the chain goes on after the next entry");+ h.call(FRAME_MS, |ctx| ctx.eval::<(), _>("on = false")).unwrap();+ let n = turns(&h).unwrap();+ assert!(n > 1000.0, "{n} turns");+ assert_eq!(turns(&h).unwrap(), n, "stopped");+ // A job that spins is interrupted where it is, and is gone: the next entry is as any other.+ for code in ["Promise.resolve().then(spin)", "(async () => { await null; spin(); })()"] {+ let t = Instant::now();+ let err = h.call(FRAME_MS, |ctx| ctx.eval::<(), _>(code)).unwrap_err();+ assert!(format!("{err}").contains("interrupted"), "{code}: {err}");+ assert!(t.elapsed().as_millis() < 1000, "{code}: ended after {} ms", t.elapsed().as_millis());+ h.frame(1.0 / 60.0).unwrap();+ }+ // An `async` function that never gets past its loop of awaits, left by a frame script.+ let h = ScriptHost::new(&format!("{GAME}{PROMISES}").replace("frame: (dt) => left(\"frame\"),", "frame: (dt) => { (async () => { for (;;) await null; })(); },")).unwrap();+ h.setup("room", None).unwrap();+ let t = Instant::now();+ let err = h.frame(1.0 / 60.0).unwrap_err();+ assert!(format!("{err}").contains("interrupted"), "{err}");+ assert!(t.elapsed().as_millis() < 1000, "ended after {} ms", t.elapsed().as_millis());+ }++ /// A promise rejected that nothing handles is one error line of the entry it was rejected in, naming its reason+ /// (an error thrown in a job is such a rejection). One that gets its handler before the entry's jobs have run is+ /// none, and no entry reports another's.+ #[test]+ fn an_unhandled_rejection_is_reported_once() {+ let h = promises();+ let lines = |code: &str| {+ let (r, lines) = h.enter(100, |ctx| ctx.eval::<(), _>(code));+ r.unwrap();+ lines+ };+ let one = |code: &str| {+ let l = lines(code);+ assert_eq!(l.len(), 1, "{code}: {l:?}");+ l.into_iter().next().unwrap()+ };+ assert!(one("Promise.reject(new Error('lost'))").starts_with("unhandled rejection: Error: lost"));+ assert!(one("Promise.resolve().then(() => { throw new TypeError('thrown in a job'); })").starts_with("unhandled rejection: TypeError: thrown in a job (at "));+ assert!(one("(async () => { await null; null.x; })()").contains("cannot read property"));+ assert_eq!(one("Promise.reject('only text')"), "unhandled rejection: only text");+ assert_eq!(one("Promise.reject({ toString() { throw 1; } })"), "unhandled rejection: a value that cannot be shown");+ assert_eq!(lines("1"), Vec::<String>::new(), "reported in its own entry only");+ // Handled: at once, by an await's try, by a job later in the same entry.+ for code in [+ "Promise.reject(new Error('caught')).catch(() => {})",+ "(async () => { try { await Promise.reject(new Error('caught')); } catch (e) {} })()",+ "const p = Promise.reject(new Error('caught')); Promise.resolve().then(() => p.catch(() => {}))",+ "const f = async () => { throw new Error('caught'); }; (async () => { try { await f(); } catch (e) {} })()",+ ] {+ assert_eq!(lines(&format!("{{ {code} }}")), Vec::<String>::new(), "{code}");+ }+ // Many in one entry: the first by their reasons, the rest counted.+ let many = lines("for (let i = 0; i < 20; i++) Promise.reject(new Error('n' + i))");+ assert_eq!(many.len(), MAX_REJECTIONS + 1);+ assert!(many[0].starts_with("unhandled rejection: Error: n0") && many[MAX_REJECTIONS] == "unhandled rejection: 12 more in the same entry", "{many:?}");+ // An event's are lines of its log, after its handlers' own.+ let e = h.event("reject", &serde_json::json!({})).unwrap();+ assert_eq!(e.log.len(), 2, "{:?}", e.log);+ assert!(e.log[0] == "ok reject" && e.log[1].starts_with("✗ unhandled rejection: TypeError: thrown in a job"), "{:?}", e.log);+ assert_eq!(h.event("click", &serde_json::json!({})).unwrap().log, vec!["ok click"]);+ // A module that throws while it loads is the load's error (and a module's top-level await is waited for).+ let runtime = "export const defineGame = (g) => g; export function installNodeHost(game) { globalThis.__threert = { describe: () => JSON.stringify({ handlers: [], frame: false, keys: {}, late: game.late }) }; }";+ let err = ScriptHost::from_modules("await null; throw new Error('no game'); export default {};", runtime).err().unwrap();+ assert!(format!("{err}").contains("no game"), "{err}");+ let h = ScriptHost::from_modules("const late = await Promise.resolve().then(() => 5); export default { late };", runtime).unwrap();+ assert_eq!(h.info["late"], 5);+ }+#[test]fn budgets_and_errors() {let h = ScriptHost::new(GAME).unwrap();diff --git a/tools/host-echo.ts b/tools/host-echo.tsindex f82e4e6..9514613 100644--- a/tools/host-echo.ts+++ b/tools/host-echo.ts@@ -5,6 +5,8 @@// (`{"host":[...]}`), and answered on its stdin (`{"cmd":"host","messages":[...]}`). Checked: the order of the// game's posts (net.open, net.send x 3, net.close; net.fetch), that a batch of messages reaches its listeners,// that what they emit is committed (the state's count is in the HUD), and that the HUD is posted as it changes.+// The game awaits its page as a promise the app's answer resolves: that its line is logged at all says the+// script host ran the code after the await (it has no event loop: renderer/src/script.rs `run_jobs`).// 2. `threert-render play` (a window, for about three seconds), which is an app itself: the same game against a// WebSocket and HTTP server on this machine, through the binary's own sockets. Checked: the server got the// game's three messages in order, the game got the three answers, the close and the page.