file-mutation-queue.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import { access, mkdtemp, readFile, rm, symlink, 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 { createEditTool } from "../src/core/tools/edit.ts";
  6. import { withFileMutationQueue } from "../src/core/tools/file-mutation-queue.ts";
  7. import { createWriteTool } from "../src/core/tools/write.ts";
  8. function delay(ms: number): Promise<void> {
  9. return new Promise((resolve) => setTimeout(resolve, ms));
  10. }
  11. function createDeferred(): { promise: Promise<void>; resolve: () => void } {
  12. let resolve!: () => void;
  13. const promise = new Promise<void>((promiseResolve) => {
  14. resolve = promiseResolve;
  15. });
  16. return { promise, resolve };
  17. }
  18. async function resolvesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {
  19. return Promise.race([promise.then(() => true), delay(ms).then(() => false)]);
  20. }
  21. const tempDirs: string[] = [];
  22. async function createTempDir(): Promise<string> {
  23. const dir = await mkdtemp(join(tmpdir(), "pi-file-mutation-queue-"));
  24. tempDirs.push(dir);
  25. return dir;
  26. }
  27. afterEach(async () => {
  28. await Promise.all(tempDirs.splice(0, tempDirs.length).map((dir) => rm(dir, { recursive: true, force: true })));
  29. });
  30. describe("withFileMutationQueue", () => {
  31. it("serializes operations for the same file", async () => {
  32. const order: string[] = [];
  33. const path = "/tmp/file-mutation-queue-same";
  34. const first = withFileMutationQueue(path, async () => {
  35. order.push("first:start");
  36. await delay(30);
  37. order.push("first:end");
  38. });
  39. const second = withFileMutationQueue(path, async () => {
  40. order.push("second:start");
  41. order.push("second:end");
  42. });
  43. await Promise.all([first, second]);
  44. expect(order).toEqual(["first:start", "first:end", "second:start", "second:end"]);
  45. });
  46. it("allows different files to proceed in parallel", async () => {
  47. const order: string[] = [];
  48. const firstStarted = createDeferred();
  49. const secondStarted = createDeferred();
  50. const finishBoth = createDeferred();
  51. const first = withFileMutationQueue("/tmp/file-mutation-queue-a", async () => {
  52. order.push("a:start");
  53. firstStarted.resolve();
  54. await finishBoth.promise;
  55. order.push("a:end");
  56. });
  57. const second = withFileMutationQueue("/tmp/file-mutation-queue-b", async () => {
  58. order.push("b:start");
  59. secondStarted.resolve();
  60. await finishBoth.promise;
  61. order.push("b:end");
  62. });
  63. try {
  64. expect(await resolvesWithin(Promise.all([firstStarted.promise, secondStarted.promise]), 1000)).toBe(true);
  65. } finally {
  66. finishBoth.resolve();
  67. }
  68. await Promise.all([first, second]);
  69. expect(order.indexOf("a:start")).toBeLessThan(order.indexOf("a:end"));
  70. expect(order.indexOf("b:start")).toBeLessThan(order.indexOf("b:end"));
  71. expect(order.indexOf("b:start")).toBeLessThan(order.indexOf("a:end"));
  72. });
  73. it("uses the same queue for symlink aliases", async () => {
  74. const dir = await createTempDir();
  75. const targetPath = join(dir, "target.txt");
  76. const symlinkPath = join(dir, "alias.txt");
  77. await writeFile(targetPath, "hello\n", "utf8");
  78. await symlink(targetPath, symlinkPath);
  79. const order: string[] = [];
  80. await Promise.all([
  81. withFileMutationQueue(targetPath, async () => {
  82. order.push("target:start");
  83. await delay(30);
  84. order.push("target:end");
  85. }),
  86. withFileMutationQueue(symlinkPath, async () => {
  87. order.push("alias:start");
  88. order.push("alias:end");
  89. }),
  90. ]);
  91. expect(order).toEqual(["target:start", "target:end", "alias:start", "alias:end"]);
  92. });
  93. });
  94. describe("built-in edit and write tools", () => {
  95. it("preserves both parallel edits on the same file", async () => {
  96. const dir = await createTempDir();
  97. const filePath = join(dir, "parallel-edit.txt");
  98. await writeFile(filePath, "alpha\nbeta\ngamma\n", "utf8");
  99. const editTool = createEditTool(dir, {
  100. operations: {
  101. access,
  102. readFile: async (path) => {
  103. const buffer = await readFile(path);
  104. await delay(30);
  105. return buffer;
  106. },
  107. writeFile: async (path, content) => {
  108. await delay(30);
  109. await writeFile(path, content, "utf8");
  110. },
  111. },
  112. });
  113. await Promise.all([
  114. editTool.execute("call-1", { path: filePath, edits: [{ oldText: "alpha", newText: "ALPHA" }] }),
  115. editTool.execute("call-2", { path: filePath, edits: [{ oldText: "beta", newText: "BETA" }] }),
  116. ]);
  117. const content = await readFile(filePath, "utf8");
  118. expect(content).toBe("ALPHA\nBETA\ngamma\n");
  119. });
  120. it("shares the queue between edit and write", async () => {
  121. const dir = await createTempDir();
  122. const filePath = join(dir, "mixed.txt");
  123. await writeFile(filePath, "original\n", "utf8");
  124. const editTool = createEditTool(dir, {
  125. operations: {
  126. access,
  127. readFile: async (path) => {
  128. const buffer = await readFile(path);
  129. await delay(30);
  130. return buffer;
  131. },
  132. writeFile: async (path, content) => {
  133. await delay(30);
  134. await writeFile(path, content, "utf8");
  135. },
  136. },
  137. });
  138. const writeTool = createWriteTool(dir, {
  139. operations: {
  140. mkdir: async () => {},
  141. writeFile: async (path, content) => {
  142. await delay(10);
  143. await writeFile(path, content, "utf8");
  144. },
  145. },
  146. });
  147. const editPromise = editTool.execute("call-1", {
  148. path: filePath,
  149. edits: [{ oldText: "original", newText: "edited" }],
  150. });
  151. await delay(5);
  152. const writePromise = writeTool.execute("call-2", {
  153. path: filePath,
  154. content: "replacement\n",
  155. });
  156. await Promise.all([editPromise, writePromise]);
  157. const content = await readFile(filePath, "utf8");
  158. expect(content).toBe("replacement\n");
  159. });
  160. it("keeps write queue locked while an aborted write is still in flight", async () => {
  161. const dir = await createTempDir();
  162. const filePath = join(dir, "abort-write.txt");
  163. const firstWriteStarted = createDeferred();
  164. const finishFirstWrite = createDeferred();
  165. const secondWriteStarted = createDeferred();
  166. let firstWriteSettled = false;
  167. const writeTool = createWriteTool(dir, {
  168. operations: {
  169. mkdir: async () => {},
  170. writeFile: async (path, content) => {
  171. if (content === "first\n") {
  172. firstWriteStarted.resolve();
  173. await finishFirstWrite.promise;
  174. await writeFile(path, content, "utf8");
  175. firstWriteSettled = true;
  176. return;
  177. }
  178. if (content === "second\n") {
  179. expect(firstWriteSettled).toBe(true);
  180. secondWriteStarted.resolve();
  181. }
  182. await writeFile(path, content, "utf8");
  183. },
  184. },
  185. });
  186. const controller = new AbortController();
  187. const firstWrite = writeTool.execute("call-1", { path: filePath, content: "first\n" }, controller.signal);
  188. await firstWriteStarted.promise;
  189. controller.abort();
  190. const secondWrite = writeTool.execute("call-2", { path: filePath, content: "second\n" });
  191. expect(await resolvesWithin(secondWriteStarted.promise, 20)).toBe(false);
  192. finishFirstWrite.resolve();
  193. await expect(firstWrite).rejects.toThrow("Operation aborted");
  194. await secondWrite;
  195. const content = await readFile(filePath, "utf8");
  196. expect(content).toBe("second\n");
  197. });
  198. it("keeps edit queue locked while an aborted edit write is still in flight", async () => {
  199. const dir = await createTempDir();
  200. const filePath = join(dir, "abort-edit.txt");
  201. await writeFile(filePath, "alpha\nbeta\n", "utf8");
  202. const firstWriteStarted = createDeferred();
  203. const finishFirstWrite = createDeferred();
  204. const secondWriteStarted = createDeferred();
  205. let firstWriteSettled = false;
  206. const editTool = createEditTool(dir, {
  207. operations: {
  208. access,
  209. readFile,
  210. writeFile: async (path, content) => {
  211. if (content === "ALPHA\nbeta\n") {
  212. firstWriteStarted.resolve();
  213. await finishFirstWrite.promise;
  214. await writeFile(path, content, "utf8");
  215. firstWriteSettled = true;
  216. return;
  217. }
  218. if (content === "ALPHA\nBETA\n" || content === "alpha\nBETA\n") {
  219. expect(firstWriteSettled).toBe(true);
  220. secondWriteStarted.resolve();
  221. }
  222. await writeFile(path, content, "utf8");
  223. },
  224. },
  225. });
  226. const controller = new AbortController();
  227. const firstEdit = editTool.execute(
  228. "call-1",
  229. { path: filePath, edits: [{ oldText: "alpha", newText: "ALPHA" }] },
  230. controller.signal,
  231. );
  232. await firstWriteStarted.promise;
  233. controller.abort();
  234. const secondEdit = editTool.execute("call-2", {
  235. path: filePath,
  236. edits: [{ oldText: "beta", newText: "BETA" }],
  237. });
  238. expect(await resolvesWithin(secondWriteStarted.promise, 20)).toBe(false);
  239. finishFirstWrite.resolve();
  240. await expect(firstEdit).rejects.toThrow("Operation aborted");
  241. await secondEdit;
  242. const content = await readFile(filePath, "utf8");
  243. expect(content).toBe("ALPHA\nBETA\n");
  244. });
  245. });