process-resource-sampler.test.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import { zcodeProcessResourceSampleSchema } from "@zcode/shared";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. ZCODE_PROCESS_RESOURCE_SAMPLE_INTERVAL_MS,
  5. createZCodeProcessResourceSampler,
  6. type ProcessMemoryUsageSnapshot,
  7. } from "../src/process-resource-sampler.js";
  8. const memoryUsage: ProcessMemoryUsageSnapshot = {
  9. rss: 64 * 1024 * 1024,
  10. heapTotal: 32 * 1024 * 1024,
  11. heapUsed: 20 * 1024 * 1024,
  12. external: 4 * 1024 * 1024,
  13. arrayBuffers: 1024 * 1024,
  14. };
  15. describe("createZCodeProcessResourceSampler", () => {
  16. it("每 60 秒按差分计算 CPU 核心数、整机百分比和 RSS,并把完整内存快照作为第二参数交给 onSample", () => {
  17. const onSample = vi.fn();
  18. const unref = vi.fn();
  19. let scheduled: (() => void) | undefined;
  20. const cpuSnapshots = [
  21. { user: 0, system: 0 },
  22. { user: 2_000_000, system: 500_000 },
  23. ];
  24. const monotonicSnapshots = [0n, 1_000_000_000n];
  25. const sampler = createZCodeProcessResourceSampler({
  26. arch: "arm64",
  27. logicalCpuCount: 8,
  28. onSample,
  29. platform: "darwin",
  30. readCpuUsage: () => cpuSnapshots.shift()!,
  31. readMonotonicTimeNs: () => monotonicSnapshots.shift()!,
  32. readMemoryUsage: () => memoryUsage,
  33. readTotalMemoryBytes: () => 16 * 1024 ** 3,
  34. readUptimeSeconds: () => 12 * 60 + 20,
  35. instanceToken: "test-instance-token",
  36. timer: {
  37. clearInterval: vi.fn(),
  38. setInterval(callback, intervalMs) {
  39. expect(intervalMs).toBe(ZCODE_PROCESS_RESOURCE_SAMPLE_INTERVAL_MS);
  40. scheduled = callback;
  41. return { unref };
  42. },
  43. },
  44. });
  45. sampler.start();
  46. expect(unref).toHaveBeenCalledOnce();
  47. scheduled?.();
  48. // 05:同一次读数除 rss 外还给出 heap、运行时长与运行机内存,供 main 的 cli 角色事件使用;
  49. // heap 细分仍经第二参数进入本地诊断日志。
  50. expect(onSample).toHaveBeenCalledOnce();
  51. expect(onSample.mock.calls[0]?.[0]).toEqual({
  52. arch: "arm64",
  53. cpuCores: 2.5,
  54. cpuPercent: 31.25,
  55. heapUsedKb: 20_480,
  56. instanceToken: "test-instance-token",
  57. intervalMs: 1_000,
  58. logicalCpuCount: 8,
  59. platform: "darwin",
  60. rssKb: 65_536,
  61. totalMemoryGb: 16,
  62. uptimeMinutes: 12,
  63. });
  64. expect(onSample.mock.calls[0]?.[1]).toBe(memoryUsage);
  65. // CLI 是协议样本的生产方:样本必须直接通过协议 schema,否则 services 侧会整条丢弃。
  66. expect(() => zcodeProcessResourceSampleSchema.parse(onSample.mock.calls[0]?.[0])).not.toThrow();
  67. });
  68. it("随机 instanceToken 在采样期间保持不变,且只含 URL 安全字符", () => {
  69. const onSample = vi.fn();
  70. let scheduled: (() => void) | undefined;
  71. const cpuSnapshots = [
  72. { user: 0, system: 0 },
  73. { user: 1_000_000, system: 0 },
  74. { user: 2_000_000, system: 0 },
  75. ];
  76. const monotonicSnapshots = [0n, 1_000_000_000n, 2_000_000_000n];
  77. const sampler = createZCodeProcessResourceSampler({
  78. arch: "x64",
  79. logicalCpuCount: 4,
  80. onSample,
  81. platform: "linux",
  82. readCpuUsage: () => cpuSnapshots.shift()!,
  83. readMonotonicTimeNs: () => monotonicSnapshots.shift()!,
  84. readMemoryUsage: () => memoryUsage,
  85. timer: {
  86. clearInterval: vi.fn(),
  87. setInterval(callback) {
  88. scheduled = callback;
  89. return { unref: vi.fn() };
  90. },
  91. },
  92. });
  93. sampler.start();
  94. scheduled?.();
  95. scheduled?.();
  96. const tokens = onSample.mock.calls.map(
  97. (call) => (call[0] as { instanceToken?: string }).instanceToken,
  98. );
  99. expect(tokens).toHaveLength(2);
  100. expect(tokens[0]).toBe(tokens[1]);
  101. // 校验随机 token 的协议字符集。
  102. expect(tokens[0]).toMatch(/^[A-Za-z0-9_-]{8,64}$/);
  103. });
  104. it("采集或上报异常只丢当前样本,后续周期仍可继续", () => {
  105. const onSample = vi
  106. .fn()
  107. .mockImplementationOnce(() => {
  108. throw new Error("transport closed");
  109. })
  110. .mockImplementation(() => undefined);
  111. let scheduled: (() => void) | undefined;
  112. const cpuSnapshots = [
  113. { user: 0, system: 0 },
  114. { user: 1_000_000, system: 0 },
  115. new Error("cpu unavailable"),
  116. { user: 3_000_000, system: 0 },
  117. ];
  118. const monotonicSnapshots = [0n, 1_000_000_000n, 3_000_000_000n];
  119. const sampler = createZCodeProcessResourceSampler({
  120. arch: "x64",
  121. logicalCpuCount: 4,
  122. onSample,
  123. platform: "linux",
  124. readCpuUsage: () => {
  125. const next = cpuSnapshots.shift()!;
  126. if (next instanceof Error) throw next;
  127. return next;
  128. },
  129. readMonotonicTimeNs: () => monotonicSnapshots.shift()!,
  130. readMemoryUsage: () => ({ ...memoryUsage, rss: 1024 }),
  131. timer: {
  132. clearInterval: vi.fn(),
  133. setInterval(callback) {
  134. scheduled = callback;
  135. return { unref: vi.fn() };
  136. },
  137. },
  138. });
  139. sampler.start();
  140. expect(() => scheduled?.()).not.toThrow();
  141. expect(() => scheduled?.()).not.toThrow();
  142. expect(() => scheduled?.()).not.toThrow();
  143. expect(onSample).toHaveBeenCalledTimes(2);
  144. expect(onSample.mock.calls[1]?.[0]).toMatchObject({
  145. cpuCores: 1,
  146. cpuPercent: 25,
  147. intervalMs: 2_000,
  148. });
  149. });
  150. it("readMemoryUsage 抛错时跳过当前周期且不抛出", () => {
  151. const onSample = vi.fn();
  152. let scheduled: (() => void) | undefined;
  153. const monotonicSnapshots = [0n, 1_000_000_000n];
  154. const sampler = createZCodeProcessResourceSampler({
  155. arch: "x64",
  156. logicalCpuCount: 4,
  157. onSample,
  158. platform: "linux",
  159. readCpuUsage: () => ({ user: 0, system: 0 }),
  160. readMonotonicTimeNs: () => monotonicSnapshots.shift()!,
  161. readMemoryUsage: () => {
  162. throw new Error("memoryUsage unavailable");
  163. },
  164. timer: {
  165. clearInterval: vi.fn(),
  166. setInterval(callback) {
  167. scheduled = callback;
  168. return { unref: vi.fn() };
  169. },
  170. },
  171. });
  172. sampler.start();
  173. expect(() => scheduled?.()).not.toThrow();
  174. expect(onSample).not.toHaveBeenCalled();
  175. });
  176. it("只创建一个 unref timer,stop 可幂等释放且不延长 CLI 生命周期", () => {
  177. const clearInterval = vi.fn();
  178. const handle = { unref: vi.fn() };
  179. const setInterval = vi.fn(() => handle);
  180. const sampler = createZCodeProcessResourceSampler({
  181. arch: "x64",
  182. logicalCpuCount: 1,
  183. onSample: vi.fn(),
  184. platform: "win32",
  185. readCpuUsage: () => ({ user: 0, system: 0 }),
  186. readMonotonicTimeNs: () => 0n,
  187. readMemoryUsage: () => memoryUsage,
  188. timer: { clearInterval, setInterval },
  189. });
  190. sampler.start();
  191. sampler.start();
  192. sampler.stop();
  193. sampler.stop();
  194. expect(setInterval).toHaveBeenCalledOnce();
  195. expect(handle.unref).toHaveBeenCalledOnce();
  196. expect(clearInterval).toHaveBeenCalledOnce();
  197. expect(clearInterval).toHaveBeenCalledWith(handle);
  198. });
  199. it("unref 自身异常时仍保留 timer owner,stop 可以回收", () => {
  200. const handle = {
  201. unref() {
  202. throw new Error("unref unavailable");
  203. },
  204. };
  205. const clearInterval = vi.fn();
  206. const sampler = createZCodeProcessResourceSampler({
  207. arch: "x64",
  208. logicalCpuCount: 1,
  209. onSample: vi.fn(),
  210. platform: "linux",
  211. readCpuUsage: () => ({ user: 0, system: 0 }),
  212. readMonotonicTimeNs: () => 0n,
  213. readMemoryUsage: () => memoryUsage,
  214. timer: {
  215. clearInterval,
  216. setInterval: () => handle,
  217. },
  218. });
  219. expect(() => sampler.start()).not.toThrow();
  220. sampler.stop();
  221. expect(clearInterval).toHaveBeenCalledWith(handle);
  222. });
  223. });