pcbjam/scripts/deploy/wasm-cache-hash.mjs

163 lines
6.9 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
// Computes the "sc" (source-content) hash for the KiCad-WASM output cache key
jspi: retire the asyncify pipeline — knob, post-link tail, binaryen hooks Phase 8 in the parent repo. Deleted: asyncify-scheduler.js, apply-asyncify.sh, apply-finalize.sh, inject-dyncall-shims.sh, asyncify-imports/removelist.txt, the wasm-opt/finalize stub pair, scripts/binaryen-hoist-pass/ (the fork stays a dormant submodule; removal is a follow-up), bench/wasm-opt-bench.sh (README marked historical), wasm/shims/context_sleep.cpp, and the sched-context harness app + Makefile targets. PCBJAM_ASYNC_BACKEND is gone: build-wx-wasm.sh hardcodes the jspi stamp (still force-cleans pre-migration trees), build-kicad-target.sh gives editors the JSPI link surface and the CLIs nothing (they pin ASYNCIFY=0), the stub dance is replaced by an unconditional .real-restore, build-wasm-test.sh lost its whole post-link loop, docker/build.sh's postprocess is the ENV shim only, and Makefile.wasm links every app JSPI with the scheduler shim as a tracked prerequisite. pcbjam_async_policy.h keys on __EMSCRIPTEN__. jspi-scheduler.js: wxWasmMainLoopPump dropped from the wrap census (the export died with the D5 detach); inert [TRACE] instrumentation removed. CI: wasm-build.yml rewritten for the single-cache pipeline (one output cache keyed on compile inputs; post-processed bytes cached after the shim); opt_level input removed from both callers. wasm-cache-hash.mjs inputs now cover patch-env-shim.mjs + jspi-scheduler.js + jspi-exports.txt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NDeBaKKhQztd8KiVtHuyXr
2026-08-13 08:39:12 +02:00
// in .github/workflows/wasm-build.yml.
//
// The cache key is:
jspi: retire the asyncify pipeline — knob, post-link tail, binaryen hooks Phase 8 in the parent repo. Deleted: asyncify-scheduler.js, apply-asyncify.sh, apply-finalize.sh, inject-dyncall-shims.sh, asyncify-imports/removelist.txt, the wasm-opt/finalize stub pair, scripts/binaryen-hoist-pass/ (the fork stays a dormant submodule; removal is a follow-up), bench/wasm-opt-bench.sh (README marked historical), wasm/shims/context_sleep.cpp, and the sched-context harness app + Makefile targets. PCBJAM_ASYNC_BACKEND is gone: build-wx-wasm.sh hardcodes the jspi stamp (still force-cleans pre-migration trees), build-kicad-target.sh gives editors the JSPI link surface and the CLIs nothing (they pin ASYNCIFY=0), the stub dance is replaced by an unconditional .real-restore, build-wasm-test.sh lost its whole post-link loop, docker/build.sh's postprocess is the ENV shim only, and Makefile.wasm links every app JSPI with the scheduler shim as a tracked prerequisite. pcbjam_async_policy.h keys on __EMSCRIPTEN__. jspi-scheduler.js: wxWasmMainLoopPump dropped from the wrap census (the export died with the D5 detach); inert [TRACE] instrumentation removed. CI: wasm-build.yml rewritten for the single-cache pipeline (one output cache keyed on compile inputs; post-processed bytes cached after the shim); opt_level input removed from both callers. wasm-cache-hash.mjs inputs now cover patch-env-shim.mjs + jspi-scheduler.js + jspi-exports.txt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NDeBaKKhQztd8KiVtHuyXr
2026-08-13 08:39:12 +02:00
// kwasm-<os>-k<kicad-sha>-wx<wx-sha>-sc<HASH>-3d<flag>-e<epoch>
//
// The kicad/wx submodule SHAs already capture the *sources*. This hash captures
// the *build logic* that shapes the wasm bytes but lives outside those
jspi: retire the asyncify pipeline — knob, post-link tail, binaryen hooks Phase 8 in the parent repo. Deleted: asyncify-scheduler.js, apply-asyncify.sh, apply-finalize.sh, inject-dyncall-shims.sh, asyncify-imports/removelist.txt, the wasm-opt/finalize stub pair, scripts/binaryen-hoist-pass/ (the fork stays a dormant submodule; removal is a follow-up), bench/wasm-opt-bench.sh (README marked historical), wasm/shims/context_sleep.cpp, and the sched-context harness app + Makefile targets. PCBJAM_ASYNC_BACKEND is gone: build-wx-wasm.sh hardcodes the jspi stamp (still force-cleans pre-migration trees), build-kicad-target.sh gives editors the JSPI link surface and the CLIs nothing (they pin ASYNCIFY=0), the stub dance is replaced by an unconditional .real-restore, build-wasm-test.sh lost its whole post-link loop, docker/build.sh's postprocess is the ENV shim only, and Makefile.wasm links every app JSPI with the scheduler shim as a tracked prerequisite. pcbjam_async_policy.h keys on __EMSCRIPTEN__. jspi-scheduler.js: wxWasmMainLoopPump dropped from the wrap census (the export died with the D5 detach); inert [TRACE] instrumentation removed. CI: wasm-build.yml rewritten for the single-cache pipeline (one output cache keyed on compile inputs; post-processed bytes cached after the shim); opt_level input removed from both callers. wasm-cache-hash.mjs inputs now cover patch-env-shim.mjs + jspi-scheduler.js + jspi-exports.txt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NDeBaKKhQztd8KiVtHuyXr
2026-08-13 08:39:12 +02:00
// submodules — the host ENV-shim patch, the per-tool
// compile scripts, the dependency builds, and the Docker toolchain. Those were
// deliberately dropped from the key's hashFiles() (so routine script edits don't
// trigger a 1-2h rebuild); folding the *output-determining* subset back in here
// keeps the cache correct while leaving the rest under the manual .ci-cache-epoch
// / [no-cache] controls.
//
// The hash is content-based and order-independent: it builds a manifest of
// `<sha256(content)> <repo-relative-path>` lines, sorts them, and hashes the
// manifest. Identical on macOS (dev) and Linux (CI) given a normal LF checkout,
// so you can predict cache hits locally.
//
// This script hashes ITSELF (and therefore the INPUTS list below) too, so
// editing it busts the cache — intended: a change here means the set of
// cache-invalidating inputs changed.
//
// Usage:
// node scripts/deploy/wasm-cache-hash.mjs # full hex sha256 -> stdout
// node scripts/deploy/wasm-cache-hash.mjs --short # 16-char prefix
// node scripts/deploy/wasm-cache-hash.mjs --short=12 # N-char prefix
// node scripts/deploy/wasm-cache-hash.mjs --manifest # per-file lines + total (stderr), hash on stdout
//
// In CI (the `keys` step, after checkout + setup-node):
// echo "sc=$(node scripts/deploy/wasm-cache-hash.mjs)" >> "$GITHUB_OUTPUT"
//
// MAINTENANCE: to add or remove inputs, edit INPUTS below — that is the only
// place the set is defined.
import { createHash } from "node:crypto";
import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { join, relative, sep } from "node:path";
// --- The inputs that determine the cached wasm bytes -------------------------
// Each entry is one of:
// { file: "<repo-relative path>" } a single file (must exist)
// { dir: "<repo-relative dir>" } every file under the dir, recursive
// { dir: "<repo-relative dir>", match: RE } files under the dir whose BASENAME matches RE, recursive
// Paths are POSIX, relative to the repo root. This script always adds itself.
const INPUTS = [
jspi: retire the asyncify pipeline — knob, post-link tail, binaryen hooks Phase 8 in the parent repo. Deleted: asyncify-scheduler.js, apply-asyncify.sh, apply-finalize.sh, inject-dyncall-shims.sh, asyncify-imports/removelist.txt, the wasm-opt/finalize stub pair, scripts/binaryen-hoist-pass/ (the fork stays a dormant submodule; removal is a follow-up), bench/wasm-opt-bench.sh (README marked historical), wasm/shims/context_sleep.cpp, and the sched-context harness app + Makefile targets. PCBJAM_ASYNC_BACKEND is gone: build-wx-wasm.sh hardcodes the jspi stamp (still force-cleans pre-migration trees), build-kicad-target.sh gives editors the JSPI link surface and the CLIs nothing (they pin ASYNCIFY=0), the stub dance is replaced by an unconditional .real-restore, build-wasm-test.sh lost its whole post-link loop, docker/build.sh's postprocess is the ENV shim only, and Makefile.wasm links every app JSPI with the scheduler shim as a tracked prerequisite. pcbjam_async_policy.h keys on __EMSCRIPTEN__. jspi-scheduler.js: wxWasmMainLoopPump dropped from the wrap census (the export died with the D5 detach); inert [TRACE] instrumentation removed. CI: wasm-build.yml rewritten for the single-cache pipeline (one output cache keyed on compile inputs; post-processed bytes cached after the shim); opt_level input removed from both callers. wasm-cache-hash.mjs inputs now cover patch-env-shim.mjs + jspi-scheduler.js + jspi-exports.txt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NDeBaKKhQztd8KiVtHuyXr
2026-08-13 08:39:12 +02:00
// Host-side post-processing — shapes the shipped glue.
{ file: "scripts/common/patch-env-shim.mjs" },
// Link-time inputs baked into every editor app: the scheduler pre-js and
// the promising-export census.
{ file: "scripts/common/shims/jspi-scheduler.js" },
{ file: "scripts/common/jspi-exports.txt" },
jspi cleanup: remove the asyncify-era residue — dead code, conditionals, pipeline scaffolding, stale prose The runtime is JSPI-only; this removes everything that still pretended otherwise. Three exhaustive sweeps (C++/JS+build+CI/tests+docs) drove the inventory; every deletion verified by grep closure + full gates. Broken-right-now fixes: - deploy-staging.yml passed the retired opt_level input — the workflow could not even start. Removed. - env.sh carried dead exports with a live -sASYNCIFY=1 inside (WASM_LDFLAGS/PTHREAD_LDFLAGS, zero consumers). Removed; the WASM_LEGACY_EXCEPTIONS rationale rewritten to the real reason. - docker/build.sh exported PCBJAM_ASYNC_BACKEND (read nowhere). Gone. Dead weight removed: - binaryen submodule (nothing builds or invokes it), wasm-opt-bench workflow + scripts/bench/, get-wasm-opt.sh, diagnostics.js (242 lines of Asyncify-API-only code), the KICAD_PIPELINE background-postprocess scaffolding (existed to parallelize the deleted wasm-opt phase; the postprocess is a seconds-long node script and now runs inline), build-monitor's dead asyncify rows, sched-context orphan build output, dead .gitignore entries, the .jspi-assets spike dir (the two wf-result research JSONs moved to docs/features/async/migration-evidence/). - bindings: fiber_park.h + its 12 embind registrations (broken-if- called under JSPI), the kicadOpenFileStart/OPEN_JOB starter route, main_stack_runner.h + 5 includes, the always-null context-sleep weak hook in nanosleep_yield.c. - shim: the backend field (installed-flag idempotency instead), noteContextWait (dead both sides), the __wxAsyncifyDump alias (+ the WasmTool fallback and string-dump normalize branch). - web: the emscripten-6-ignored mainScriptUrlOrBlob option in boot.ts (gerber-demo keeps it: it loads the deployed CDN release, which predates emscripten 6 — noted inline). Conditionals: all 'backend === jspi' checks reduced to scheduler- presence checks; races_quiescent re-keyed from Asyncify.state (vacuous) to real backlog quiescence (resumeReady/mutatorQueue — NOT _windowLive, which is the probing activation's own window by definition). Renames (identifiers only, no file renames): ASYNC_LINK_FLAGS→ JSPI_LINK_FLAGS and Makefile ASYNC_LDFLAGS→JSPI_LDFLAGS, kicadCollabFiberBusy→kicadCollabBusy (embind + web + tests), collab_common.h fiber*→apply*/coroutine naming, asyncifySignatures→ wasmTrapSignatures (lists byte-identical). Tests: the two remaining vacuous [wx-asyncify]/fiber-resume-refused asserts re-keyed to live JSPI beacons; eeschema-load's failure message no longer sends the developer to a deleted script; wait-beacons' dead families/parser deleted; lane-0 legacy-glue guards removed (lane 0 is unconstructible); the embind test.fail re-gated with the JSPI reason (plain embind invokers cannot suspend — verified still failing); lint-determinism now scans tests/jspi (166 files clean); eeschema-collab local-move gated to chromium (~50% flaky on FF even solo; pcbnew twin covers both engines). Docs: DEBUG.md rewritten as the JSPI debugging guide; build.md describes the single-phase build; docs/features/async/README.md banner-marked historical and repointed at the NEW 23-jspi-runtime.md (current architecture: export census, turnstile, libcontext ownership + refusal contract, embind call shapes, the em-pthread service-wrapper trick, exception policy, known gaps). Gates on the cleaned tree: test:e2e 725 passed / 0 failed (after the quiescence-probe fix; the 3 other reds were verified contention flakes solo-green or the documented FF gate), web 76/0, jspi 18/18 both engines, vitest 295/295 + 17/17, all lints green, live-app census clean. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016X9eh1s5sTx1o9Em9KBuwR
2026-08-14 09:25:32 +02:00
// Single-sources DEPS_EH_FLAGS (the exception-model link flags).
{ file: "scripts/common/env.sh" },
// Per-tool compile recipes (compile flags / emcc link options).
{ dir: "scripts/kicad", match: /^build-.*\.sh$/ },
// The pcbjam-repo C++/CMake/shim sources compiled INTO the tools (bindings,
// cli mains, kiplatform, gl1, stubs, editor glue). These live outside the
// kicad/wx submodules, so without this entry a pure wasm/** edit (e.g. a
// new kicad_tools subcommand) would cache-hit stale output — plugins 0002
// shipped exactly that way before this entry existed.
{ dir: "wasm" },
// Dependency builds (boost/cairo/occ/... — the sysroot the wasm links against).
{ dir: "scripts/deps" },
// Docker toolchain (base image, emsdk, build driver).
{ file: "docker/Dockerfile" },
{ file: "docker/build.sh" },
jspi: migration phases 0-7 — build knob, scheduler shim, test successor suite Toolchain: emsdk 6.0.6 (versions.sh; cache-hash keys on it). Build knob PCBJAM_ASYNC_BACKEND=jspi|asyncify: build-kicad-target.sh links editors with -sJSPI + -sJSPI_EXPORTS=@scripts/common/jspi-exports.txt + --pre-js jspi-scheduler.js (no DYNCALLS, no post-link asyncify pipeline); wx build stamps the backend and forces clean on flip or unknown provenance; docker/build.sh passes the knob, seeds the emscripten ports cache from the volume every launch, jspi postprocess = patch-env-shim only. scripts/common/shims/jspi-scheduler.js: the JSPI successor scheduler — token-wait registry, resume turnstile (one armed resume between engine re-entries, SP swaps only at microtask boundaries), green-region spill stacks (16-aligned tops), S1 embind mutator FIFO lane + parker wraps, S6 shutdown, libctx integration hooks (suspend/end/quarantine + g_current arm/clear), SuspendError attributor, lost-wake + stuck-window watchdogs, __wxWaitDump observability. Embind: PARKER registrations get emscripten::async() under PCBJAM_JSPI (wasm/bindings/pcbjam_async_policy.h). nanosleep yields route via the shim. Tests: tests/asyncify -> tests/jspi successor suite (jspi-stack red/green shadow-stack battery, jspi-coroutine MiniCoro harness, suspend-races semantic scenarios + __wxWaitDump books coherence); projects jspi-firefox/ jspi-chrome (asyncify-webkit retired — no JSPI in WebKit); unconditional Firefox JSPI pref; guard-beacons -> wait-beacons (+wxScheduler/libctxJspi families); Makefile.wasm links test apps against JSPI with the shim as a tracked link prerequisite. Web: WasmTool setRo await + __wxWaitDump forensics, open-flow contained promise, scheduler-shim.test.ts retargeted (8 green). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NDeBaKKhQztd8KiVtHuyXr
2026-08-13 07:06:24 +02:00
// Toolchain pins — EMSCRIPTEN_VERSION reaches the Dockerfile only as a build
// ARG, so without this entry an emsdk bump alone would cache-hit wasm built
// by the previous toolchain.
{ file: "scripts/common/versions.sh" },
];
// --- helpers -----------------------------------------------------------------
const ROOT = fileURLToPath(new URL("../..", import.meta.url)); // scripts/deploy -> repo root
const toPosix = (p) => p.split(sep).join("/");
const sha256hex = (buf) => createHash("sha256").update(buf).digest("hex");
// Recursively collect repo-relative file paths under an absolute dir. Skips
// dotfiles/dot-dirs (no hidden files are intended inputs) and follows the
// optional basename matcher.
function walk(absDir, match) {
const out = [];
for (const ent of readdirSync(absDir, { withFileTypes: true })) {
if (ent.name.startsWith(".")) continue;
const abs = join(absDir, ent.name);
if (ent.isDirectory()) {
out.push(...walk(abs, match));
} else if (ent.isFile()) {
if (match && !match.test(ent.name)) continue;
out.push(toPosix(relative(ROOT, abs)));
}
}
return out;
}
// --- resolve the file set ----------------------------------------------------
const files = new Set();
for (const entry of INPUTS) {
if (entry.file) {
const abs = join(ROOT, entry.file);
if (!existsSync(abs) || !statSync(abs).isFile()) {
// Hard error: a listed file vanished (renamed/moved). Silently dropping it
// would weaken the key and serve a stale cache.
console.error(`wasm-cache-hash: required input missing: ${entry.file}`);
process.exit(1);
}
files.add(toPosix(entry.file));
} else if (entry.dir) {
const abs = join(ROOT, entry.dir);
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
console.error(`wasm-cache-hash: required input dir missing: ${entry.dir}`);
process.exit(1);
}
const found = walk(abs, entry.match);
if (found.length === 0) {
// Non-fatal: a dir/matcher that yields nothing is suspicious but
// deterministic. Warn so a bad matcher doesn't go unnoticed.
console.error(
`wasm-cache-hash: warning: no files for ${entry.dir}` +
(entry.match ? ` matching ${entry.match}` : "")
);
}
for (const f of found) files.add(f);
}
}
// Always include this script (and thus the INPUTS list).
files.add(toPosix(relative(ROOT, fileURLToPath(import.meta.url))));
// --- build the manifest and hash it ------------------------------------------
const manifest = [...files]
.sort()
.map((rel) => `${sha256hex(readFileSync(join(ROOT, rel)))} ${rel}`)
.join("\n");
const hash = sha256hex(Buffer.from(manifest, "utf8"));
// --- output ------------------------------------------------------------------
const args = process.argv.slice(2);
if (args.includes("--help") || args.includes("-h")) {
console.error(readFileSync(fileURLToPath(import.meta.url), "utf8").split("\n\n")[1]);
process.exit(0);
}
if (args.includes("--manifest")) {
// Manifest to stderr so stdout stays a clean, capturable hash.
console.error(manifest);
console.error(`-- ${files.size} files --`);
}
const shortArg = args.find((a) => a === "--short" || a.startsWith("--short="));
const out = shortArg
? hash.slice(0, Number(shortArg.split("=")[1]) || 16)
: hash;
process.stdout.write(out + "\n");