diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1303f028..a972939b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,15 @@ jobs: run: npm install working-directory: ${{ env.BUILD_PATH }} + # The site loads the Rust planner (rust/planner-wasm). build-wasm builds it for + # wasm32 and copies planner.js and planner_wasm.wasm into src/lib/planner-wasm, + # which the Vite build imports, so it has to run first. No toolchain action: + # rust/rust-toolchain.toml pins the compiler and the wasm32 target, and the + # runner's rustup installs both on first use, as in the Rust job. + - name: Build the Rust planner + run: npm run build-wasm + working-directory: ${{ env.BUILD_PATH }} + - name: Build run: npm run build working-directory: ${{ env.BUILD_PATH }} diff --git a/.github/workflows/deploy-cloudflare.yml b/.github/workflows/deploy-cloudflare.yml index 144074fc..699d7f3d 100644 --- a/.github/workflows/deploy-cloudflare.yml +++ b/.github/workflows/deploy-cloudflare.yml @@ -7,28 +7,19 @@ on: push: branches: - "main" - # Pull requests run this whole job except the deploy step itself, so the WASM - # publish and the public/framework copy are proven before merge rather than by - # the deploy that happens after it. ci.yml's front-end build does none of that - # work - it builds with public/framework absent, so it is green against a - # different artifact from the one that ships. + # Pull requests run this whole job except the deploy step itself, so the + # planner build and the bundle check are proven before merge rather than by the + # deploy that happens after it. # - # The paths list is the dependency chain that feeds the bundle: - # BrowserWasm -> Serialization + Contract -> FactorioTools, plus the Vue app - # that consumes it and the build inputs that change how any of them compile. - # Keep it in sync when a new project joins that chain; a missing entry costs - # coverage silently, which is the failure mode this job exists to remove. + # The paths list is what feeds the bundle: the Rust planner (rust/, built by + # build-wasm into src/vue/src/lib/planner-wasm) and the Vue app. Keep it in + # sync when something new joins that chain; a missing entry costs coverage + # silently, which is the failure mode this job exists to remove. pull_request: paths: - ".github/workflows/deploy-cloudflare.yml" - - "src/BrowserWasm/**" - - "src/FactorioTools/**" - - "src/FactorioTools.Serialization/**" - - "src/FactorioTools.Contract/**" + - "rust/**" - "src/vue/**" - - "submodules/**" - - "global.json" - - "Directory.Build.props" workflow_dispatch: permissions: @@ -47,52 +38,48 @@ jobs: with: submodules: recursive fetch-depth: 0 - - name: Set up .NET - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 - with: - global-json-file: global.json - # build-wasm below shells out to dotnet publish, which needs the workload. - - name: Restore wasm-tools workload - run: dotnet workload restore - name: Set up Node uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24 cache: "npm" cache-dependency-path: ${{ env.BUILD_PATH }}/package-lock.json - # Node is set up before the .NET publish because build-wasm runs through + # Node is set up before the planner build because build-wasm runs through # npm and needs shx from node_modules. - name: Install dependencies run: npm install working-directory: ${{ env.BUILD_PATH }} - # Publishes BrowserWasm and copies AppBundle/_framework to public/framework. - # This deliberately calls the npm script rather than reimplementing those - # steps inline: this workflow used to carry its own copy of the publish and - # cp logic, so the command developers run locally (per CLAUDE.md) and the - # one that builds the deployed site were two hand-maintained definitions - # that had already drifted in operation order. Now there is one, and this - # job is what proves it still works. - - name: Build the WASM bundle + # Builds the Rust planner (rust/planner-wasm) for wasm32 and copies planner.js + # and planner_wasm.wasm into src/lib/planner-wasm for Vite to bundle. No + # toolchain action: rust/rust-toolchain.toml pins the compiler and the wasm32 + # target, and the runner's rustup installs both on first use. This calls the + # npm script rather than reimplementing it inline, so the command developers + # run locally (per CLAUDE.md) and the one that builds the deployed site stay + # one definition, and this job is what proves it still works. + - name: Build the Rust planner run: npm run build-wasm working-directory: ${{ env.BUILD_PATH }} - name: Build run: npm run build working-directory: ${{ env.BUILD_PATH }} - # Guard against the bundle landing in the wrong shape - a flattened copy - # leaves dotnet.js at the dist root, the import 404s, and the site loads but - # cannot plan. Cheap to assert, and the assertion is the point of running - # this job on pull requests at all. - - name: Check the WASM bundle landed in the right shape + # Guard against shipping a site that cannot plan: the planner's .wasm and its + # worker must be in dist/assets with a content hash, and nothing may still + # point at the old .NET bundle under /framework/. + - name: Check the planner landed in the bundle run: | - for f in framework/dotnet.js framework/dotnet.boot.js framework/dotnet.native.wasm; do - if [ ! -f "$BUILD_PATH/dist/$f" ]; then - echo "::error::$BUILD_PATH/dist/$f is missing - the _framework copy did not land as dist/framework/." - echo "dist contents:" - ls -la "$BUILD_PATH/dist" + dist="$BUILD_PATH/dist" + for pattern in 'assets/planner_wasm-*.wasm' 'assets/plannerWorker-*.js'; do + if ! compgen -G "$dist/$pattern" > /dev/null; then + echo "::error::$dist/$pattern is missing - did build-wasm run before the Vite build?" + ls -la "$dist/assets" exit 1 fi done - echo "dist/framework/ contains the expected bundle entry points." + if [ -e "$dist/framework" ] || grep -rq "framework/dotnet" "$dist"; then + echo "::error::$dist still has or references the .NET bundle under /framework/." + exit 1 + fi + echo "dist/assets has the planner's .wasm and worker, and nothing references /framework/." - name: Deploy to Cloudflare Workers # Pull requests build and verify, but never deploy. This also keeps the # repository's only credential-bearing step off the PR path. diff --git a/.github/workflows/devcontainer.yml b/.github/workflows/devcontainer.yml index 79493b8e..1bddc423 100644 --- a/.github/workflows/devcontainer.yml +++ b/.github/workflows/devcontainer.yml @@ -83,6 +83,19 @@ jobs: echo "Transpile reproduced the committed output, and it parses and runs under 5.2." ' + # The site now loads the Rust planner (rust/planner-wasm), and the Vite build + # imports it from src/vue/src/lib/planner-wasm. The devcontainer image has no + # Rust toolchain yet (adding one belongs with stage 13 of #138, when .NET + # leaves the image), so build it on the runner, whose rustup honours + # rust/rust-toolchain.toml. The checkout is mounted into the container, so the + # copied files are visible there. This is what `npm run build-wasm` does, + # minus shx, which the runner does not have outside the container. + - name: Build the Rust planner on the runner + working-directory: rust + run: | + cargo build --release -p planner-wasm --target wasm32-unknown-unknown + cp target/wasm32-unknown-unknown/release/planner_wasm.wasm planner-wasm/js/planner.js ../src/vue/src/lib/planner-wasm/ + - name: The front-end builds and tests run: | npx --yes @devcontainers/cli@0.89.0 exec --workspace-folder "$GITHUB_WORKSPACE" bash -ec ' diff --git a/CLAUDE.md b/CLAUDE.md index 4afa64c4..51a6b372 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,26 +37,25 @@ npm install npm run dev # vite dev server npm run build # regenerates TS API client from swagger, type-checks, builds npm run swagger-gen # regenerate src/lib API client from ../WebApp/swagger.json -npm run build-wasm # publish BrowserWasm and copy the bundle (incl. dotnet.js) into public/framework +npm run build-wasm # build the Rust planner (rust/planner-wasm) and copy it into src/lib/planner-wasm ``` -- The Vue app plans in-browser via .NET WASM. After changing C# planner code, run - `npm run build-wasm` in `src/vue` to refresh `public/framework` (the bundle, - incl. `dotnet.js`, lives in `public/framework`). The copy must land as - `public/framework/`, not flattened into `public/` - a flattened bundle puts - `dotnet.js` at the root, the `framework/dotnet.js` import 404s, and the site - loads but cannot plan. `build-wasm` does `mkdir -p public` first to guarantee - that. (Only `src/vue/public/framework/` is gitignored, not all of - `src/vue/public/`; the directory itself exists in a fresh checkout because - `_headers` is tracked in it, so the `mkdir -p` is belt-and-braces rather - than load-bearing.) `deploy-cloudflare.yml` runs `build-wasm` and asserts the - resulting shape, on pull requests as well as on deploys, so this is now - checked rather than trusted. Requires the .NET 10 SDK plus the wasm-tools - workload; without a local .NET 10 SDK, publish via `./docker-build.sh` (the SDK image - also needs `python3` on PATH for the emscripten native relink step), passing - `--property:LocationAsStruct=false` the way `build-wasm` does, and copy - `src/BrowserWasm/bin/Release/net10.0/browser-wasm/AppBundle/_framework` into - `src/vue/public/framework`. `npm run dev` / `npm run build` serve those assets. +- The Vue app plans in-browser with the **Rust planner** (`rust/planner-wasm`), compiled to + WebAssembly. `npm run build-wasm` in `src/vue` builds it (`cargo build --release -p + planner-wasm --target wasm32-unknown-unknown`, run inside `rust/` so the pinned toolchain + applies) and copies `planner.js` and `planner_wasm.wasm` into `src/vue/src/lib/planner-wasm/`. + That folder is gitignored except for `planner.d.ts`, which types the wrapper, so run + `build-wasm` before `npm run dev` or `npm run build`: the Vite build imports those files and + fails without them. Vite gives the `.wasm` a content-hashed name under `/assets/`. Needs a + Rust toolchain (rustup); no .NET. +- **Planning runs in a Web Worker** (`src/lib/plannerWorker.ts`), started by + `src/lib/wasmPlanner.ts`, so the page stays responsive while it plans. If the worker cannot + start (it fails to construct, reports an error, or does not answer within 15 s), the planner + falls back for good to the main thread and logs one warning. Add `?planner=main-thread` to + the page URL to force the fallback. The .NET build could never run in a worker (its runtime + deadlocked in `create()`); the Rust module has no runtime, so it can. + `deploy-cloudflare.yml` runs `build-wasm` and checks the planner landed in `dist/assets`, on + pull requests as well as on deploys. ### Building without a local .NET 10 SDK (Docker / OrbStack) @@ -125,9 +124,9 @@ Blueprint string parsing and emitting live here, separate from the core lib: `Pa - `src/vue` - the primary front-end (Vue 3 + Vite + Pinia, persisted settings). This is what's deployed, as a Cloudflare Worker with static assets (see "Deployment" below); it plans in-browser via the WASM bundle and no longer calls a hosted API. Planner constants (pole presets, geometry defaults, strategy defaults, quality levels) are not retyped in TypeScript - they come from `src/vue/src/lib/plannerDefaults.verified.json`, which `PlannerDefaultsTest` generates from `OilFieldOptions` (most fields) and the `Quality` enum (`qualityLevels`). Change a default in the C# and `dotnet test` rewrites that file; commit it with your change. **Keep the FLUTE credit in the footer of `src/vue/src/App.vue`.** FLUTE (the `ConnectedCentersFlute` strategy, via the FluteSharp submodule) is under Chris Chu's Attribution Assurance License, `submodules/FluteSharp/flute-c/license.txt`. It requires a prominent display of "Dr. Chris C. N. Chu", "Iowa State University" and `http://home.engineering.iastate.edu/~cnchu/` every time the program launches. The footer shows on every page, which is what meets that. A Rust port of FLUTE would be under the same terms (#138). -- `src/BrowserWasm` - runs the planner fully client-side via .NET WASM (trimmed). Lets the SPA plan without the API. +- `src/BrowserWasm` - the planner as .NET WASM (trimmed). **The site no longer loads it**: it loads `rust/planner-wasm` instead (see the Rust port section). It stays until stage 13 of #138 removes the .NET projects, and the notes below describe how it was built. - **It ships as AOT with `Location` as a class, and the two flags only work together.** `BrowserWasm.csproj` sets `RunAOTCompilation=true`, and `build-wasm` passes `--property:LocationAsStruct=false`. That flag must stay on the command line: it is a global property that has to reach the referenced projects, and setting it in the `.csproj` does not. Measured 2026-10-06 in issue #139, against native .NET on the same machine: + **It shipped as AOT with `Location` as a class, and the two flags only work together.** `BrowserWasm.csproj` sets `RunAOTCompilation=true`, and `build-wasm` passes `--property:LocationAsStruct=false`. That flag must stay on the command line: it is a global property that has to reach the referenced projects, and setting it in the `.csproj` does not. Measured 2026-10-06 in issue #139, against native .NET on the same machine: | Build | Planning speed | Time to first plan | Download (brotli) | | --- | --- | --- | --- | @@ -147,7 +146,7 @@ The planner is being ported to Rust/WASM, one stage per PR, following the plan o - **Those copies are tested against fixtures recorded from real .NET** (`rust/dotnet-compat/fixtures`, format in `rust/dotnet-compat/FIXTURES.md`). The `test-default` CI job reruns the recorder on the pinned SDK and fails if the fixtures drift, so an SDK bump that changes .NET's behavior shows up as a red check. - **`rust/delaunator-net` and `rust/flute` are ports of the two submodules**, DelaunatorSharp and FluteSharp, kept byte-for-byte compatible with them. Do not swap in the `delaunator` crate: it is a newer algorithm whose tie-breaking differs, which changes the planner's pipes. `rust/flute` is under FLUTE's Attribution Assurance License (`rust/flute/LICENSE-FLUTE`), the same terms as the C#, so the site's footer credit covers it too. - **`rust/snapshots` is the end-to-end gate.** It plans every case the C# Verify tests plan, from the same `small-list.txt` and `big-list.txt`, and compares the output with the committed `*.verified.txt` files byte for byte, plus `Score.HasExpectedScore`. It also fails if a snapshot file exists that no Rust case checks. Run it in release: `cargo test --release -p snapshots -- --include-ignored` (about a minute). `rust/blueprint` parses blueprint strings for it. -- **`rust/contract` and `rust/planner-wasm` are what the site will load.** `contract` is the JSON the site sends and gets back (`PlanOrchestrator`'s `Plan` and `Normalize`, the error envelope), checked against responses recorded from the C# (`rust/contract/fixtures`). `planner-wasm` builds it to WebAssembly with no extra toolchain, and `planner-wasm/js/planner.js` exposes `plan(json)` and `normalize(json)` with the same signatures as `src/vue/src/lib/wasmPlanner.ts`. CI checks the WebAssembly build's output against the native contract byte for byte. The site still loads the .NET build; switching it over is a separate change. +- **`rust/contract` and `rust/planner-wasm` are what the site loads.** `contract` is the JSON the site sends and gets back (`PlanOrchestrator`'s `Plan` and `Normalize`, the error envelope), checked against responses recorded from the C# (`rust/contract/fixtures`). `planner-wasm` builds it to WebAssembly with no extra toolchain, and `planner-wasm/js/planner.js` exposes `plan(json)` and `normalize(json)` with the same signatures as `src/vue/src/lib/wasmPlanner.ts`. CI checks the WebAssembly build's output against the native contract byte for byte. **The site loads this module** (stage 12b of #138), through `src/vue/src/lib/wasmPlanner.ts` and a Web Worker. - **Commands**, from `rust/`: `cargo fmt --all`, `cargo clippy --all-targets -- -D warnings`, `cargo test --all-targets`, and `cargo build --workspace --target wasm32-unknown-unknown`. The toolchain is pinned in `rust/rust-toolchain.toml`; rustup installs it on first use. - **A change to the C# planner during the port** has to land in the Rust version too, or wait for it. `rust/planner/fixtures` are recorded from the C# planner (format and the command to regenerate them in `rust/planner/FIXTURES.md`), and the `test-default` CI job reruns every recorder under `rust/`. So a C# change that alters planner output turns CI red until the fixtures are regenerated and the Rust port matches them. @@ -158,7 +157,7 @@ The Vue app runs at `https://oilfieldplanner.factorygamefan.com` as a Cloudflare - **Config:** `src/vue/wrangler.jsonc`. It is an assets-only Worker: there is no Worker script, and every request is served straight from `dist/`. It attaches the hostname as a Custom Domain. `workers_dev` and `preview_urls` are off, so the site has one public hostname. - **CI deploys on every push to `main`.** `deploy-cloudflare.yml` runs `wrangler deploy` from `src/vue`, using the `wrangler` pinned in `package-lock.json`. Pull requests build and check the bundle but never deploy. So merging a PR that touches the site is a live deploy. - **Client routes use `"not_found_handling": "404-page"`.** A path with no file gets `dist/404.html` with status 404. That file is the SPA shell (`npm run build` copies `index.html` to it), so a hard load of a client route like `/oil-field` still starts the app. The 404 status is what Pages returned too. Do not swap this for `"single-page-application"` without meaning to: that serves `index.html` with status 200, which changes what crawlers see. -- **Headers come from `src/vue/public/_headers`**, which Vite copies to `dist/` and Cloudflare reads without serving. It gives `/assets/*` a one-year `immutable` cache, since Vite puts a content hash in those file names. `/framework/` stays on the default (`max-age=0, must-revalidate`, with an ETag): the .NET WASM bundle keeps fixed names like `dotnet.native.wasm` across builds, so a long cache would serve a stale planner after a deploy. HTML stays on the default too. +- **Headers come from `src/vue/public/_headers`**, which Vite copies to `dist/` and Cloudflare reads without serving. It gives `/assets/*` a one-year `immutable` cache, since Vite puts a content hash in those file names. That includes the planner's `planner_wasm-.wasm` and the worker script, so a deploy always gets new URLs. (The old .NET bundle lived under `/framework/` with fixed names and so stayed on the default cache; it is gone.) HTML stays on the default (`max-age=0, must-revalidate`, with an ETag). - **Two Pages default headers are restored in `_headers`.** Pages added `x-content-type-options: nosniff`, `referrer-policy: strict-origin-when-cross-origin` and `access-control-allow-origin: *` to every response, and a Worker adds none of them. The first two are back, in a `/*` block; `access-control-allow-origin: *` is left out on purpose: no other site is known to fetch these files. Add it back if one ever needs to. - **The old Pages host still redirects.** The Pages project `factoriotools` stays alive only to 301 `factoriotools-5jg.pages.dev` to the new hostname, keeping the path. Its whole deploy is `tools/pages-redirect-stub/_redirects`. CI never touches it. Never deploy it while `oilfieldplanner.factorygamefan.com` is still attached to the Pages project, or that hostname redirects to itself. To redeploy it, from `src/vue`: @@ -166,7 +165,7 @@ The Vue app runs at `https://oilfieldplanner.factorygamefan.com` as a Cloudflare npx wrangler pages deploy ../../tools/pages-redirect-stub --project-name factoriotools --branch main ``` -Test locally against a real build (run `npm run build-wasm` first, or `dist/framework/` is missing): +Test locally against a real build (run `npm run build-wasm` first, or the Vite build fails for want of `src/lib/planner-wasm/planner.js`): ```bash cd src/vue diff --git a/README.md b/README.md index 3f173824..415055a5 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Why did I build my own? Well, I didn't know of these tools before I started and ### Check it out -The tool is available here: https://oilfieldplanner.factorygamefan.com/oil-field. The planner runs entirely in your browser via .NET WebAssembly, so no blueprint data leaves your machine. There is an "Add sample" button (which drops one of my test blueprints in) and "View in FBE" buttons to view the input and output blueprints. Give it a try and let me know what you think! +The tool is available here: https://oilfieldplanner.factorygamefan.com/oil-field. The planner runs entirely in your browser via WebAssembly (a Rust port of the C# planner, in a background worker), so no blueprint data leaves your machine. There is an "Add sample" button (which drops one of my test blueprints in) and "View in FBE" buttons to view the input and output blueprints. Give it a try and let me know what you think! I've also attached a video of the thing in action. diff --git a/src/vue/package.json b/src/vue/package.json index 00abf933..6d9e6e99 100644 --- a/src/vue/package.json +++ b/src/vue/package.json @@ -11,7 +11,7 @@ "lint": "eslint . --fix", "format": "prettier --write src/", "swagger-gen": "swagger-typescript-api generate --path ../WebApp/swagger.json --output src/lib --name FactorioToolsApi", - "build-wasm": "dotnet publish ../BrowserWasm/BrowserWasm.csproj --configuration Release --property:LocationAsStruct=false && shx rm -rf public/framework && shx mkdir -p public && shx cp -r ../BrowserWasm/bin/Release/net10.0/browser-wasm/AppBundle/_framework public/framework", + "build-wasm": "cd ../../rust && cargo build --release -p planner-wasm --target wasm32-unknown-unknown && shx cp target/wasm32-unknown-unknown/release/planner_wasm.wasm planner-wasm/js/planner.js ../src/vue/src/lib/planner-wasm/", "test": "vitest run", "test:watch": "vitest" }, diff --git a/src/vue/public/_headers b/src/vue/public/_headers index 335f3a00..b0a12c6c 100644 --- a/src/vue/public/_headers +++ b/src/vue/public/_headers @@ -5,9 +5,9 @@ # contents in its name under /assets/ (index-SHUCZ6FL.js), so a changed file # always has a new URL and a cached copy can never go stale. # -# /framework/ is left on the default on purpose. The .NET WASM bundle keeps -# fixed names (dotnet.native.wasm, dotnet.js) from build to build, so a long -# cache there would keep serving an old planner after a deploy. +# That includes the planner: Vite fingerprints planner_wasm.wasm too +# (src/lib/planner-wasm), so it is served from /assets/ with the long cache and +# a deploy always gets a new URL. # # HTML also stays on the Workers default (max-age=0, must-revalidate), so a new # deploy shows up on the next page load. diff --git a/src/vue/src/lib/planner-wasm/.gitignore b/src/vue/src/lib/planner-wasm/.gitignore new file mode 100644 index 00000000..abf1959b --- /dev/null +++ b/src/vue/src/lib/planner-wasm/.gitignore @@ -0,0 +1,5 @@ +# `npm run build-wasm` copies the Rust planner here (rust/planner-wasm): planner.js and +# planner_wasm.wasm. Only this file and planner.d.ts are committed. +* +!.gitignore +!planner.d.ts diff --git a/src/vue/src/lib/planner-wasm/planner.d.ts b/src/vue/src/lib/planner-wasm/planner.d.ts new file mode 100644 index 00000000..afcc85e8 --- /dev/null +++ b/src/vue/src/lib/planner-wasm/planner.d.ts @@ -0,0 +1,17 @@ +// Types for planner.js, which `npm run build-wasm` copies here from +// rust/planner-wasm/js/planner.js along with planner_wasm.wasm. That wrapper is plain +// JavaScript; this file describes it so the TypeScript that imports it type-checks +// before the build has run. + +/** Sets where the WebAssembly module comes from. Optional; the default is the + * planner_wasm.wasm next to planner.js. Resolves once the module is loaded. */ +export function init( + moduleSource?: string | URL | Response | BufferSource | WebAssembly.Module, +): Promise + +/** Plans an oil field. Resolves to the response JSON, which may be an error envelope. + * Rejects with an Error where the C# contract would have thrown. */ +export function plan(requestJson: string): Promise + +/** Normalizes a blueprint. Resolves to the response JSON. */ +export function normalize(requestJson: string): Promise diff --git a/src/vue/src/lib/plannerWorker.ts b/src/vue/src/lib/plannerWorker.ts new file mode 100644 index 00000000..843a3526 --- /dev/null +++ b/src/vue/src/lib/plannerWorker.ts @@ -0,0 +1,49 @@ +// Runs the Rust planner (rust/planner-wasm) in a dedicated Web Worker, so planning does not +// freeze the page. wasmPlanner.ts starts this worker and talks to it with these messages. +// +// Requests: { id, op: "init" | "plan" | "normalize", request }. "init" loads the WebAssembly +// module and is how wasmPlanner.ts learns the worker works at all. +// Replies: { id, ok: true, response } or { id, ok: false, message } when the planner threw. + +import { init, normalize, plan } from "./planner-wasm/planner.js" + +export type PlannerOp = "init" | "plan" | "normalize" + +export interface PlannerRequest { + id: number + op: PlannerOp + request: string +} + +export type PlannerReply = + { id: number; ok: true; response: string } | { id: number; ok: false; message: string } + +// The DOM typings describe `self` as a Window, whose postMessage needs a target origin. In a +// dedicated worker it takes the message alone. +const scope = self as unknown as { + postMessage(message: PlannerReply): void + addEventListener(type: "message", listener: (event: MessageEvent) => void): void +} + +async function handle(op: PlannerOp, request: string): Promise { + switch (op) { + case "init": + await init() + return "" + case "plan": + return await plan(request) + case "normalize": + return await normalize(request) + } +} + +scope.addEventListener("message", async (event) => { + const { id, op, request } = event.data + let reply: PlannerReply + try { + reply = { id, ok: true, response: await handle(op, request) } + } catch (error) { + reply = { id, ok: false, message: error instanceof Error ? error.message : String(error) } + } + scope.postMessage(reply) +}) diff --git a/src/vue/src/lib/wasmPlanner.ts b/src/vue/src/lib/wasmPlanner.ts index 2bef7b02..4d83e49c 100644 --- a/src/vue/src/lib/wasmPlanner.ts +++ b/src/vue/src/lib/wasmPlanner.ts @@ -1,43 +1,146 @@ -// Boots the .NET WASM runtime once and exposes the Plan/Normalize exports. -// The bundle is published into public/framework by `npm run build-wasm` and -// served at the site root, so dotnet.js lives at `framework/dotnet.js` and -// resolves its sibling assets relative to itself. +// The oil-field planner: the Rust port (rust/planner-wasm) compiled to WebAssembly. +// `npm run build-wasm` builds it and copies planner.js and planner_wasm.wasm into +// ./planner-wasm/, where Vite gives the .wasm a content-hashed name under /assets/. // -// The runtime is booted and invoked on the main thread on purpose: the -// single-threaded .NET WASM runtime deadlocks during `create()` when booted in -// a dedicated Web Worker (it is designed to initialize on the browser's main -// thread). Running it in a worker would require the multithreaded build plus -// SharedArrayBuffer and COOP/COEP cross-origin-isolation headers. - -type Exports = { - Interop: { - Plan: (requestJson: string) => string - Normalize: (requestJson: string) => string +// Planning runs in a Web Worker (plannerWorker.ts), so the page stays responsive while a +// big field is planned. If the worker cannot start - it fails to construct, reports an +// error, or does not answer the first request within WORKER_START_TIMEOUT_MS - this module +// falls back for good to running the same planner on the main thread, which is how the +// .NET build always ran. (The .NET runtime deadlocked when booted in a worker; the Rust +// module has no runtime and does not.) Add `?planner=main-thread` to the page URL to force +// the fallback, for testing. +// +// plan() and normalize() resolve to the response JSON, which may be an error envelope, and +// reject when the planner threw - the same contract the .NET build had. + +import type { PlannerOp, PlannerReply, PlannerRequest } from "./plannerWorker" + +const WORKER_START_TIMEOUT_MS = 15_000 + +type Pending = { resolve: (response: string) => void; reject: (error: Error) => void } + +let worker: Worker | null = null +let workerReady: Promise | null = null +let useMainThread = false +let nextId = 1 +const pending = new Map() + +/** The worker went away while a request was waiting; the request reruns on the main thread. */ +class WorkerLostError extends Error { + constructor() { + super("The planner worker stopped.") + } +} + +function forcedMainThread(): boolean { + try { + return new URLSearchParams(globalThis.location?.search ?? "").get("planner") === "main-thread" + } catch { + return false + } +} + +function fallBack(reason: string) { + if (!useMainThread) { + console.warn(`Planner worker unavailable (${reason}); planning on the main thread.`) + } + useMainThread = true + worker?.terminate() + worker = null + // Anything still waiting on the worker reruns on the main thread. + const waiting = [...pending.values()] + pending.clear() + for (const p of waiting) { + p.reject(new WorkerLostError()) + } +} + +function send(op: PlannerOp, request: string): Promise { + return new Promise((resolve, reject) => { + if (!worker) { + reject(new WorkerLostError()) + return + } + const id = nextId++ + pending.set(id, { resolve, reject }) + worker.postMessage({ id, op, request } satisfies PlannerRequest) + }) +} + +function startWorker(): Promise { + if (workerReady) { + return workerReady } + workerReady = (async () => { + if (forcedMainThread()) { + fallBack("forced by ?planner=main-thread") + return false + } + try { + worker = new Worker(new URL("./plannerWorker.ts", import.meta.url), { type: "module" }) + } catch (error) { + fallBack(`could not construct it: ${String(error)}`) + return false + } + worker.addEventListener("message", (event: MessageEvent) => { + const reply = event.data + const p = pending.get(reply.id) + if (!p) { + return + } + pending.delete(reply.id) + if (reply.ok) { + p.resolve(reply.response) + } else { + p.reject(new Error(reply.message)) + } + }) + worker.addEventListener("error", (event) => fallBack(`error: ${event.message || "unknown"}`)) + worker.addEventListener("messageerror", () => fallBack("a message could not be read")) + + let timer: ReturnType | undefined + const timeout = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`no answer within ${WORKER_START_TIMEOUT_MS} ms`)), + WORKER_START_TIMEOUT_MS, + ) + }) + try { + await Promise.race([send("init", ""), timeout]) + return true + } catch (error) { + fallBack(`it did not start: ${error instanceof Error ? error.message : String(error)}`) + return false + } finally { + clearTimeout(timer) + } + })() + return workerReady } -let exportsPromise: Promise | null = null +async function onMainThread(op: "plan" | "normalize", request: string): Promise { + const planner = await import("./planner-wasm/planner.js") + return op === "plan" ? planner.plan(request) : planner.normalize(request) +} -function bootExports(): Promise { - if (!exportsPromise) { - exportsPromise = (async () => { - // Resolve dotnet.js relative to the deployed base (root '/'). - const dotnetUrl = `${__BASE_PATH__}framework/dotnet.js` - const { dotnet } = await import(/* @vite-ignore */ dotnetUrl) - const { getAssemblyExports, getConfig } = await dotnet.withDiagnosticTracing(false).create() - const config = getConfig() - return (await getAssemblyExports(config.mainAssemblyName)) as Exports - })() +async function run(op: "plan" | "normalize", request: string): Promise { + if (!useMainThread && (await startWorker())) { + try { + return await send(op, request) + } catch (error) { + // A planner error is the caller's to handle. Only a lost worker reruns here. + if (!(error instanceof WorkerLostError)) { + throw error + } + } } - return exportsPromise + return onMainThread(op, request) } -export async function plan(requestJson: string): Promise { - const exports = await bootExports() - return exports.Interop.Plan(requestJson) +export function plan(requestJson: string): Promise { + return run("plan", requestJson) } -export async function normalize(requestJson: string): Promise { - const exports = await bootExports() - return exports.Interop.Normalize(requestJson) +export function normalize(requestJson: string): Promise { + return run("normalize", requestJson) } diff --git a/src/vue/vite.config.ts b/src/vue/vite.config.ts index 93eccb8d..f8f88104 100644 --- a/src/vue/vite.config.ts +++ b/src/vue/vite.config.ts @@ -72,6 +72,9 @@ export default defineConfig({ }, }, plugins: [vue()], + // The planner runs in a module Web Worker (src/lib/plannerWorker.ts) that imports the + // Rust planner's ES module wrapper, so build the worker as an ES module too. + worker: { format: 'es' }, define: define, base: basePath })