storageAdapters.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  2. import { chmod, mkdir, mkdtemp, rm, symlink, utimes, writeFile } from "node:fs/promises";
  3. import { existsSync } from "node:fs";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { walkStorageRoot } from "../src/storage/adapters/fsWalker.js";
  7. import { probeStorageVolume } from "../src/storage/adapters/volumeProbe.js";
  8. import { createFsStorageCleaner } from "../src/storage/adapters/fsCleaner.js";
  9. import { runStorageScan } from "../src/storage/adapters/inProcessScanRunner.js";
  10. import type { StorageScanEntry } from "../src/storage/domain/usageAggregate.js";
  11. let root: string;
  12. async function seed(files: Record<string, string>): Promise<void> {
  13. for (const [path, content] of Object.entries(files)) {
  14. await mkdir(join(root, path, ".."), { recursive: true });
  15. await writeFile(join(root, path), content);
  16. }
  17. }
  18. beforeEach(async () => {
  19. root = await mkdtemp(join(tmpdir(), "zcode-storage-"));
  20. });
  21. afterEach(async () => {
  22. await rm(root, { recursive: true, force: true });
  23. });
  24. describe("walkStorageRoot", () => {
  25. it("reports every regular file with size and mtime", async () => {
  26. await seed({ "cli/debug/a.jsonl": "12345", "v2/logs/b.log": "12", "top.txt": "1" });
  27. const entries: StorageScanEntry[] = [];
  28. const result = await walkStorageRoot({
  29. rootPath: root,
  30. onEntry: (e) => entries.push(e),
  31. concurrency: 2,
  32. });
  33. expect(entries.map((e) => [e.relativePath, e.bytes]).sort()).toEqual([
  34. ["cli/debug/a.jsonl", 5],
  35. ["top.txt", 1],
  36. ["v2/logs/b.log", 2],
  37. ]);
  38. expect(entries.every((e) => e.mtimeMs > 0)).toBe(true);
  39. expect(result).toMatchObject({ filesScanned: 3, missingRoot: false });
  40. expect(result.directoriesScanned).toBe(5);
  41. });
  42. // Windows 普通用户无 SeCreateSymbolicLinkPrivilege(开发者模式才赋予),fs.symlink 直接
  43. // EPERM;普通文件扫描已拆到上一条跨平台用例,这里只验证链接目录不被递归,
  44. // skipped 在报告里可见,覆盖由 CI Linux 承担。
  45. it.skipIf(process.platform === "win32")(
  46. "skips symlinked directories instead of recursing into them",
  47. async () => {
  48. await seed({ "cli/debug/a.jsonl": "12345", "v2/logs/b.log": "12", "top.txt": "1" });
  49. await symlink(join(root, "cli"), join(root, "link-to-cli"));
  50. const entries: StorageScanEntry[] = [];
  51. const result = await walkStorageRoot({
  52. rootPath: root,
  53. onEntry: (e) => entries.push(e),
  54. concurrency: 2,
  55. });
  56. // 链接目录不得被递归:目标内容不得重复出现,目录计数也不把它算作被扫描的目录。
  57. expect(entries.map((e) => [e.relativePath, e.bytes]).sort()).toEqual([
  58. ["cli/debug/a.jsonl", 5],
  59. ["top.txt", 1],
  60. ["v2/logs/b.log", 2],
  61. ]);
  62. expect(result).toMatchObject({ filesScanned: 3, missingRoot: false });
  63. expect(result.directoriesScanned).toBe(5);
  64. },
  65. );
  66. it("treats a missing root as empty and collects unreadable directories as errors", async () => {
  67. const missing = await walkStorageRoot({ rootPath: join(root, "nope"), onEntry: () => {} });
  68. expect(missing).toEqual({ directoriesScanned: 0, filesScanned: 0, missingRoot: true });
  69. if (process.platform === "win32" || process.getuid?.() === 0) return;
  70. await seed({ "locked/x": "1", "open/y": "1" });
  71. await chmod(join(root, "locked"), 0o000);
  72. const errors: Array<{ path: string; code: string }> = [];
  73. try {
  74. const result = await walkStorageRoot({
  75. rootPath: root,
  76. onEntry: () => {},
  77. onError: (e) => errors.push(e),
  78. });
  79. expect(result.filesScanned).toBe(1);
  80. expect(errors).toEqual([{ path: "locked", code: "EACCES" }]);
  81. } finally {
  82. await chmod(join(root, "locked"), 0o755);
  83. }
  84. });
  85. it("stops promptly when aborted", async () => {
  86. await seed(Object.fromEntries(Array.from({ length: 50 }, (_, i) => [`d${i % 5}/f${i}`, "x"])));
  87. const controller = new AbortController();
  88. let seen = 0;
  89. await expect(
  90. walkStorageRoot({
  91. rootPath: root,
  92. yieldEvery: 1,
  93. onEntry: () => {
  94. seen += 1;
  95. if (seen === 3) controller.abort();
  96. },
  97. signal: controller.signal,
  98. }),
  99. ).rejects.toMatchObject({ name: "AbortError" });
  100. expect(seen).toBeLessThan(50);
  101. });
  102. });
  103. describe("probeStorageVolume", () => {
  104. it("returns the volume of an existing path and null for a missing one", async () => {
  105. const volume = await probeStorageVolume(root);
  106. expect(volume).not.toBeNull();
  107. expect(volume!.totalBytes).toBeGreaterThan(0);
  108. expect(volume!.freeBytes).toBeGreaterThanOrEqual(0);
  109. expect(root.startsWith(volume!.mountPoint)).toBe(true);
  110. expect(await probeStorageVolume(join(root, "missing"))).toBeNull();
  111. });
  112. });
  113. describe("createFsStorageCleaner", () => {
  114. it("lists recursive and shallow scopes without duplicates", async () => {
  115. await seed({
  116. "cli/db/db.sqlite": "live",
  117. "cli/db/db.sqlite.bak-1": "bak",
  118. "cli/db/backup/db.pre.sqlite": "old",
  119. "cli/db/backup/nested/x": "old",
  120. });
  121. const cleaner = createFsStorageCleaner();
  122. const candidates = await cleaner.listCandidates(root, [
  123. { prefix: "cli/db/backup", recursive: true },
  124. { prefix: "cli/db", recursive: false },
  125. { prefix: "does-not-exist", recursive: true },
  126. { prefix: "nor-this", recursive: false },
  127. ]);
  128. expect(candidates.map((c) => c.relativePath).sort()).toEqual([
  129. "cli/db/backup/db.pre.sqlite",
  130. "cli/db/backup/nested/x",
  131. "cli/db/db.sqlite",
  132. "cli/db/db.sqlite.bak-1",
  133. ]);
  134. });
  135. it("deletes targets, prunes emptied directories below kept ones and reports failures", async () => {
  136. await seed({ "backup/one/deep/x": "1234", "backup/one/keep": "1", "cli/debug/a.jsonl": "12" });
  137. const cleaner = createFsStorageCleaner();
  138. const result = await cleaner.deleteFiles(
  139. root,
  140. [
  141. { relativePath: "backup/one/deep/x", bytes: 4, mtimeMs: 0 },
  142. { relativePath: "cli/debug/a.jsonl", bytes: 2, mtimeMs: 0 },
  143. { relativePath: "cli/debug/missing.jsonl", bytes: 9, mtimeMs: 0 },
  144. { relativePath: "../outside", bytes: 1, mtimeMs: 0 },
  145. ],
  146. { keepDirectories: ["backup", "cli/debug"] },
  147. );
  148. // 删除是有界并发的,failures 顺序不保证
  149. expect({
  150. ...result,
  151. failures: [...result.failures].sort((a, b) => a.path.localeCompare(b.path)),
  152. }).toEqual({
  153. deletedCount: 2,
  154. freedBytes: 6,
  155. failures: [
  156. { path: "../outside", code: "EOUTSIDE" },
  157. { path: "cli/debug/missing.jsonl", code: "ENOENT" },
  158. ],
  159. });
  160. expect(existsSync(join(root, "backup/one/deep"))).toBe(false);
  161. expect(existsSync(join(root, "backup/one/keep"))).toBe(true);
  162. expect(existsSync(join(root, "cli/debug"))).toBe(true);
  163. expect(existsSync(join(root, "cli/debug/a.jsonl"))).toBe(false);
  164. });
  165. });
  166. describe("runStorageScan", () => {
  167. it("classifies real files per root and reports progress plus a final result", async () => {
  168. await seed({
  169. "cli/debug/model-io-a.jsonl": "12345",
  170. "v2/logs/2026-09-01.log": "123",
  171. "junk/x": "1",
  172. });
  173. const custom = await mkdtemp(join(tmpdir(), "zcode-storage-custom-"));
  174. await mkdir(join(custom, "v2/logs"), { recursive: true });
  175. await writeFile(join(custom, "v2/logs/a.log"), "1234");
  176. await utimes(join(custom, "v2/logs/a.log"), new Date(), new Date());
  177. const progress: number[] = [];
  178. try {
  179. const result = await runStorageScan({
  180. progressIntervalMs: 0,
  181. roots: [
  182. { id: "home", path: root, hasCustomDataBaseDir: true },
  183. { id: "dataBaseDir", path: custom, hasCustomDataBaseDir: true },
  184. ],
  185. signal: new AbortController().signal,
  186. onProgress: (p) => progress.push(p.roots.length),
  187. });
  188. expect(progress.length).toBeGreaterThan(1);
  189. expect(progress.at(-1)).toBe(2);
  190. const [home, dataBaseDir] = result.roots;
  191. expect(home!.bytes).toBe(9);
  192. expect(home!.volume).not.toBeNull();
  193. const byId = (usage: typeof home, id: string) => usage!.categories.find((c) => c.id === id)!;
  194. expect(byId(home, "modelTrajectory")).toMatchObject({ bytes: 5, fileCount: 1 });
  195. // home 根启用了自定义数据路径:v2 旧副本归「其他」
  196. expect(byId(home, "logs").bytes).toBe(0);
  197. expect(byId(home, "other")).toMatchObject({ bytes: 4, fileCount: 2 });
  198. expect(byId(dataBaseDir, "logs")).toMatchObject({ bytes: 4, fileCount: 1 });
  199. expect(result.errors).toEqual([]);
  200. } finally {
  201. await rm(custom, { recursive: true, force: true });
  202. }
  203. });
  204. });