windows-file-system.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const RETRYABLE_WINDOWS_FILE_CODES = new Set(['EACCES', 'EBUSY', 'EPERM']);
  2. const DEFAULT_RETRIES = 4;
  3. const DEFAULT_RETRY_DELAY_MS = 50;
  4. export interface WindowsFileSystemRetryOptions {
  5. platform?: NodeJS.Platform;
  6. retries?: number;
  7. retryDelayMs?: number;
  8. wait?(delayMs: number): void;
  9. }
  10. export function retryWindowsFileSystemOperation<T>(
  11. operation: () => T,
  12. options: WindowsFileSystemRetryOptions = {},
  13. ): T {
  14. const platform = options.platform ?? process.platform;
  15. const retries = Math.max(0, Math.floor(options.retries ?? DEFAULT_RETRIES));
  16. const retryDelayMs = Math.max(0, Math.floor(options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS));
  17. const wait = options.wait ?? waitSynchronously;
  18. for (let attempt = 0; ; attempt += 1) {
  19. try {
  20. return operation();
  21. } catch (error) {
  22. if (platform !== 'win32' || attempt >= retries || !isRetryableWindowsFileError(error)) {
  23. throw error;
  24. }
  25. wait(retryDelayMs * (attempt + 1));
  26. }
  27. }
  28. }
  29. function isRetryableWindowsFileError(error: unknown): boolean {
  30. return (
  31. typeof error === 'object' &&
  32. error !== null &&
  33. 'code' in error &&
  34. typeof error.code === 'string' &&
  35. RETRYABLE_WINDOWS_FILE_CODES.has(error.code)
  36. );
  37. }
  38. function waitSynchronously(delayMs: number): void {
  39. if (delayMs <= 0) return;
  40. Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs);
  41. }