desktopCrashCapture.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import { access, mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import {
  6. archiveCrashDumps,
  7. resolveProcessGoneLogLevel,
  8. resolveCrashReporterSourceDirs,
  9. type CrashCapturePaths,
  10. } from "../src/main/desktopCrashCapture.js";
  11. import { buildCrashDumpFixture, CODE_SPACE_OOM_ANNOTATIONS } from "./crashDumpFixture.js";
  12. describe("desktopCrashCapture", () => {
  13. const tempDirs: string[] = [];
  14. afterEach(async () => {
  15. await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
  16. });
  17. it("受控进程退出使用 info,未分类的异常退出使用 warn", () => {
  18. expect(resolveProcessGoneLogLevel("clean-exit")).toBe("info");
  19. expect(resolveProcessGoneLogLevel("killed")).toBe("info");
  20. expect(resolveProcessGoneLogLevel("crashed")).toBe("warn");
  21. expect(resolveProcessGoneLogLevel("oom")).toBe("warn");
  22. });
  23. async function createPaths(platform: NodeJS.Platform): Promise<CrashCapturePaths> {
  24. const rootDir = await mkdtemp(join(tmpdir(), "zcode-crash-capture-"));
  25. tempDirs.push(rootDir);
  26. const paths: CrashCapturePaths = {
  27. rootDir,
  28. stagingDir: join(rootDir, "live"),
  29. archiveDir: join(rootDir, "archive"),
  30. };
  31. await mkdir(paths.archiveDir, { recursive: true });
  32. for (const dir of resolveCrashReporterSourceDirs(paths.stagingDir, platform)) {
  33. await mkdir(dir, { recursive: true });
  34. }
  35. return paths;
  36. }
  37. it("应归档已稳定的 crash dump,并忽略非 dmp 文件", async () => {
  38. const paths = await createPaths("linux");
  39. const completedDir = resolveCrashReporterSourceDirs(paths.stagingDir, "linux")[0];
  40. const dumpPath = join(completedDir, "renderer-1.dmp");
  41. const ignoredPath = join(completedDir, "note.txt");
  42. await writeFile(dumpPath, "dump-a");
  43. await writeFile(ignoredPath, "ignore");
  44. const oldDate = new Date(Date.now() - 5_000);
  45. await utimes(dumpPath, oldDate, oldDate);
  46. const result = archiveCrashDumps(paths, { platform: "linux" });
  47. expect(result.archivedFiles).toEqual([dumpPath]);
  48. expect(result.skippedFiles).toEqual([]);
  49. await expect(readFile(join(paths.archiveDir, "renderer-1.dmp"), "utf-8")).resolves.toBe(
  50. "dump-a",
  51. );
  52. });
  53. it("归档时解析 crashpad 注解,把 V8 OOM 摘要写进 .dmp.json 并返回给调用方", async () => {
  54. const paths = await createPaths("linux");
  55. const completedDir = resolveCrashReporterSourceDirs(paths.stagingDir, "linux")[0];
  56. const oomDumpPath = join(completedDir, "renderer-oom.dmp");
  57. const nativeDumpPath = join(completedDir, "gpu-native.dmp");
  58. await writeFile(oomDumpPath, buildCrashDumpFixture(CODE_SPACE_OOM_ANNOTATIONS));
  59. await writeFile(nativeDumpPath, buildCrashDumpFixture({ process_type: "gpu-process" }));
  60. const oldDate = new Date(Date.now() - 5_000);
  61. await utimes(oomDumpPath, oldDate, oldDate);
  62. await utimes(nativeDumpPath, oldDate, oldDate);
  63. const result = archiveCrashDumps(paths, { platform: "linux" });
  64. expect(result.archivedDumps.map((record) => record.dumpPath).sort()).toEqual(
  65. [nativeDumpPath, oomDumpPath].sort(),
  66. );
  67. const oomRecord = result.archivedDumps.find((record) => record.dumpPath === oomDumpPath);
  68. expect(oomRecord?.v8OomSummary).toMatchObject({
  69. processType: "renderer",
  70. oomKind: "code_space_exhausted",
  71. codeCageFreeBytes: 0,
  72. });
  73. const nativeRecord = result.archivedDumps.find((record) => record.dumpPath === nativeDumpPath);
  74. expect(nativeRecord?.v8OomSummary).toBeNull();
  75. const oomMetadata = JSON.parse(
  76. await readFile(join(paths.archiveDir, "renderer-oom.dmp.json"), "utf-8"),
  77. ) as Record<string, unknown>;
  78. expect(oomMetadata.originalPath).toBe(oomDumpPath);
  79. expect(oomMetadata.annotations).toEqual(CODE_SPACE_OOM_ANNOTATIONS);
  80. expect(oomMetadata.v8OomSummary).toMatchObject({ oomKind: "code_space_exhausted" });
  81. const nativeMetadata = JSON.parse(
  82. await readFile(join(paths.archiveDir, "gpu-native.dmp.json"), "utf-8"),
  83. ) as Record<string, unknown>;
  84. expect(nativeMetadata.annotations).toEqual({ process_type: "gpu-process" });
  85. expect(nativeMetadata).not.toHaveProperty("v8OomSummary");
  86. });
  87. it("应跳过仍在写入窗口内的 crash dump", async () => {
  88. const paths = await createPaths("darwin");
  89. const pendingDir = resolveCrashReporterSourceDirs(paths.stagingDir, "darwin")[1];
  90. const dumpPath = join(pendingDir, "renderer-2.dmp");
  91. await writeFile(dumpPath, "dump-b");
  92. const result = archiveCrashDumps(paths, {
  93. platform: "darwin",
  94. now: new Date(),
  95. });
  96. expect(result.archivedFiles).toEqual([]);
  97. expect(result.skippedFiles).toEqual([dumpPath]);
  98. });
  99. it("默认最多保留最近 5 个归档", async () => {
  100. const paths = await createPaths("linux");
  101. const dumpPaths = Array.from({ length: 6 }, (_, index) =>
  102. join(paths.archiveDir, `renderer-${index}.dmp`),
  103. );
  104. await Promise.all(dumpPaths.map((path) => writeFile(path, "dump")));
  105. await Promise.all(
  106. dumpPaths.map((path, index) => {
  107. const modifiedAt = new Date(`2026-08-0${index + 1}T00:00:00.000Z`);
  108. return utimes(path, modifiedAt, modifiedAt);
  109. }),
  110. );
  111. archiveCrashDumps(paths, { platform: "linux" });
  112. expect((await readdir(paths.archiveDir)).sort()).toEqual([
  113. "renderer-1.dmp",
  114. "renderer-2.dmp",
  115. "renderer-3.dmp",
  116. "renderer-4.dmp",
  117. "renderer-5.dmp",
  118. ]);
  119. });
  120. it("恢复残留 dump 时应按原始 crash 时间保留较新的归档", async () => {
  121. const paths = await createPaths("linux");
  122. const completedDir = resolveCrashReporterSourceDirs(paths.stagingDir, "linux")[0];
  123. const olderSourceDumpPath = join(completedDir, "older-source.dmp");
  124. const newerArchivedDumpPath = join(paths.archiveDir, "newer-archive.dmp");
  125. const now = new Date();
  126. const olderCrashAt = new Date(now.getTime() - 60_000);
  127. const newerCrashAt = new Date(now.getTime() - 30_000);
  128. await Promise.all([
  129. writeFile(olderSourceDumpPath, "older-source"),
  130. writeFile(newerArchivedDumpPath, "newer-archive"),
  131. ]);
  132. await Promise.all([
  133. utimes(olderSourceDumpPath, olderCrashAt, olderCrashAt),
  134. utimes(newerArchivedDumpPath, newerCrashAt, newerCrashAt),
  135. ]);
  136. archiveCrashDumps(paths, {
  137. platform: "linux",
  138. now,
  139. retention: { maxFiles: 1, maxTotalBytes: 100 },
  140. });
  141. expect(await readdir(paths.archiveDir)).toEqual(["newer-archive.dmp"]);
  142. });
  143. it("归档数量超限时删除最旧 dump 及其元数据,并保留 live 与其他文件", async () => {
  144. const paths = await createPaths("linux");
  145. const completedDir = resolveCrashReporterSourceDirs(paths.stagingDir, "linux")[0];
  146. const sourceDumpPath = join(completedDir, "latest.dmp");
  147. const oldestDumpPath = join(paths.archiveDir, "oldest.dmp");
  148. const newerDumpPath = join(paths.archiveDir, "newer.dmp");
  149. const oldestMetadataPath = `${oldestDumpPath}.json`;
  150. const unrelatedPath = join(paths.archiveDir, "keep.txt");
  151. const now = new Date("2026-08-03T12:00:00.000Z");
  152. await Promise.all([
  153. writeFile(sourceDumpPath, "latest"),
  154. writeFile(oldestDumpPath, "oldest"),
  155. writeFile(newerDumpPath, "newer"),
  156. writeFile(oldestMetadataPath, "{}"),
  157. writeFile(unrelatedPath, "keep"),
  158. ]);
  159. await Promise.all([
  160. utimes(sourceDumpPath, new Date(now.getTime() - 5_000), new Date(now.getTime() - 5_000)),
  161. utimes(
  162. oldestDumpPath,
  163. new Date("2026-07-01T00:00:00.000Z"),
  164. new Date("2026-07-01T00:00:00.000Z"),
  165. ),
  166. utimes(
  167. newerDumpPath,
  168. new Date("2026-07-02T00:00:00.000Z"),
  169. new Date("2026-07-02T00:00:00.000Z"),
  170. ),
  171. ]);
  172. archiveCrashDumps(paths, {
  173. platform: "linux",
  174. now,
  175. retention: { maxFiles: 2, maxTotalBytes: 100 },
  176. });
  177. expect((await readdir(paths.archiveDir)).sort()).toEqual([
  178. "keep.txt",
  179. "latest.dmp",
  180. "latest.dmp.json",
  181. "newer.dmp",
  182. ]);
  183. await expect(access(sourceDumpPath)).resolves.toBeUndefined();
  184. });
  185. it("归档总大小超限时仍保留最新 dump,并删除更旧文件", async () => {
  186. const paths = await createPaths("linux");
  187. const latestDumpPath = join(paths.archiveDir, "latest-large.dmp");
  188. const olderDumpPath = join(paths.archiveDir, "older.dmp");
  189. await Promise.all([
  190. writeFile(latestDumpPath, "latest-large"),
  191. writeFile(`${latestDumpPath}.json`, "{}"),
  192. writeFile(olderDumpPath, "older"),
  193. writeFile(`${olderDumpPath}.json`, "{}"),
  194. ]);
  195. await Promise.all([
  196. utimes(
  197. latestDumpPath,
  198. new Date("2026-08-03T00:00:00.000Z"),
  199. new Date("2026-08-03T00:00:00.000Z"),
  200. ),
  201. utimes(
  202. olderDumpPath,
  203. new Date("2026-08-02T00:00:00.000Z"),
  204. new Date("2026-08-02T00:00:00.000Z"),
  205. ),
  206. ]);
  207. archiveCrashDumps(paths, {
  208. platform: "linux",
  209. retention: { maxFiles: 5, maxTotalBytes: 10 },
  210. });
  211. expect((await readdir(paths.archiveDir)).sort()).toEqual([
  212. "latest-large.dmp",
  213. "latest-large.dmp.json",
  214. ]);
  215. });
  216. it("清理只处理普通 dmp 文件,不被同后缀目录阻断", async () => {
  217. const paths = await createPaths("win32");
  218. const dumpDirectory = join(paths.archiveDir, "not-a-file.dmp");
  219. const latestDumpPath = join(paths.archiveDir, "latest.dmp");
  220. await Promise.all([mkdir(dumpDirectory), writeFile(latestDumpPath, "latest")]);
  221. expect(() =>
  222. archiveCrashDumps(paths, {
  223. platform: "win32",
  224. retention: { maxFiles: 1, maxTotalBytes: 100 },
  225. }),
  226. ).not.toThrow();
  227. await expect(access(dumpDirectory)).resolves.toBeUndefined();
  228. await expect(access(latestDumpPath)).resolves.toBeUndefined();
  229. });
  230. it("旧 dump 元数据删除失败后应在后续清理重试,并保留其他 JSON 文件", async () => {
  231. const paths = await createPaths("linux");
  232. const latestDumpPath = join(paths.archiveDir, "latest.dmp");
  233. const oldDumpPath = join(paths.archiveDir, "old.dmp");
  234. const invalidMetadataPath = `${oldDumpPath}.json`;
  235. const unrelatedJsonPath = join(paths.archiveDir, "keep.json");
  236. await Promise.all([
  237. writeFile(latestDumpPath, "latest"),
  238. writeFile(oldDumpPath, "old"),
  239. mkdir(invalidMetadataPath),
  240. writeFile(unrelatedJsonPath, "{}"),
  241. ]);
  242. await Promise.all([
  243. utimes(
  244. latestDumpPath,
  245. new Date("2026-08-03T00:00:00.000Z"),
  246. new Date("2026-08-03T00:00:00.000Z"),
  247. ),
  248. utimes(
  249. oldDumpPath,
  250. new Date("2026-08-02T00:00:00.000Z"),
  251. new Date("2026-08-02T00:00:00.000Z"),
  252. ),
  253. ]);
  254. const result = archiveCrashDumps(paths, {
  255. platform: "linux",
  256. retention: { maxFiles: 1, maxTotalBytes: 100 },
  257. });
  258. expect(result.failedArchiveFiles).toEqual([invalidMetadataPath]);
  259. await expect(access(oldDumpPath)).rejects.toMatchObject({ code: "ENOENT" });
  260. await expect(access(invalidMetadataPath)).resolves.toBeUndefined();
  261. await rm(invalidMetadataPath, { recursive: true });
  262. await writeFile(invalidMetadataPath, '{"originalPath":"/Users/example/live/old.dmp"}');
  263. const retryResult = archiveCrashDumps(paths, {
  264. platform: "linux",
  265. retention: { maxFiles: 1, maxTotalBytes: 100 },
  266. });
  267. expect(retryResult.deletedArchiveFiles).toEqual([invalidMetadataPath]);
  268. await expect(access(invalidMetadataPath)).rejects.toMatchObject({ code: "ENOENT" });
  269. await expect(access(unrelatedJsonPath)).resolves.toBeUndefined();
  270. });
  271. });