workflowArtifactFile.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // dwf 产物「作为文件打开」的宿主副本(docs/dynamic-workflow/authoring.md「How the user sees them」)。
  2. //
  3. // ⚠ 术语:artifact = 脚本经 `artifact.*` 发布给用户看的产出,不是引擎的 `RunSettlement.artifact`。
  4. //
  5. // 钉四件事:
  6. // 1. 落点:~/.zcode/tmp/workflow-artifacts/<runId>-<digest>/<artifactId>-<digest>/v<N>/<name>,一版一份;
  7. // 2. 只在路径为空时写——一版的字节永不变,已有副本要么同字节要么是用户自己的编辑,都保留;
  8. // 3. 渲染器给的每个路径片段都清洗过,写不出这个目录;
  9. // 4. 形状与上限(20 MiB,同 `artifact.file`)在宿主侧再校验一次。
  10. import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
  11. import { tmpdir } from "node:os";
  12. import { createHash } from "node:crypto";
  13. import { dirname, join, relative, sep } from "node:path";
  14. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  15. import { setDataBaseDir } from "@zcode/services/node";
  16. import {
  17. WORKFLOW_ARTIFACT_FILE_MAX_BYTES,
  18. materializeWorkflowArtifactFile,
  19. } from "../src/main/workflowArtifactFile.js";
  20. let tempRoot = "";
  21. function artifactsRoot(): string {
  22. return join(tempRoot, ".zcode", "tmp", "workflow-artifacts");
  23. }
  24. /** run / 产物目录名:清洗后的 id 加原始 id 的 sha256 前 8 位(与实现同一规则)。 */
  25. function segmentDir(id: string): string {
  26. return `${id}-${createHash("sha256").update(id, "utf8").digest("hex").slice(0, 8)}`;
  27. }
  28. function bytesOf(text: string): Uint8Array {
  29. return new TextEncoder().encode(text);
  30. }
  31. beforeEach(async () => {
  32. tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-artifact-file-"));
  33. setDataBaseDir(tempRoot);
  34. });
  35. afterEach(async () => {
  36. setDataBaseDir(null);
  37. await rm(tempRoot, { recursive: true, force: true });
  38. });
  39. describe("materializeWorkflowArtifactFile", () => {
  40. it("按 run / 产物 / 版本分目录写出这一版的字节", async () => {
  41. const result = await materializeWorkflowArtifactFile({
  42. runId: "dwfrun-1",
  43. artifactId: "report",
  44. version: 2,
  45. fileName: "report.md",
  46. bytes: bytesOf("# v2"),
  47. });
  48. expect(result.localPath).toBe(
  49. join(artifactsRoot(), segmentDir("dwfrun-1"), segmentDir("report"), "v2", "report.md"),
  50. );
  51. await expect(readFile(result.localPath, "utf8")).resolves.toBe("# v2");
  52. });
  53. it("路径已有文件时不覆盖:用户在外部编辑过的副本保留,再次打开还是同一个文件", async () => {
  54. const request = {
  55. runId: "dwfrun-1",
  56. artifactId: "report",
  57. version: 1,
  58. fileName: "report.md",
  59. bytes: bytesOf("# published"),
  60. };
  61. const first = await materializeWorkflowArtifactFile(request);
  62. await writeFile(first.localPath, "# edited by the user");
  63. const second = await materializeWorkflowArtifactFile(request);
  64. expect(second.localPath).toBe(first.localPath);
  65. await expect(readFile(second.localPath, "utf8")).resolves.toBe("# edited by the user");
  66. });
  67. it("同一版并发两次:两边拿到同一个路径,文件是完整的一份,不留临时文件", async () => {
  68. const request = {
  69. runId: "dwfrun-1",
  70. artifactId: "book",
  71. version: 1,
  72. fileName: "book.pdf",
  73. bytes: bytesOf("%PDF-1.7 whole"),
  74. };
  75. const [a, b] = await Promise.all([
  76. materializeWorkflowArtifactFile(request),
  77. materializeWorkflowArtifactFile(request),
  78. ]);
  79. expect(a.localPath).toBe(b.localPath);
  80. await expect(readFile(a.localPath, "utf8")).resolves.toBe("%PDF-1.7 whole");
  81. await expect(readdir(dirname(a.localPath))).resolves.toEqual(["book.pdf"]);
  82. });
  83. it("不同版本各落一份,互不覆盖", async () => {
  84. const v1 = await materializeWorkflowArtifactFile({
  85. runId: "dwfrun-1",
  86. artifactId: "report",
  87. version: 1,
  88. fileName: "report.md",
  89. bytes: bytesOf("one"),
  90. });
  91. const v2 = await materializeWorkflowArtifactFile({
  92. runId: "dwfrun-1",
  93. artifactId: "report",
  94. version: 2,
  95. fileName: "report.md",
  96. bytes: bytesOf("two"),
  97. });
  98. expect(v1.localPath).not.toBe(v2.localPath);
  99. await expect(readFile(v1.localPath, "utf8")).resolves.toBe("one");
  100. await expect(readFile(v2.localPath, "utf8")).resolves.toBe("two");
  101. });
  102. it("渲染器给的路径片段一律清洗:写不出 workflow-artifacts 目录", async () => {
  103. const result = await materializeWorkflowArtifactFile({
  104. runId: "../../escape",
  105. artifactId: "..",
  106. version: 1,
  107. fileName: "../../../etc/evil.md",
  108. bytes: bytesOf("x"),
  109. });
  110. expect(result.localPath.startsWith(artifactsRoot() + sep)).toBe(true);
  111. const segments = relative(artifactsRoot(), result.localPath).split(sep);
  112. expect(segments).toHaveLength(4);
  113. // 没有一个片段是 `.` / `..`,也没有隐藏目录。
  114. expect(segments.every((segment) => !segment.startsWith("."))).toBe(true);
  115. expect(segments.at(-1)).toBe("evil.md");
  116. });
  117. it("文件名保留 Unicode 与扩展名,只替换各平台的非法字符", async () => {
  118. const result = await materializeWorkflowArtifactFile({
  119. runId: "dwfrun-1",
  120. artifactId: "sheet",
  121. version: 1,
  122. fileName: "季度:报告<草稿>?.xlsx",
  123. bytes: bytesOf("x"),
  124. });
  125. expect(result.localPath.endsWith(`${sep}季度_报告_草稿__.xlsx`)).toBe(true);
  126. });
  127. it("Windows 保留名与空文件名换成可用的名字", async () => {
  128. const reserved = await materializeWorkflowArtifactFile({
  129. runId: "dwfrun-1",
  130. artifactId: "a",
  131. version: 1,
  132. fileName: "CON.md",
  133. bytes: bytesOf("x"),
  134. });
  135. const empty = await materializeWorkflowArtifactFile({
  136. runId: "dwfrun-1",
  137. artifactId: "b",
  138. version: 1,
  139. fileName: " ",
  140. bytes: bytesOf("x"),
  141. });
  142. expect(reserved.localPath.endsWith(`${sep}_CON.md`)).toBe(true);
  143. expect(empty.localPath.endsWith(`${sep}b`)).toBe(true);
  144. });
  145. // 修复原因(MR !2837 评审 CR-02):目录名曾只是清洗后的产物 id。引擎认为不同的两个 id 可以落进同一个
  146. // 目录——macOS / Windows 的文件系统默认不分大小写(`Report` 与 `report`),清洗又去掉开头的点
  147. // (`.notes` 与 `notes`)——同名文件随即以 EEXIST 命中对方的副本,打开的是另一个产物(连同用户的编辑)。
  148. it("引擎认为不同的产物 id 各落各的目录:大小写不同、只差开头的点", async () => {
  149. for (const [first, second] of [
  150. ["Report", "report"],
  151. [".notes", "notes"],
  152. ] as const) {
  153. const a = await materializeWorkflowArtifactFile({
  154. runId: "dwfrun-1",
  155. artifactId: first,
  156. version: 1,
  157. fileName: "same.md",
  158. bytes: bytesOf(first),
  159. });
  160. const b = await materializeWorkflowArtifactFile({
  161. runId: "dwfrun-1",
  162. artifactId: second,
  163. version: 1,
  164. fileName: "same.md",
  165. bytes: bytesOf(second),
  166. });
  167. expect(a.localPath.toLowerCase()).not.toBe(b.localPath.toLowerCase());
  168. await expect(readFile(a.localPath, "utf8")).resolves.toBe(first);
  169. await expect(readFile(b.localPath, "utf8")).resolves.toBe(second);
  170. }
  171. });
  172. // 同一条规则也盖住 runId:CLI 铸的 id 是 `dwfrun-<uuid>`,撞不上;但 IPC 边界只校验非空字符串,
  173. // 目录的唯一性不该靠这条注释。
  174. it("只差大小写的两个 run id 各落各的目录", async () => {
  175. const a = await materializeWorkflowArtifactFile({
  176. runId: "Run-1",
  177. artifactId: "report",
  178. version: 1,
  179. fileName: "report.md",
  180. bytes: bytesOf("upper"),
  181. });
  182. const b = await materializeWorkflowArtifactFile({
  183. runId: "run-1",
  184. artifactId: "report",
  185. version: 1,
  186. fileName: "report.md",
  187. bytes: bytesOf("lower"),
  188. });
  189. expect(a.localPath.toLowerCase()).not.toBe(b.localPath.toLowerCase());
  190. await expect(readFile(a.localPath, "utf8")).resolves.toBe("upper");
  191. await expect(readFile(b.localPath, "utf8")).resolves.toBe("lower");
  192. });
  193. it("超过 20 MiB 的字节拒绝写(与 artifact.file 的上限同级)", async () => {
  194. await expect(
  195. materializeWorkflowArtifactFile({
  196. runId: "dwfrun-1",
  197. artifactId: "big",
  198. version: 1,
  199. fileName: "big.bin",
  200. bytes: new Uint8Array(WORKFLOW_ARTIFACT_FILE_MAX_BYTES + 1),
  201. }),
  202. ).rejects.toThrow(/too large/u);
  203. });
  204. it("形状不对的请求在碰磁盘之前就拒绝", async () => {
  205. const valid = {
  206. runId: "dwfrun-1",
  207. artifactId: "report",
  208. version: 1,
  209. fileName: "report.md",
  210. bytes: bytesOf("x"),
  211. };
  212. for (const bad of [
  213. { ...valid, version: 0 },
  214. { ...valid, version: 1.5 },
  215. { ...valid, runId: "" },
  216. { ...valid, artifactId: 3 },
  217. { ...valid, bytes: "not bytes" },
  218. ]) {
  219. await expect(materializeWorkflowArtifactFile(bad as unknown as typeof valid)).rejects.toThrow(
  220. /invalid/u,
  221. );
  222. }
  223. await expect(readdir(join(tempRoot, ".zcode"))).rejects.toThrow();
  224. });
  225. });