Open History to see the last commit
1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import type * as PlatformError from "effect/PlatformError";
4
5const WINDOWS_FILE_RETRY_DELAYS = [25, 75, 150, 300, 600] as const;
6const TRANSIENT_WINDOWS_SYSTEM_ERROR_TAGS = new Set([
7 "Busy",
8 "PermissionDenied",
9 "WouldBlock",
10]);
11const TRANSIENT_WINDOWS_ERROR_CODES = new Set([
12 "EACCES",
13 "EBUSY",
14 "EMFILE",
15 "ENFILE",
16 "EPERM",
17 "ETXTBSY",
18]);
19
20function readErrorCode(value: unknown): string | null {
21 if (typeof value !== "object" || value === null) return null;
22 const code = (value as { readonly code?: unknown }).code;
23 if (typeof code === "string") return code.toUpperCase();
24 const cause = (value as { readonly cause?: unknown }).cause;
25 return cause === value ? null : readErrorCode(cause);
26}
27
28export function isTransientWindowsFileSystemError(error: PlatformError.PlatformError): boolean {
29 if (TRANSIENT_WINDOWS_SYSTEM_ERROR_TAGS.has(error.reason._tag)) {
30 return true;
31 }
32 return TRANSIENT_WINDOWS_ERROR_CODES.has(readErrorCode(error.reason) ?? "");
33}
34
35/**
36 * Windows scanners, indexers, sync clients, and antivirus software can briefly
37 * hold a file between our temporary-file write and atomic rename. Effect
38 * normalizes those failures to Busy / WouldBlock / PermissionDenied (or an
39 * Unknown reason retaining the original Node errno). Retry only that bounded
40 * class; permanent filesystem failures still surface to the caller.
41 */
42export function retryWindowsFileSystemOperation<A>(
43 operation: Effect.Effect<A, PlatformError.PlatformError>,
44 options?: {
45 readonly platform?: NodeJS.Platform;
46 readonly delaysMs?: readonly number[];
47 },
48): Effect.Effect<A, PlatformError.PlatformError> {
49 const platform = options?.platform ?? process.platform;
50 if (platform !== "win32") return operation;
51 const delays = options?.delaysMs ?? WINDOWS_FILE_RETRY_DELAYS;
52
53 const attempt = (index: number): Effect.Effect<A, PlatformError.PlatformError> =>
54 operation.pipe(
55 Effect.catch((error) => {
56 const delay = delays[index];
57 if (delay === undefined || !isTransientWindowsFileSystemError(error)) {
58 return Effect.fail(error);
59 }
60 return Effect.sleep(Duration.millis(delay)).pipe(Effect.andThen(attempt(index + 1)));
61 }),
62 );
63
64 return attempt(0);
65}