Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

smoke-wsl-native-runtime.mjs

164 lines6.5 KB

1#!/usr/bin/env node
2​
3import { createHash } from "node:crypto";
4import { spawnSync } from "node:child_process";
5import { copyFileSync, mkdirSync, readFileSync } from "node:fs";
6import { createRequire } from "node:module";
7import path from "node:path";
8import { fileURLToPath } from "node:url";
9​
10function parseArgs(argv) {
11 const options = {};
12 for (let index = 0; index < argv.length; index += 2) {
13 const arg = argv[index];
14 const value = argv[index + 1];
15 if (!value) throw new Error(`Missing value for ${arg}`);
16 if (arg === "--server-root") options.serverRoot = value;
17 else if (arg === "--node-pty") options.nodePty = value;
18 else if (arg === "--node-runtime") options.nodeRuntime = value;
19 else if (arg === "--manifest") options.manifest = value;
20 else if (arg === "--arch") options.arch = value;
21 else throw new Error(`Unknown argument: ${arg}`);
22 }
23 for (const key of ["serverRoot", "nodePty", "nodeRuntime", "manifest", "arch"]) {
24 if (!options[key]) throw new Error(`Missing required option: ${key}`);
25 }
26 return options;
28​
29function sha256File(filePath) {
30 return createHash("sha256").update(readFileSync(filePath)).digest("hex");
32​
33function resolveNativeRuntime(serverRoot, arch) {
34 const serverRequire = createRequire(path.join(path.resolve(serverRoot), "package.json"));
35 const ptyManifest = serverRequire.resolve("node-pty/package.json");
36 const ptyDir = path.dirname(ptyManifest);
37 const fffNodeEntry = serverRequire.resolve("@ff-labs/fff-node");
38 const fffRequire = createRequire(fffNodeEntry);
39 const fffPath = fffRequire.resolve(`@ff-labs/fff-bin-linux-${arch}-gnu`);
40 const ffiEntry = fffRequire.resolve("ffi-rs");
41 const ffiRequire = createRequire(ffiEntry);
42 const ffiPath = ffiRequire.resolve(`@yuuang/ffi-rs-linux-${arch}-gnu`);
43 return { serverRequire, ptyDir, fffPath, ffiPath };
45​
46function verifyManifestHashes(manifest, paths) {
47 const byName = new Map(manifest.artifacts.map((artifact) => [artifact.name, artifact]));
48 for (const [name, filePath] of Object.entries(paths)) {
49 const expected = byName.get(name);
50 if (!expected) throw new Error(`ABI manifest is missing artifact ${name}.`);
51 const actual = sha256File(filePath);
52 if (actual !== expected.sha256) {
53 throw new Error(`${name} hash differs from the ABI-audited artifact: expected ${expected.sha256}, got ${actual}.`);
54 }
55 }
57​
58async function smokeNodePty(serverRequire, ptyDir, prebuildPath, arch) {
59 const destination = path.join(ptyDir, "prebuilds", `linux-${arch}`, "pty.node");
60 mkdirSync(path.dirname(destination), { recursive: true });
61 copyFileSync(path.resolve(prebuildPath), destination);
62 const nodePty = serverRequire("node-pty");
63 await new Promise((resolve, reject) => {
64 let output = "";
65 const terminal = nodePty.spawn("/bin/sh", ["-lc", "printf T3CODE_WSL_PTY_OK"], {
66 name: "xterm-color",
67 cols: 80,
68 rows: 24,
69 cwd: process.cwd(),
70 env: process.env,
71 });
72 const timeout = setTimeout(() => {
73 try {
74 terminal.kill();
75 } catch {}
76 reject(new Error("node-pty WSL smoke test timed out."));
77 }, 5000);
78 terminal.onData((chunk) => {
79 output += chunk;
80 });
81 terminal.onExit(({ exitCode }) => {
82 clearTimeout(timeout);
83 if (exitCode !== 0 || !output.includes("T3CODE_WSL_PTY_OK")) {
84 reject(new Error(`node-pty smoke failed (exit ${exitCode}): ${JSON.stringify(output)}`));
85 } else {
86 resolve();
87 }
88 });
89 });
91​
92function smokeFffDynamicDependencies(fffPath) {
93 const dynamic = spawnSync("readelf", ["-d", fffPath], {
94 encoding: "utf8",
95 timeout: 5000,
96 });
97 if (dynamic.error || dynamic.status !== 0) {
98 throw new Error(
99 `Could not inspect audited fff Linux binary: ${dynamic.error?.message ?? dynamic.stderr ?? `readelf exited ${dynamic.status}`}`,
100 );
101 }
102 // A fully-static ELF has no DT_NEEDED entries and `ldd` intentionally exits
103 // non-zero for it, so static binaries pass this loader smoke without ldd.
104 if (!/Shared library: \[[^\]]+\]/.test(dynamic.stdout ?? "")) return;
105​
106 const result = spawnSync("ldd", [fffPath], {
107 encoding: "utf8",
108 timeout: 5000,
109 });
110 const combined = `${result.stdout ?? ""}\n${result.stderr ?? ""}`;
111 if (result.error) throw new Error(`Could not inspect audited fff Linux binary: ${result.error.message}`);
112 if (result.status !== 0 || /\bnot found\b/i.test(combined)) {
113 throw new Error(`fff failed dynamic-loader compatibility smoke:\n${combined}`);
114 }
116​
117function smokeFfiNative(ffiPath) {
118 createRequire(import.meta.url)(ffiPath);
120​
121export async function runSmoke(options) {
122 const manifest = JSON.parse(readFileSync(path.resolve(options.manifest), "utf8"));
123 if (manifest?.schemaVersion !== 2) throw new Error("Unsupported WSL ABI manifest schema.");
124 if (manifest?.baseline?.arch !== options.arch) {
125 throw new Error(`ABI manifest architecture ${manifest?.baseline?.arch ?? "unknown"} does not match ${options.arch}.`);
126 }
127​
128 const bundledNode = path.resolve(options.nodeRuntime);
129 const runtimeVersion = spawnSync(bundledNode, ["-p", "process.versions.node"], { encoding: "utf8", timeout: 5000 });
130 if (runtimeVersion.error || runtimeVersion.status !== 0) {
131 throw new Error(`Bundled Node runtime could not execute: ${runtimeVersion.error?.message ?? runtimeVersion.stderr ?? `exit ${runtimeVersion.status}`}`);
132 }
133 const actualNodeVersion = (runtimeVersion.stdout ?? "").trim();
134 if (actualNodeVersion !== manifest?.nodeRuntime?.version) {
135 throw new Error(`Bundled Node runtime version mismatch: manifest ${manifest?.nodeRuntime?.version ?? "unknown"}, binary ${actualNodeVersion || "unknown"}.`);
136 }
137​
138 const runtime = resolveNativeRuntime(options.serverRoot, options.arch);
139 verifyManifestHashes(manifest, {
140 "node-runtime": bundledNode,
141 "node-pty": path.resolve(options.nodePty),
142 fff: runtime.fffPath,
143 "ffi-rs": runtime.ffiPath,
144 });
145​
146 await smokeNodePty(runtime.serverRequire, runtime.ptyDir, options.nodePty, options.arch);
147 smokeFffDynamicDependencies(runtime.fffPath);
148 smokeFfiNative(runtime.ffiPath);
149​
150 console.log(
151 `[wsl-runtime-smoke] PASS ${manifest.baseline.id}/${options.arch}: bundled Node ${manifest.nodeRuntime.version}, node-pty PTY spawn, fff dependency resolution, ffi-rs native require`,
152 );
154​
155async function main() {
156 await runSmoke(parseArgs(process.argv.slice(2)));
158​
159if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
160 main().catch((error) => {
161 console.error(error?.stack ?? error);
162 process.exitCode = 1;
163 });