observation-events.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { readdir, stat } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import type {
  4. ObservationChangeEvent,
  5. ObservationHelloEvent,
  6. ObservationSourceErrorEvent,
  7. ObservationSourceFingerprint,
  8. ObservationSourceKind,
  9. } from "../src/shared.js";
  10. import { defaultDbPath, defaultLogDir } from "./sources.js";
  11. import type { ObservationOptions } from "./types.js";
  12. interface ObservationEventStreamOptions {
  13. intervalMs?: number;
  14. now?: () => Date;
  15. }
  16. interface ObservationWatchTarget {
  17. kind: ObservationSourceKind;
  18. label: string;
  19. path: string;
  20. jsonlOnly?: boolean;
  21. ignoreMtime?: boolean;
  22. }
  23. const DEFAULT_OBSERVATION_EVENT_INTERVAL_MS = 750;
  24. const MIN_OBSERVATION_EVENT_INTERVAL_MS = 50;
  25. const OBSERVATION_EVENT_RETRY_MS = 1500;
  26. export function createObservationEventStream(
  27. options: ObservationOptions,
  28. streamOptions: ObservationEventStreamOptions = {},
  29. ): ReadableStream<Uint8Array> {
  30. const encoder = new TextEncoder();
  31. const intervalMs = normalizeInterval(streamOptions.intervalMs);
  32. const now = streamOptions.now ?? (() => new Date());
  33. let revision = 0;
  34. let previousSources: ObservationSourceFingerprint[] = [];
  35. let timer: ReturnType<typeof setInterval> | undefined;
  36. let closed = false;
  37. let checking = false;
  38. const encodeEvent = (type: string, data: unknown): Uint8Array =>
  39. encoder.encode(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`);
  40. const enqueueEvent = (
  41. controller: ReadableStreamDefaultController<Uint8Array>,
  42. type: string,
  43. data: unknown,
  44. ): void => {
  45. if (closed) return;
  46. try {
  47. controller.enqueue(encodeEvent(type, data));
  48. } catch {
  49. closed = true;
  50. }
  51. };
  52. const checkSources = async (
  53. controller: ReadableStreamDefaultController<Uint8Array>,
  54. ): Promise<void> => {
  55. if (checking || closed) return;
  56. checking = true;
  57. try {
  58. const nextSources = await fingerprintObservationSources(options);
  59. const changedSources = diffSources(previousSources, nextSources);
  60. if (changedSources.length > 0) {
  61. previousSources = nextSources;
  62. revision += 1;
  63. const event: ObservationChangeEvent = {
  64. revision,
  65. changedAt: now().toISOString(),
  66. changedSources,
  67. sources: nextSources,
  68. };
  69. enqueueEvent(controller, "change", event);
  70. }
  71. } catch (error) {
  72. const event: ObservationSourceErrorEvent = {
  73. checkedAt: now().toISOString(),
  74. message: error instanceof Error ? error.message : String(error),
  75. };
  76. enqueueEvent(controller, "source-error", event);
  77. } finally {
  78. checking = false;
  79. }
  80. };
  81. return new ReadableStream({
  82. async start(controller) {
  83. controller.enqueue(encoder.encode(`retry: ${OBSERVATION_EVENT_RETRY_MS}\n\n`));
  84. previousSources = await fingerprintObservationSources(options);
  85. const hello: ObservationHelloEvent = {
  86. generatedAt: now().toISOString(),
  87. intervalMs,
  88. sources: previousSources,
  89. };
  90. enqueueEvent(controller, "hello", hello);
  91. timer = setInterval(() => {
  92. void checkSources(controller);
  93. }, intervalMs);
  94. timer.unref?.();
  95. },
  96. cancel() {
  97. closed = true;
  98. if (timer) clearInterval(timer);
  99. },
  100. });
  101. }
  102. export async function fingerprintObservationSources(
  103. options: ObservationOptions,
  104. ): Promise<ObservationSourceFingerprint[]> {
  105. const fingerprints: ObservationSourceFingerprint[] = [];
  106. for (const target of observationWatchTargets(options)) {
  107. fingerprints.push(await fingerprintTarget(target));
  108. }
  109. return fingerprints;
  110. }
  111. function observationWatchTargets(options: ObservationOptions): ObservationWatchTarget[] {
  112. const dbPath = resolve(options.dbPath ?? defaultDbPath());
  113. const targets: ObservationWatchTarget[] = [
  114. {
  115. kind: "log",
  116. label: "结构化日志",
  117. path: resolve(options.logDir ?? defaultLogDir()),
  118. jsonlOnly: true,
  119. },
  120. ];
  121. if (options.eventPath) {
  122. targets.push({
  123. kind: "eventlog",
  124. label: "Session 事件 JSONL",
  125. path: resolve(options.eventPath),
  126. jsonlOnly: true,
  127. });
  128. }
  129. targets.push(
  130. {
  131. kind: "sqlite",
  132. label: "SQLite Session 数据库",
  133. path: dbPath,
  134. },
  135. {
  136. kind: "sqlite",
  137. label: "SQLite WAL",
  138. path: `${dbPath}-wal`,
  139. },
  140. {
  141. kind: "sqlite",
  142. label: "SQLite SHM",
  143. path: `${dbPath}-shm`,
  144. ignoreMtime: true,
  145. },
  146. );
  147. return targets;
  148. }
  149. async function fingerprintTarget(
  150. target: ObservationWatchTarget,
  151. ): Promise<ObservationSourceFingerprint> {
  152. try {
  153. const inputStat = await stat(target.path);
  154. if (inputStat.isDirectory()) {
  155. const entries = (await readdir(target.path))
  156. .filter((entry) => !target.jsonlOnly || entry.endsWith(".jsonl") || entry.endsWith(".log"))
  157. .sort();
  158. const parts: string[] = [];
  159. for (const entry of entries) {
  160. const entryPath = join(target.path, entry);
  161. try {
  162. const entryStat = await stat(entryPath);
  163. const kind = entryStat.isDirectory() ? "dir" : "file";
  164. parts.push(`${entry}:${kind}:${entryStat.size}:${mtimeSignature(entryStat.mtimeMs)}`);
  165. } catch {
  166. parts.push(`${entry}:missing`);
  167. }
  168. }
  169. return {
  170. kind: target.kind,
  171. label: target.label,
  172. path: target.path,
  173. exists: true,
  174. signature: `dir:${mtimeSignature(inputStat.mtimeMs)}:${parts.join("|")}`,
  175. };
  176. }
  177. // SQLite readers, including this debug app's own read-only analyzer pass, can update
  178. // the WAL shared-memory file mtime. Treating that mtime as data change makes the UI
  179. // refresh itself forever, so SHM fingerprints only track existence and size.
  180. const signature = target.ignoreMtime
  181. ? `file:${inputStat.size}`
  182. : `file:${inputStat.size}:${mtimeSignature(inputStat.mtimeMs)}`;
  183. return {
  184. kind: target.kind,
  185. label: target.label,
  186. path: target.path,
  187. exists: true,
  188. signature,
  189. };
  190. } catch (error) {
  191. if (isMissingPathError(error)) {
  192. return {
  193. kind: target.kind,
  194. label: target.label,
  195. path: target.path,
  196. exists: false,
  197. signature: "missing",
  198. };
  199. }
  200. return {
  201. kind: target.kind,
  202. label: target.label,
  203. path: target.path,
  204. exists: false,
  205. signature: `error:${error instanceof Error ? error.message : String(error)}`,
  206. };
  207. }
  208. }
  209. function diffSources(
  210. previousSources: ObservationSourceFingerprint[],
  211. nextSources: ObservationSourceFingerprint[],
  212. ): ObservationSourceFingerprint[] {
  213. const previousByKey = new Map(
  214. previousSources.map((source) => [sourceFingerprintKey(source), source.signature]),
  215. );
  216. return nextSources.filter(
  217. (source) => previousByKey.get(sourceFingerprintKey(source)) !== source.signature,
  218. );
  219. }
  220. function sourceFingerprintKey(source: ObservationSourceFingerprint): string {
  221. return `${source.kind}:${source.label}:${source.path}`;
  222. }
  223. function normalizeInterval(value?: number): number {
  224. if (typeof value !== "number" || !Number.isFinite(value)) {
  225. return DEFAULT_OBSERVATION_EVENT_INTERVAL_MS;
  226. }
  227. return Math.max(Math.trunc(value), MIN_OBSERVATION_EVENT_INTERVAL_MS);
  228. }
  229. function mtimeSignature(value: number): string {
  230. return Math.floor(value).toString(36);
  231. }
  232. function isMissingPathError(error: unknown): boolean {
  233. return (
  234. typeof error === "object" &&
  235. error !== null &&
  236. "code" in error &&
  237. (error.code === "ENOENT" || error.code === "ENOTDIR")
  238. );
  239. }