host-acceptance.cjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Windows 原生运行时验收。传入包含 helper、fixture、adapter.cjs 的构建目录。
  2. // Wine 可用 Node 20 执行;仅补 Promise.withResolvers,不把它记为 Node 24 / Windows 实机证据。
  3. Promise.withResolvers ??= function () {
  4. let resolve, reject;
  5. const promise = new Promise((a, b) => {
  6. resolve = a;
  7. reject = b;
  8. });
  9. return { promise, resolve, reject };
  10. };
  11. const assert = require("node:assert/strict");
  12. const { setTimeout: delay } = require("node:timers/promises");
  13. const { join, resolve } = require("node:path");
  14. const { spawn } = require("node:child_process");
  15. const { once } = require("node:events");
  16. const net = require("node:net");
  17. const connections = [];
  18. const createServer = net.createServer;
  19. net.createServer = (...args) => {
  20. const server = createServer(...args);
  21. server.on("connection", (connection) => connections.push(connection));
  22. return server;
  23. };
  24. const adapterLogs = [];
  25. // 复用真实 service logger 的输出;子 Host 的 stdout 只保留原来的 PID 控制结果。
  26. for (const level of ["log", "warn", "error"]) {
  27. const original = console[level].bind(console);
  28. console[level] = (...args) => {
  29. if (typeof args[0] === "string" && args[0].includes("[windows-runtime-host]")) {
  30. adapterLogs.push({ message: args[1], fields: args[2] });
  31. return;
  32. }
  33. original(...args);
  34. };
  35. }
  36. const nativeMarker = "[windows-runtime-host:exit] ";
  37. const buildDir = resolve(process.argv[2]);
  38. const { spawnWindowsRuntimeHost } = require(join(buildDir, "adapter.cjs"));
  39. process.env.ZCODE_RUNTIME_HOST_PATH = join(buildDir, "zcode-runtime-host.exe");
  40. const fixture = join(buildDir, "zcode-runtime-host-acceptance.exe");
  41. async function create(mode) {
  42. const abort = new AbortController();
  43. const runtime = await spawnWindowsRuntimeHost({
  44. command: fixture,
  45. args: ["fixture", mode],
  46. cwd: buildDir,
  47. env: process.env,
  48. signal: abort.signal,
  49. });
  50. await runtime.ready();
  51. let output = "";
  52. let stderr = "";
  53. runtime.child.stdout.on("data", (s) => (output += s));
  54. runtime.child.stderr.on("data", (s) => {
  55. stderr += s;
  56. process.stderr.write(s);
  57. });
  58. let root;
  59. runtime.onRootExit((code) => (root = code));
  60. const connection = connections.at(-1);
  61. const closed = Promise.all([
  62. once(runtime.child, "close"),
  63. new Promise((resolveClosed) => connection.once("close", resolveClosed)),
  64. ]);
  65. return {
  66. runtime,
  67. abort,
  68. connection,
  69. closed,
  70. output: () => output,
  71. stderr: () => stderr,
  72. root: () => root,
  73. };
  74. }
  75. function diagnostics(x, reason) {
  76. const spawned = adapterLogs.find(
  77. (entry) =>
  78. entry.message === "Windows runtime host spawned" &&
  79. entry.fields.helperPid === x.runtime.child.pid,
  80. );
  81. assert.ok(spawned);
  82. assert.match(spawned.fields.runId, /^[0-9a-f-]{36}$/);
  83. assert.equal(spawned.fields.hostPid, process.pid);
  84. const events = adapterLogs.filter((entry) => entry.fields.runId === spawned.fields.runId);
  85. assert.equal(
  86. events.filter((entry) => entry.message === "Windows runtime host helper exit").length,
  87. 1,
  88. );
  89. const exit = events.find((entry) => entry.message === "Windows runtime host helper exit").fields;
  90. assert.equal(exit.helperPid, x.runtime.child.pid);
  91. assert.equal(exit.runtimePid, x.runtime.runtimePid);
  92. assert.equal(exit.code, x.runtime.child.exitCode);
  93. assert.equal(exit.signal, x.runtime.child.signalCode);
  94. const closed = events.find(
  95. (entry) => entry.message === "Windows runtime host control close",
  96. ).fields;
  97. assert.equal(typeof closed.hadError, "boolean");
  98. assert.equal(typeof closed.rootSeen, "boolean");
  99. assert.equal(typeof closed.empty, "boolean");
  100. assert.equal(typeof closed.closeSent, "boolean");
  101. assert.ok(["none", "ready", "started", "root", "empty"].includes(closed.lastFrame));
  102. assert.ok(
  103. [
  104. "none",
  105. "invalid_frame",
  106. "invalid_event",
  107. "start_cancelled",
  108. "helper_error",
  109. "cleanup_complete",
  110. ].includes(closed.destroyReason),
  111. );
  112. for (const entry of events) {
  113. assert.ok(
  114. Object.keys(entry.fields).every((key) =>
  115. [
  116. "runId",
  117. "hostPid",
  118. "helperPid",
  119. "runtimePid",
  120. "code",
  121. "signal",
  122. "errorCode",
  123. "errorName",
  124. "hadError",
  125. "rootSeen",
  126. "empty",
  127. "lastFrame",
  128. "closeSent",
  129. "destroyReason",
  130. ].includes(key),
  131. ),
  132. );
  133. }
  134. const summaries = x
  135. .stderr()
  136. .split(/\r?\n/)
  137. .filter((line) => line.startsWith(nativeMarker));
  138. if (reason === undefined) {
  139. assert.equal(summaries.length, 0, "externally killed helper need not emit a summary");
  140. } else {
  141. assert.equal(summaries.length, 1);
  142. const summary = JSON.parse(summaries[0].slice(nativeMarker.length));
  143. assert.deepEqual(
  144. Object.keys(summary).sort(),
  145. [
  146. "hostPid",
  147. "helperPid",
  148. "runtimePid",
  149. "reason",
  150. "stage",
  151. "win32Error",
  152. "running",
  153. "rootExited",
  154. "forced",
  155. "jobEmpty",
  156. ].sort(),
  157. );
  158. assert.equal(summary.reason, reason);
  159. assert.equal(summary.hostPid, process.pid);
  160. assert.equal(summary.helperPid, x.runtime.child.pid);
  161. assert.equal(summary.runtimePid, x.runtime.runtimePid);
  162. assert.equal(summary.jobEmpty, true);
  163. assert.equal(summary.rootExited, true);
  164. if (reason === "root_exited" || reason === "close_grace_elapsed") {
  165. assert.equal(closed.empty, true);
  166. assert.equal(closed.lastFrame, "empty");
  167. assert.equal(summary.stage, "none");
  168. assert.equal(summary.win32Error, 0);
  169. }
  170. }
  171. return events;
  172. }
  173. (async () => {
  174. if (process.argv[3] === "crash-host") {
  175. const owned = await create("tree");
  176. await owned.runtime.start();
  177. while (!/descendant ([0-9]+)/.test(owned.output())) await delay(10);
  178. console.log(
  179. JSON.stringify([
  180. owned.runtime.runtimePid,
  181. owned.runtime.child.pid,
  182. Number(/descendant ([0-9]+)/.exec(owned.output())[1]),
  183. ]),
  184. );
  185. return;
  186. }
  187. for (const mode of ["graceful", "tree", "root-exit"]) {
  188. const x = await create(mode);
  189. assert.equal(x.output(), "");
  190. assert.notEqual(x.runtime.runtimePid, x.runtime.child.pid);
  191. await x.runtime.start();
  192. await delay(100);
  193. const begin = Date.now();
  194. await Promise.all([x.runtime.close(Date.now() + 3250), x.runtime.close(Date.now() + 3250)]);
  195. if (mode === "graceful") {
  196. assert.equal(x.root(), 0);
  197. assert.ok(Date.now() - begin >= 1400);
  198. }
  199. await x.closed;
  200. diagnostics(x, mode === "tree" ? "close_grace_elapsed" : "root_exited");
  201. console.log("PASS adapter", mode, Date.now() - begin);
  202. }
  203. const lost = await create("tree");
  204. await lost.runtime.start();
  205. await delay(100);
  206. lost.connection.destroy();
  207. await lost.runtime.close(Date.now() + 2000);
  208. await lost.closed;
  209. diagnostics(lost, "control_lost");
  210. console.log("PASS control loss retains safe diagnostics and kernel cleanup");
  211. const socketError = await create("tree");
  212. await socketError.runtime.start();
  213. await delay(100);
  214. // 注入 Error 的正文不得进入生产诊断,只记录原有 error/close 回调的安全事实。
  215. socketError.connection.destroy(
  216. Object.assign(new Error("PRIVATE socket body"), { code: "ECONNRESET" }),
  217. );
  218. await socketError.runtime.close(Date.now() + 2000);
  219. await socketError.closed;
  220. const errorEvents = diagnostics(socketError, "control_lost");
  221. const errorFields = errorEvents.find(
  222. (entry) => entry.message === "Windows runtime host control error",
  223. ).fields;
  224. assert.equal(errorFields.errorCode, "ECONNRESET");
  225. assert.equal(errorFields.errorName, "Error");
  226. assert.equal(
  227. errorEvents.find((entry) => entry.message === "Windows runtime host control close").fields
  228. .hadError,
  229. true,
  230. );
  231. assert.ok(!JSON.stringify(errorEvents).includes("PRIVATE"));
  232. console.log("PASS socket error logs code/name without body");
  233. const late = await create("tree");
  234. await late.runtime.start();
  235. await assert.rejects(late.runtime.close(Date.now() + 50), /timed out/);
  236. await delay(2100);
  237. await late.runtime.close(Date.now() + 1000);
  238. console.log("PASS deadline retains Job; later close succeeds");
  239. const crashed = await create("tree");
  240. await crashed.runtime.start();
  241. await delay(150);
  242. crashed.runtime.child.kill();
  243. await delay(150);
  244. await crashed.runtime.close(Date.now() + 1500);
  245. await crashed.closed;
  246. diagnostics(crashed);
  247. console.log("PASS helper crash kernel Job probe recovery");
  248. const cancelled = await create("tree");
  249. cancelled.abort.abort();
  250. await assert.rejects(cancelled.runtime.start());
  251. await cancelled.runtime.close(Date.now() + 1500);
  252. assert.equal(cancelled.output(), "");
  253. console.log("PASS cancelled startup never executes CLI");
  254. const early = await spawnWindowsRuntimeHost({
  255. command: fixture,
  256. args: ["fixture", "tree"],
  257. cwd: buildDir,
  258. env: process.env,
  259. signal: new AbortController().signal,
  260. });
  261. await early.close(Date.now() + 2000);
  262. await assert.rejects(early.start());
  263. console.log("PASS close during startup retains and cleans owner");
  264. const invalid = await spawnWindowsRuntimeHost({
  265. command: join(buildDir, "missing-cli.exe"),
  266. args: [],
  267. cwd: buildDir,
  268. env: process.env,
  269. signal: new AbortController().signal,
  270. });
  271. invalid.child.stderr.resume();
  272. await assert.rejects(invalid.ready());
  273. await invalid.close(Date.now() + 2000);
  274. console.log("PASS failed CLI creation releases verified empty Job");
  275. const host = spawn(process.execPath, [__filename, buildDir, "crash-host"], {
  276. stdio: ["ignore", "pipe", "inherit"],
  277. env: process.env,
  278. });
  279. let hostOutput = "";
  280. host.stdout.on("data", (s) => (hostOutput += s));
  281. while (!hostOutput.includes("\n")) await delay(10);
  282. const pids = JSON.parse(hostOutput.trim());
  283. const observer = spawn(fixture, ["watch", ...pids.map(String)], {
  284. stdio: ["ignore", "pipe", "inherit"],
  285. });
  286. const observerExit = once(observer, "exit");
  287. let observerOutput = "";
  288. observer.stdout.on("data", (s) => (observerOutput += s));
  289. while (!observerOutput.includes("watching")) await delay(10);
  290. host.kill();
  291. assert.equal((await observerExit)[0], 0);
  292. console.log("PASS Host death terminates helper, CLI and descendant handles");
  293. })().catch((e) => {
  294. console.error(e);
  295. process.exitCode = 1;
  296. });