hostMemoryDiagnosticsLog.test.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { describe, expect, it, vi } from "vitest";
  2. import { startHostMemoryDiagnosticsLog } from "../src/host/hostMemoryDiagnosticsLog.js";
  3. const usage = (heapUsed: number): NodeJS.MemoryUsage => ({
  4. rss: 200 * 1024 * 1024,
  5. heapTotal: 100 * 1024 * 1024,
  6. heapUsed,
  7. external: 10 * 1024 * 1024,
  8. arrayBuffers: 1024 * 1024,
  9. });
  10. describe("startHostMemoryDiagnosticsLog", () => {
  11. it("MEM-008 按 60s 节拍采样,首次写盘、无变化不写、计数器变化再写;stop 后不再输出", () => {
  12. const info = vi.fn();
  13. let tick: (() => void) | undefined;
  14. const clearInterval = vi.fn();
  15. let nowMs = 0;
  16. let counters: Record<string, number> = { "terminal.open": 1 };
  17. const log = startHostMemoryDiagnosticsLog({
  18. logger: { info },
  19. collectCounters: () => counters,
  20. readMemoryUsage: () => usage(50 * 1024 * 1024),
  21. now: () => nowMs,
  22. timer: {
  23. setInterval(callback, intervalMs) {
  24. expect(intervalMs).toBe(60_000);
  25. tick = callback;
  26. return { unref: vi.fn() };
  27. },
  28. clearInterval,
  29. },
  30. });
  31. nowMs = 60_000;
  32. tick?.();
  33. expect(info).toHaveBeenCalledOnce();
  34. expect(info.mock.calls[0]?.[0]).toBe(
  35. "[memory] role=utility_host reason=first rssKb=204800 heapUsedKb=51200 heapTotalKb=102400 externalKb=10240 arrayBuffersKb=1024 terminal.open=1",
  36. );
  37. nowMs = 120_000;
  38. tick?.();
  39. expect(info).toHaveBeenCalledOnce();
  40. counters = { "terminal.open": 2 };
  41. nowMs = 180_000;
  42. tick?.();
  43. expect(info).toHaveBeenCalledTimes(2);
  44. expect(info.mock.calls[1]?.[0]).toContain("reason=changed");
  45. expect(info.mock.calls[1]?.[0]).toContain("terminal.open=2");
  46. log.stop();
  47. log.stop();
  48. expect(clearInterval).toHaveBeenCalledOnce();
  49. });
  50. it("计数器读取抛错时只丢当前样本,不抛出也不写盘", () => {
  51. const info = vi.fn();
  52. const log = startHostMemoryDiagnosticsLog({
  53. logger: { info },
  54. collectCounters: () => {
  55. throw new Error("services disposed");
  56. },
  57. readMemoryUsage: () => usage(1024),
  58. timer: { setInterval: () => ({ unref: vi.fn() }), clearInterval: vi.fn() },
  59. });
  60. expect(log.sampleNow()).toBe(false);
  61. expect(info).not.toHaveBeenCalled();
  62. log.stop();
  63. });
  64. });