proxyStdio.test.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { createServer } from "node:net";
  2. import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { PassThrough } from "node:stream";
  6. import { describe, expect, it } from "vitest";
  7. import { runProxyStdio } from "../src/server-core/proxyStdio.js";
  8. import { resolveServerLayout } from "../src/runtime/paths.js";
  9. async function writeReadyStatus(serverRoot: string, port: number): Promise<void> {
  10. const layout = resolveServerLayout(serverRoot);
  11. await mkdir(layout.runDir, { recursive: true });
  12. await writeFile(
  13. layout.statusFile,
  14. JSON.stringify({
  15. protocolVersion: 1,
  16. state: "ready",
  17. pid: process.pid,
  18. port,
  19. host: "127.0.0.1",
  20. version: "3.8.0",
  21. generation: 1,
  22. startedAt: Date.now(),
  23. lastExitReason: null,
  24. serviceRegistered: false,
  25. runningTaskCount: 0,
  26. crashBudget: { crashCount: 0, nextRestartDelayMs: 1_000, exhausted: false },
  27. updatedAt: Date.now(),
  28. }),
  29. );
  30. }
  31. describe("server proxy-stdio", () => {
  32. it("forwards arbitrary bytes between stdio and the ready loopback daemon", async () => {
  33. const echo = createServer((socket) => socket.pipe(socket));
  34. await new Promise<void>((resolve) => echo.listen(0, "127.0.0.1", resolve));
  35. const address = echo.address();
  36. if (!address || typeof address === "string") throw new Error("missing echo port");
  37. const root = await mkdtemp(join(tmpdir(), "zcode-r3-proxy-stdio-"));
  38. const layout = resolveServerLayout(join(root, "server"));
  39. await writeReadyStatus(layout.serverRoot, address.port);
  40. const input = new PassThrough();
  41. const output = new PassThrough();
  42. const received: Buffer[] = [];
  43. output.on("data", (chunk) => received.push(Buffer.from(chunk)));
  44. const payload = Buffer.from([0, 1, 2, 13, 10, 127, 128, 254, 255]);
  45. const forwarding = runProxyStdio({ layout, input, output });
  46. input.end(payload);
  47. await forwarding;
  48. await new Promise<void>((resolve) => echo.close(() => resolve()));
  49. expect(Buffer.concat(received)).toEqual(payload);
  50. });
  51. it("fails before writing channel bytes when daemon status is missing", async () => {
  52. const root = await mkdtemp(join(tmpdir(), "zcode-r3-proxy-stdio-missing-"));
  53. const layout = resolveServerLayout(join(root, "server"));
  54. await expect(
  55. runProxyStdio({
  56. layout,
  57. input: new PassThrough(),
  58. output: new PassThrough(),
  59. }),
  60. ).rejects.toMatchObject({ code: "daemon-not-ready" });
  61. });
  62. });