official-plugin-cache-fs.test.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createOfficialPluginCacheRetryBudget,
  4. getOfficialPluginCacheRetryAttempts,
  5. isTransientOfficialPluginCacheFsError,
  6. retryOfficialPluginCacheFs,
  7. } from "../src/app/official-plugin-cache-fs.js";
  8. describe("official plugin cache fs helpers", () => {
  9. it("recognizes only transient cache contention errors", () => {
  10. for (const code of ["EACCES", "EBUSY", "EEXIST", "ENOTEMPTY", "EPERM"]) {
  11. expect(isTransientOfficialPluginCacheFsError(errno(code))).toBe(true);
  12. }
  13. expect(isTransientOfficialPluginCacheFsError(errno("ENOENT"))).toBe(false);
  14. expect(isTransientOfficialPluginCacheFsError(new Error("invalid manifest"))).toBe(false);
  15. });
  16. it("retries transient failures within the shared deadline", () => {
  17. let nowMs = 0;
  18. const sleep = vi.fn((delayMs: number) => {
  19. nowMs += delayMs;
  20. });
  21. const budget = createOfficialPluginCacheRetryBudget({
  22. durationMs: 1_500,
  23. now: () => nowMs,
  24. sleep,
  25. });
  26. let attempts = 0;
  27. const result = retryOfficialPluginCacheFs(
  28. () => {
  29. attempts += 1;
  30. if (attempts < 3) throw errno("EPERM");
  31. return "ok";
  32. },
  33. { budget },
  34. );
  35. expect(result).toBe("ok");
  36. expect(attempts).toBe(3);
  37. expect(sleep.mock.calls).toEqual([[25], [50]]);
  38. });
  39. it("stops retrying when the shared deadline cannot fit the next delay", () => {
  40. let nowMs = 0;
  41. const budget = createOfficialPluginCacheRetryBudget({
  42. durationMs: 60,
  43. now: () => nowMs,
  44. sleep: (delayMs) => {
  45. nowMs += delayMs;
  46. },
  47. });
  48. const error = errno("EPERM");
  49. let attempts = 0;
  50. expect(() =>
  51. retryOfficialPluginCacheFs(
  52. () => {
  53. attempts += 1;
  54. throw error;
  55. },
  56. { budget },
  57. ),
  58. ).toThrow(error);
  59. expect(attempts).toBe(2);
  60. expect(getOfficialPluginCacheRetryAttempts(error)).toBe(2);
  61. });
  62. it("does not retry non-transient failures", () => {
  63. const operation = vi.fn(() => {
  64. throw new Error("invalid manifest");
  65. });
  66. expect(() => retryOfficialPluginCacheFs(operation)).toThrow("invalid manifest");
  67. expect(operation).toHaveBeenCalledTimes(1);
  68. });
  69. });
  70. function errno(code: string): NodeJS.ErrnoException {
  71. return Object.assign(new Error(code), { code });
  72. }