observation-events.test.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import { appendFile, mkdir, mkdtemp, utimes, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createDebugApp } from "../server/index.js";
  6. import {
  7. createObservationEventStream,
  8. fingerprintObservationSources,
  9. } from "../server/observation-events.js";
  10. describe("observation events", () => {
  11. it("emits SSE changes when observed JSONL files change", async () => {
  12. const root = await mkdtemp(join(tmpdir(), "zcode-debug-events-"));
  13. const logDir = join(root, "log");
  14. const logPath = join(logDir, "debug.jsonl");
  15. await mkdir(logDir);
  16. await writeFile(logPath, `${JSON.stringify({ message: "before" })}\n`, "utf8");
  17. const stream = createObservationEventStream(
  18. {
  19. logDir,
  20. dbPath: join(root, "missing.sqlite"),
  21. },
  22. { intervalMs: 50 },
  23. );
  24. const reader = stream.getReader();
  25. try {
  26. await readUntil(reader, "event: hello");
  27. await appendFile(logPath, `${JSON.stringify({ message: "after" })}\n`, "utf8");
  28. const eventText = await readUntil(reader, "event: change");
  29. expect(eventText).toContain("结构化日志");
  30. expect(eventText).toContain(logDir);
  31. } finally {
  32. await reader.cancel();
  33. }
  34. });
  35. it("exposes the observation event stream from the API", async () => {
  36. const root = await mkdtemp(join(tmpdir(), "zcode-debug-events-api-"));
  37. const logDir = join(root, "log");
  38. await mkdir(logDir);
  39. const app = createDebugApp();
  40. const response = await app.request(
  41. `/api/observations/events?logDir=${encodeURIComponent(logDir)}&dbPath=${encodeURIComponent(
  42. join(root, "missing.sqlite"),
  43. )}`,
  44. );
  45. const reader = response.body?.getReader();
  46. if (!reader) throw new Error("response body is missing");
  47. try {
  48. const eventText = await readUntil(reader, "event: hello");
  49. expect(response.status).toBe(200);
  50. expect(response.headers.get("content-type")).toContain("text/event-stream");
  51. expect(eventText).toContain("event: hello");
  52. } finally {
  53. await reader.cancel();
  54. }
  55. });
  56. it("includes SQLite WAL companion files in the fingerprint set", async () => {
  57. const root = await mkdtemp(join(tmpdir(), "zcode-debug-events-sqlite-"));
  58. const dbPath = join(root, "db.sqlite");
  59. const sources = await fingerprintObservationSources({
  60. logDir: join(root, "missing-log"),
  61. dbPath,
  62. });
  63. expect(sources.map((source) => source.path)).toEqual(
  64. expect.arrayContaining([dbPath, `${dbPath}-wal`, `${dbPath}-shm`]),
  65. );
  66. });
  67. it("does not treat SQLite SHM mtime churn as a source change", async () => {
  68. const root = await mkdtemp(join(tmpdir(), "zcode-debug-events-sqlite-shm-"));
  69. const dbPath = join(root, "db.sqlite");
  70. const shmPath = `${dbPath}-shm`;
  71. await writeFile(shmPath, "shared-memory-index", "utf8");
  72. const before = await fingerprintObservationSources({
  73. logDir: join(root, "missing-log"),
  74. dbPath,
  75. });
  76. await utimes(
  77. shmPath,
  78. new Date("2026-05-04T01:00:00.000Z"),
  79. new Date("2026-05-04T01:00:00.000Z"),
  80. );
  81. const after = await fingerprintObservationSources({
  82. logDir: join(root, "missing-log"),
  83. dbPath,
  84. });
  85. const beforeShm = before.find((source) => source.path === shmPath);
  86. const afterShm = after.find((source) => source.path === shmPath);
  87. expect(afterShm?.signature).toBe(beforeShm?.signature);
  88. });
  89. });
  90. async function readUntil(
  91. reader: ReadableStreamDefaultReader<Uint8Array>,
  92. pattern: string,
  93. ): Promise<string> {
  94. let text = "";
  95. const deadline = Date.now() + 2_000;
  96. while (Date.now() < deadline) {
  97. const remainingMs = Math.max(deadline - Date.now(), 1);
  98. const result = await Promise.race([
  99. reader.read(),
  100. new Promise<null>((resolve) => setTimeout(() => resolve(null), remainingMs)),
  101. ]);
  102. if (result === null) break;
  103. if (result.done) break;
  104. text += Buffer.from(result.value).toString("utf8");
  105. if (text.includes(pattern)) return text;
  106. }
  107. throw new Error(`Timed out waiting for ${pattern}. Read: ${text}`);
  108. }