runtimeUpdateIntegration.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import { spawn } from "node:child_process";
  2. import { mkdir, mkdtemp, readFile, symlink, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { describe, expect, it } from "vitest";
  7. import { requestControl } from "../src/ipc/controlClient.js";
  8. import { resolveCanonicalServerLayout, resolveServerLayout } from "../src/runtime/paths.js";
  9. import { ReleaseManager } from "../src/runtime/releaseManager.js";
  10. async function waitForReady(
  11. controlEndpoint: string,
  12. ): Promise<{ serviceRegistered?: boolean; state?: string }> {
  13. const deadline = Date.now() + 15_000;
  14. while (Date.now() < deadline) {
  15. try {
  16. const status = (await requestControl(controlEndpoint, { command: "status" }, 200)) as {
  17. state?: string;
  18. };
  19. if (status.state === "ready") return status;
  20. } catch {
  21. // Supervisor/Core 仍在真实启动,继续轮询 control endpoint。
  22. }
  23. await new Promise<void>((resolve) => setTimeout(resolve, 25));
  24. }
  25. throw new Error("Timed out waiting for integration Supervisor ready");
  26. }
  27. async function waitForCondition(predicate: () => boolean): Promise<void> {
  28. const deadline = Date.now() + 15_000;
  29. while (Date.now() < deadline) {
  30. if (predicate()) return;
  31. await new Promise<void>((resolve) => setTimeout(resolve, 25));
  32. }
  33. throw new Error("Timed out waiting for integration CLI ready output");
  34. }
  35. async function listChildPids(parentPid: number): Promise<number[]> {
  36. const { execFile } = await import("node:child_process");
  37. return await new Promise<number[]>((resolve) => {
  38. execFile("pgrep", ["-P", String(parentPid)], (error, stdout) => {
  39. if (error) {
  40. resolve([]);
  41. return;
  42. }
  43. resolve(String(stdout).split(/\s+/u).filter(Boolean).map(Number));
  44. });
  45. });
  46. }
  47. async function waitForHttpClosed(port: number): Promise<boolean> {
  48. const deadline = Date.now() + 5_000;
  49. while (Date.now() < deadline) {
  50. try {
  51. const response = await fetch(`http://127.0.0.1:${port}/api/server-info`, {
  52. signal: AbortSignal.timeout(250),
  53. });
  54. await response.arrayBuffer();
  55. } catch {
  56. return true;
  57. }
  58. await new Promise<void>((resolve) => setTimeout(resolve, 50));
  59. }
  60. return false;
  61. }
  62. describe.skipIf(process.platform === "win32")("runtime update integration", () => {
  63. it("收口 Supervisor IPC 断连后的 Core,避免遗留孤儿监听进程", async () => {
  64. const root = await mkdtemp(join("/tmp", "zcode-orphan-"));
  65. const layout = resolveServerLayout(join(root, ".zcode", "server"));
  66. await new ReleaseManager(layout).ensure();
  67. const coreEntry = fileURLToPath(new URL("../src/server-core/entry.ts", import.meta.url));
  68. const zcodeBuiltinProviderConfigFilePath = fileURLToPath(
  69. new URL("../../../config/provider/zcode-builtin.json", import.meta.url),
  70. );
  71. const harness = [
  72. "import { fork } from 'node:child_process';",
  73. `const core = fork(${JSON.stringify(coreEntry)}, ['1'], { execArgv: ['--import', 'tsx'], env: { ...process.env, ZCODE_SERVER_ROOT: ${JSON.stringify(layout.serverRoot)}, ZCODE_DATA_BASE_DIR: ${JSON.stringify(layout.dataBaseDir)}, ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: ${JSON.stringify(zcodeBuiltinProviderConfigFilePath)} }, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });`,
  74. "core.on('message', (message) => { if (message && message.type === 'ready') process.stdout.write(JSON.stringify(message)); });",
  75. ].join("\n");
  76. const supervisor = spawn(process.execPath, ["--input-type=module", "-e", harness], {
  77. env: process.env,
  78. stdio: ["ignore", "pipe", "ignore"],
  79. });
  80. let output = "";
  81. supervisor.stdout.on("data", (chunk) => {
  82. output += String(chunk);
  83. });
  84. const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
  85. (resolve) => {
  86. supervisor.once("exit", (code, signal) => resolve({ code, signal }));
  87. },
  88. );
  89. let corePids: number[] = [];
  90. try {
  91. await waitForCondition(() => {
  92. try {
  93. JSON.parse(output);
  94. return true;
  95. } catch {
  96. return false;
  97. }
  98. });
  99. const ready = JSON.parse(output) as { port?: number };
  100. if (!ready.port) throw new Error("Core did not publish a listening port");
  101. corePids = await listChildPids(supervisor.pid ?? -1);
  102. expect(corePids.length).toBeGreaterThan(0);
  103. supervisor.kill("SIGKILL");
  104. await expect(exited).resolves.toMatchObject({ signal: "SIGKILL" });
  105. await expect(waitForHttpClosed(ready.port)).resolves.toBe(true);
  106. } finally {
  107. if (supervisor.exitCode === null) supervisor.kill("SIGKILL");
  108. for (const pid of corePids) {
  109. try {
  110. process.kill(pid, "SIGKILL");
  111. } catch {
  112. /* child 已退出 */
  113. }
  114. }
  115. }
  116. }, 20_000);
  117. it("launches real old/new Core processes with release-scoped Agent wiring", async () => {
  118. // POSIX Unix socket 有路径长度限制,macOS 的 tmpdir() 可能位于很长的 /var/folders 路径;
  119. // 保持短路径,Windows 则使用其可移植的系统临时目录。
  120. const root = await mkdtemp(
  121. join(process.platform === "win32" ? tmpdir() : "/tmp", "zcode-runtime-"),
  122. );
  123. const layout = resolveServerLayout(join(root, ".zcode", "server"));
  124. const canonicalLayout = await resolveCanonicalServerLayout(layout.serverRoot);
  125. const releases = new ReleaseManager(layout);
  126. await releases.ensure();
  127. const fixture = fileURLToPath(new URL("./fixtures/coreWiringFixture.mjs", import.meta.url));
  128. for (const version of ["old", "new"]) {
  129. const runtimeRoot = join(layout.releasesDir, version, "runtime");
  130. await mkdir(runtimeRoot, { recursive: true });
  131. await symlink(process.execPath, join(runtimeRoot, "node"));
  132. await symlink(fixture, join(runtimeRoot, "server-core.js"));
  133. await writeFile(join(runtimeRoot, "zcode.cjs"), "", "utf8");
  134. }
  135. await releases.writePending({ version: "old", releaseDir: join(layout.releasesDir, "old") });
  136. await releases.applyPending();
  137. const wiringOutput = join(root, "wiring.jsonl");
  138. const mainEntry = fileURLToPath(new URL("../src/main.ts", import.meta.url));
  139. const child = spawn(
  140. process.execPath,
  141. [
  142. "--import",
  143. "tsx",
  144. mainEntry,
  145. "serve",
  146. "--supervisor",
  147. "--server-root",
  148. layout.serverRoot,
  149. "--json",
  150. ],
  151. {
  152. env: {
  153. ...process.env,
  154. ZCODE_TEST_WIRING_OUTPUT: wiringOutput,
  155. },
  156. stdio: ["ignore", "pipe", "pipe"],
  157. },
  158. );
  159. let diagnostics = "";
  160. child.stdout.on("data", (chunk) => {
  161. diagnostics += String(chunk);
  162. });
  163. child.stderr.on("data", (chunk) => {
  164. diagnostics += String(chunk);
  165. });
  166. const exited = new Promise<number | null>((resolve) => child.once("exit", resolve));
  167. try {
  168. await expect(waitForReady(layout.controlEndpoint)).resolves.toMatchObject({
  169. state: "ready",
  170. serviceRegistered: false,
  171. });
  172. // control socket 会比外层 serve 命令返回稍早;先等 CLI 完成自己的 ready barrier,
  173. // 避免测试立即 update/stop 让启动调用方错过短暂的 ready 状态。
  174. await waitForCondition(() => diagnostics.includes('"state":"ready"'));
  175. await releases.writePending({ version: "new", releaseDir: join(layout.releasesDir, "new") });
  176. await expect(
  177. requestControl(layout.controlEndpoint, { command: "apply-update" }, 15_000),
  178. ).resolves.toMatchObject({ applied: true, version: "new" });
  179. await expect(waitForReady(layout.controlEndpoint)).resolves.toMatchObject({
  180. state: "ready",
  181. serviceRegistered: false,
  182. });
  183. await requestControl(layout.controlEndpoint, { command: "stop" }, 2_000);
  184. await expect(exited).resolves.toBe(0);
  185. } catch (error) {
  186. await requestControl(layout.controlEndpoint, { command: "stop" }, 500).catch(() => undefined);
  187. await Promise.race([exited, new Promise<void>((resolve) => setTimeout(resolve, 1_000))]);
  188. if (child.exitCode === null) child.kill("SIGKILL");
  189. throw new Error(`${error instanceof Error ? error.message : String(error)}\n${diagnostics}`);
  190. }
  191. const records = (await readFile(wiringOutput, "utf8"))
  192. .trim()
  193. .split("\n")
  194. .map(
  195. (line) =>
  196. JSON.parse(line) as {
  197. agentArgs: string[];
  198. agentCommand: string;
  199. dataBaseDir: string;
  200. runtimeRoot: string;
  201. },
  202. );
  203. expect(records).toHaveLength(2);
  204. for (const [index, version] of ["old", "new"].entries()) {
  205. const runtimeRoot = join(layout.releasesDir, version, "runtime");
  206. expect(records[index]).toMatchObject({
  207. agentArgs: [join(runtimeRoot, "zcode.cjs"), "app-server", "--stdio"],
  208. agentCommand: join(runtimeRoot, "node"),
  209. dataBaseDir: canonicalLayout.dataBaseDir,
  210. runtimeRoot,
  211. });
  212. }
  213. }, 30_000);
  214. });