test-web-app-gateway-reset.mjs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. #!/usr/bin/env node
  2. import { spawn } from "node:child_process";
  3. import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
  4. import { request as httpRequest } from "node:http";
  5. import { connect as connectTcp, createServer as createTcpServer } from "node:net";
  6. import { tmpdir } from "node:os";
  7. import { join, resolve } from "node:path";
  8. import { pathToFileURL } from "node:url";
  9. const repoRoot = resolve(import.meta.dirname, "..");
  10. const startScript = join(repoRoot, "docker/web-app/start.mjs");
  11. const tempDir = await mkdtemp(join(tmpdir(), "zcode-web-app-gateway-reset-"));
  12. const dataDir = join(tempDir, "data");
  13. const workspaceDir = join(tempDir, "workspace");
  14. const webDistDir = join(tempDir, "web");
  15. const backendEntry = join(tempDir, "backend.mjs");
  16. const agentEntry = join(tempDir, "agent.cjs");
  17. const injectResetEntry = join(tempDir, "inject-reset.mjs");
  18. const publicPort = await reservePort();
  19. const backendPort = await reservePort();
  20. let child;
  21. try {
  22. await mkdir(dataDir, { recursive: true });
  23. await mkdir(workspaceDir, { recursive: true });
  24. await mkdir(webDistDir, { recursive: true });
  25. await writeFile(join(webDistDir, "index.html"), "<!doctype html><html><body>ZCode test</body></html>\n");
  26. await writeFile(agentEntry, "module.exports = {};\n");
  27. await writeFile(
  28. injectResetEntry,
  29. `setTimeout(() => {
  30. process.emit("uncaughtException", Object.assign(new Error("read ECONNRESET"), {
  31. code: "ECONNRESET",
  32. syscall: "read",
  33. }));
  34. }, 250);
  35. `,
  36. );
  37. await writeFile(
  38. backendEntry,
  39. `import { createServer } from "node:http";
  40. const startDelayMs = Number(process.env.ZCODE_TEST_BACKEND_START_DELAY_MS || 0);
  41. setTimeout(() => {
  42. const server = createServer((req, res) => {
  43. if (req.url === "/api/stream") {
  44. res.writeHead(200, { "content-type": "application/octet-stream" });
  45. const payload = Buffer.alloc(64 * 1024, "x");
  46. const timer = setInterval(() => {
  47. res.write(payload);
  48. }, 5);
  49. res.on("close", () => clearInterval(timer));
  50. return;
  51. }
  52. res.writeHead(200, { "content-type": "application/json" });
  53. res.end(JSON.stringify({ ok: true }));
  54. });
  55. server.on("upgrade", (_req, socket) => {
  56. socket.write("HTTP/1.1 101 Switching Protocols\\r\\nConnection: Upgrade\\r\\nUpgrade: websocket\\r\\n\\r\\n");
  57. });
  58. server.listen(Number(process.env.PORT), "127.0.0.1");
  59. }, startDelayMs);
  60. `,
  61. );
  62. child = spawn(process.execPath, [startScript], {
  63. cwd: repoRoot,
  64. env: {
  65. ...process.env,
  66. NODE_OPTIONS: appendNodeImport(process.env.NODE_OPTIONS, injectResetEntry),
  67. PORT: String(publicPort),
  68. ZCODE_BACKEND_PORT: String(backendPort),
  69. ZCODE_DATA_BASE_DIR: dataDir,
  70. ZCODE_SERVER_ENTRY: backendEntry,
  71. ZCODE_AGENT_ENTRY: agentEntry,
  72. ZCODE_SERVER_WORKSPACE: workspaceDir,
  73. ZCODE_STORAGE_DIR: join(dataDir, ".zcode"),
  74. ZCODE_TEST_BACKEND_START_DELAY_MS: "1000",
  75. ZCODE_WEB_DIST_DIR: webDistDir,
  76. },
  77. stdio: ["ignore", "pipe", "pipe"],
  78. });
  79. const output = [];
  80. child.stdout.on("data", (chunk) => output.push(String(chunk)));
  81. child.stderr.on("data", (chunk) => output.push(String(chunk)));
  82. await waitForOutput(output, "listening on", 5_000);
  83. await assertHealthzStatus(publicPort, 503);
  84. await waitForHealthzStatus(publicPort, 200, 5_000);
  85. await delay(500);
  86. await resetHttpStream(publicPort);
  87. await resetUpgradeConnection(publicPort);
  88. await delay(1_000);
  89. if (child.exitCode !== null) {
  90. throw new Error(`gateway exited after client disconnects:\n${output.join("")}`);
  91. }
  92. await assertHealthzStatus(publicPort, 200);
  93. console.log("web app gateway tolerates reset client connections");
  94. } finally {
  95. if (child && child.exitCode === null) {
  96. child.kill("SIGTERM");
  97. await waitForExit(child, 5_000).catch(() => child.kill("SIGKILL"));
  98. }
  99. await rm(tempDir, { force: true, recursive: true });
  100. }
  101. async function reservePort() {
  102. const server = createTcpServer();
  103. await new Promise((resolveListen, rejectListen) => {
  104. server.once("error", rejectListen);
  105. server.listen(0, "127.0.0.1", resolveListen);
  106. });
  107. const address = server.address();
  108. const port = typeof address === "object" && address ? address.port : null;
  109. await new Promise((resolveClose) => server.close(resolveClose));
  110. if (!port) {
  111. throw new Error("failed to reserve port");
  112. }
  113. return port;
  114. }
  115. async function waitForOutput(output, text, timeoutMs) {
  116. const start = Date.now();
  117. while (Date.now() - start < timeoutMs) {
  118. if (output.join("").includes(text)) {
  119. return;
  120. }
  121. await delay(25);
  122. }
  123. throw new Error(`timed out waiting for ${text}:\n${output.join("")}`);
  124. }
  125. async function resetHttpStream(port) {
  126. await new Promise((resolveAbort) => {
  127. const req = httpRequest({ hostname: "127.0.0.1", path: "/api/stream", port }, (res) => {
  128. res.resume();
  129. res.once("data", () => {
  130. resetSocket(req.socket);
  131. resolveAbort();
  132. });
  133. res.on("end", resolveAbort);
  134. });
  135. req.on("error", () => resolveAbort());
  136. req.end();
  137. });
  138. }
  139. async function resetUpgradeConnection(port) {
  140. await new Promise((resolveReset, rejectReset) => {
  141. const socket = connectTcp(port, "127.0.0.1");
  142. const timer = setTimeout(() => {
  143. socket.destroy();
  144. rejectReset(new Error("upgrade reset timed out"));
  145. }, 1_000);
  146. socket.once("error", () => {
  147. clearTimeout(timer);
  148. resolveReset();
  149. });
  150. socket.once("connect", () => {
  151. socket.write(
  152. "GET /ws HTTP/1.1\r\n" +
  153. "Host: 127.0.0.1\r\n" +
  154. "Connection: Upgrade\r\n" +
  155. "Upgrade: websocket\r\n" +
  156. "Sec-WebSocket-Version: 13\r\n" +
  157. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" +
  158. "\r\n",
  159. );
  160. setTimeout(() => {
  161. resetSocket(socket);
  162. clearTimeout(timer);
  163. resolveReset();
  164. }, 20);
  165. });
  166. });
  167. }
  168. async function waitForHealthzStatus(port, expectedStatus, timeoutMs) {
  169. const start = Date.now();
  170. let lastResult;
  171. while (Date.now() - start < timeoutMs) {
  172. lastResult = await requestHealthz(port).catch((error) => ({ error: error.message }));
  173. if (lastResult.statusCode === expectedStatus) {
  174. return;
  175. }
  176. await delay(25);
  177. }
  178. throw new Error(`timed out waiting for healthz ${expectedStatus}: ${JSON.stringify(lastResult)}`);
  179. }
  180. async function assertHealthzStatus(port, expectedStatus) {
  181. const result = await requestHealthz(port);
  182. if (result.statusCode !== expectedStatus) {
  183. throw new Error(`healthz returned ${result.statusCode}, expected ${expectedStatus}: ${result.body}`);
  184. }
  185. if (expectedStatus === 200 && !result.body.includes('"ok":true')) {
  186. throw new Error(`unexpected healthz body: ${result.body}`);
  187. }
  188. if (expectedStatus !== 200 && !result.body.includes('"ok":false')) {
  189. throw new Error(`unexpected non-ready healthz body: ${result.body}`);
  190. }
  191. }
  192. async function requestHealthz(port) {
  193. return new Promise((resolveBody, rejectBody) => {
  194. const req = httpRequest({ hostname: "127.0.0.1", path: "/healthz", port }, (res) => {
  195. let data = "";
  196. res.setEncoding("utf8");
  197. res.on("data", (chunk) => {
  198. data += chunk;
  199. });
  200. res.on("end", () => {
  201. resolveBody({ body: data, statusCode: res.statusCode });
  202. });
  203. });
  204. req.on("error", rejectBody);
  205. req.end();
  206. });
  207. }
  208. async function waitForExit(childProcess, timeoutMs) {
  209. if (childProcess.exitCode !== null) {
  210. return;
  211. }
  212. await new Promise((resolveExit, rejectExit) => {
  213. const timer = setTimeout(() => {
  214. childProcess.off("exit", onExit);
  215. rejectExit(new Error("timed out waiting for child exit"));
  216. }, timeoutMs);
  217. function onExit() {
  218. clearTimeout(timer);
  219. resolveExit();
  220. }
  221. childProcess.once("exit", onExit);
  222. });
  223. }
  224. function delay(ms) {
  225. return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
  226. }
  227. function resetSocket(socket) {
  228. if (!socket) {
  229. return;
  230. }
  231. if (typeof socket.resetAndDestroy === "function") {
  232. socket.resetAndDestroy();
  233. return;
  234. }
  235. socket.destroy(Object.assign(new Error("client reset"), { code: "ECONNRESET" }));
  236. }
  237. function appendNodeImport(existingOptions, importPath) {
  238. const importOption = `--import=${pathToFileURL(importPath).href}`;
  239. return existingOptions?.trim() ? `${existingOptions} ${importOption}` : importOption;
  240. }