plugin-storage-lock.test.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { describe, expect, it } from "vitest";
  2. import { withPluginStorageLock } from "../src/lib/plugin-storage-lock.js";
  3. describe("withPluginStorageLock", () => {
  4. it("serializes operations on the same storage root", async () => {
  5. const order: string[] = [];
  6. const slow = withPluginStorageLock("/root-a", async () => {
  7. order.push("a-start");
  8. await new Promise((r) => setTimeout(r, 30));
  9. order.push("a-end");
  10. return "a";
  11. });
  12. const fast = withPluginStorageLock("/root-a", async () => {
  13. order.push("b-start");
  14. order.push("b-end");
  15. return "b";
  16. });
  17. await Promise.all([slow, fast]);
  18. expect(order).toEqual(["a-start", "a-end", "b-start", "b-end"]);
  19. });
  20. it("runs different roots concurrently", async () => {
  21. const order: string[] = [];
  22. await Promise.all([
  23. withPluginStorageLock("/root-a", async () => {
  24. order.push("a-start");
  25. await new Promise((r) => setTimeout(r, 30));
  26. order.push("a-end");
  27. }),
  28. withPluginStorageLock("/root-b", async () => {
  29. order.push("b");
  30. }),
  31. ]);
  32. expect(order[0]).toBe("a-start");
  33. expect(order).toContain("b");
  34. // b should not wait for a-end
  35. expect(order.indexOf("b")).toBeLessThan(order.indexOf("a-end"));
  36. });
  37. it("releases the lock even if the operation throws", async () => {
  38. await expect(
  39. withPluginStorageLock("/root-c", async () => {
  40. throw new Error("boom");
  41. }),
  42. ).rejects.toThrow("boom");
  43. // next op still runs
  44. await expect(
  45. withPluginStorageLock("/root-c", async () => "ok"),
  46. ).resolves.toBe("ok");
  47. });
  48. });