index.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { existsSync } from "node:fs";
  2. import { readFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import { fileURLToPath } from "node:url";
  5. import { serve } from "@hono/node-server";
  6. import { serveStatic } from "@hono/node-server/serve-static";
  7. import { cors } from "hono/cors";
  8. import { Hono } from "hono";
  9. import { inspectTrace, listTraces } from "./analyzer.js";
  10. import {
  11. createNetworkCaptureServiceFromEnv,
  12. disabledNetworkCaptureStatus,
  13. type NetworkCaptureService,
  14. } from "./network-capture.js";
  15. import { createObservationEventStream } from "./observation-events.js";
  16. import type { ObservationOptions } from "./types.js";
  17. interface DebugAppOptions {
  18. staticRoot?: string;
  19. networkCapture?: NetworkCaptureService;
  20. }
  21. interface DebugServerOptions extends Omit<DebugAppOptions, "networkCapture"> {
  22. host?: string;
  23. port?: number;
  24. networkCapture?: NetworkCaptureService | false;
  25. }
  26. export function createDebugApp(options: DebugAppOptions = {}): Hono {
  27. const app = new Hono();
  28. app.use("*", cors());
  29. app.get("/api/health", (context) =>
  30. context.json({
  31. ok: true,
  32. service: "zcode-debug",
  33. }),
  34. );
  35. app.get("/api/traces", async (context) =>
  36. context.json(await listTraces(queryToOptions(context.req.query()))),
  37. );
  38. app.get("/api/traces/:traceId", async (context) => {
  39. const traceId = context.req.param("traceId");
  40. return context.json(await inspectTrace(traceId, queryToOptions(context.req.query())));
  41. });
  42. app.get("/api/observations/events", (context) => {
  43. const stream = createObservationEventStream(queryToOptions(context.req.query()));
  44. return context.body(stream, 200, {
  45. "Content-Type": "text/event-stream",
  46. "Cache-Control": "no-cache, no-transform",
  47. Connection: "keep-alive",
  48. });
  49. });
  50. app.get("/api/network/status", (context) =>
  51. context.json(options.networkCapture?.getStatus() ?? disabledNetworkCaptureStatus()),
  52. );
  53. app.get("/api/network/requests", (context) => {
  54. const query = context.req.query();
  55. const limit = parsePositiveInteger(query.limit);
  56. const status = options.networkCapture?.getStatus() ?? disabledNetworkCaptureStatus();
  57. const requests =
  58. options.networkCapture?.listRequests({
  59. traceId: query.traceId || undefined,
  60. limit,
  61. }) ?? [];
  62. return context.json({ status, requests });
  63. });
  64. app.get("/api/network/ca.pem", async (context) => {
  65. const status = options.networkCapture?.getStatus();
  66. const path = status?.certificate.caCertPath;
  67. if (!path || !status.certificate.caCertAvailable) {
  68. return context.text("network capture CA certificate is not available", 404);
  69. }
  70. const certificate = await readFile(path, "utf8");
  71. return context.body(certificate, 200, {
  72. "Content-Type": "application/x-pem-file; charset=utf-8",
  73. "Content-Disposition": 'inline; filename="zcode-debug-ca.pem"',
  74. });
  75. });
  76. app.get("/api/network/events", (context) => {
  77. const stream = createNetworkEventStream(options.networkCapture);
  78. return context.body(stream, 200, {
  79. "Content-Type": "text/event-stream",
  80. "Cache-Control": "no-cache, no-transform",
  81. Connection: "keep-alive",
  82. });
  83. });
  84. if (options.staticRoot && existsSync(options.staticRoot)) {
  85. app.use("/*", serveStatic({ root: options.staticRoot }));
  86. app.get("*", async (context) => {
  87. const index = await readFile(join(options.staticRoot ?? "", "index.html"), "utf8");
  88. return context.html(index);
  89. });
  90. }
  91. return app;
  92. }
  93. export function startDebugServer(options: DebugServerOptions = {}) {
  94. const port = options.port ?? 4174;
  95. const hostname = options.host ?? "127.0.0.1";
  96. const networkCapture =
  97. options.networkCapture === false
  98. ? undefined
  99. : options.networkCapture ?? createNetworkCaptureServiceFromEnv();
  100. const app = createDebugApp({ ...options, networkCapture });
  101. const server = serve({
  102. fetch: app.fetch,
  103. hostname,
  104. port,
  105. });
  106. if (networkCapture) {
  107. void networkCapture.start().catch(() => {
  108. // Startup failures are exposed through /api/network/status so the debug UI can keep running.
  109. });
  110. server.on("close", () => {
  111. void networkCapture.stop();
  112. });
  113. }
  114. return server;
  115. }
  116. function queryToOptions(query: Record<string, string>): ObservationOptions {
  117. return {
  118. sessionId: query.sessionId || undefined,
  119. logDir: query.logDir || undefined,
  120. dbPath: query.dbPath || undefined,
  121. eventPath: query.eventPath || undefined,
  122. projectId: query.projectId || undefined,
  123. limit: parsePositiveInteger(query.limit),
  124. };
  125. }
  126. function parsePositiveInteger(value?: string): number | undefined {
  127. if (!value) return undefined;
  128. const parsed = Number(value);
  129. return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
  130. }
  131. function createNetworkEventStream(
  132. networkCapture: NetworkCaptureService | undefined,
  133. ): ReadableStream<Uint8Array> {
  134. const encoder = new TextEncoder();
  135. const writeEvent = (type: string, data: unknown): Uint8Array =>
  136. encoder.encode(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`);
  137. let unsubscribe: (() => void) | undefined;
  138. return new ReadableStream({
  139. start(controller) {
  140. if (!networkCapture) {
  141. controller.enqueue(writeEvent("status", disabledNetworkCaptureStatus()));
  142. return;
  143. }
  144. controller.enqueue(writeEvent("status", networkCapture.getStatus()));
  145. controller.enqueue(writeEvent("snapshot", networkCapture.listRequests()));
  146. unsubscribe = networkCapture.subscribe((event) => {
  147. if (event.type === "status") controller.enqueue(writeEvent("status", event.status));
  148. if (event.type === "snapshot") controller.enqueue(writeEvent("snapshot", event.requests));
  149. if (event.type === "request") controller.enqueue(writeEvent("request", event.request));
  150. if (event.type === "reset") controller.enqueue(writeEvent("reset", {}));
  151. });
  152. },
  153. cancel() {
  154. unsubscribe?.();
  155. },
  156. });
  157. }
  158. const currentFile = fileURLToPath(import.meta.url);
  159. if (process.argv[1] && resolve(process.argv[1]) === currentFile) {
  160. const staticRoot = resolve(process.cwd(), "dist");
  161. const networkCapture = createNetworkCaptureServiceFromEnv();
  162. networkCapture?.subscribe((event) => {
  163. if (event.type === "status" && event.status.running) {
  164. console.log(
  165. `network proxy listening on ${event.status.proxyUrl} (CA ${event.status.certificate.caCertPath})`,
  166. );
  167. }
  168. });
  169. const server = startDebugServer({
  170. staticRoot,
  171. port: parsePositiveInteger(process.env.PORT) ?? 4174,
  172. networkCapture,
  173. });
  174. server.on("listening", () => {
  175. const address = server.address();
  176. const port = typeof address === "object" && address ? address.port : 4174;
  177. console.log(`debug listening on http://127.0.0.1:${port}`);
  178. });
  179. }