|
| 1 | +import * as fs from "node:fs/promises"; |
| 2 | + |
| 3 | +const transientRenameCodes: ReadonlySet<string> = new Set([ |
| 4 | + "EPERM", |
| 5 | + "EACCES", |
| 6 | + "EBUSY", |
| 7 | +]); |
| 8 | + |
| 9 | +/** |
| 10 | + * Rename with retry for transient Windows filesystem errors (EPERM, EACCES, |
| 11 | + * EBUSY). On Windows, antivirus, Search Indexer, cloud sync, or concurrent |
| 12 | + * processes can briefly lock files causing renames to fail. |
| 13 | + * |
| 14 | + * On non-Windows platforms, calls renameFn directly with no retry. |
| 15 | + * |
| 16 | + * Matches the strategy used by VS Code (pfs.ts) and graceful-fs: 60s |
| 17 | + * wall-clock timeout with linear backoff (10ms increments) capped at 100ms. |
| 18 | + */ |
| 19 | +export async function renameWithRetry( |
| 20 | + renameFn: (src: string, dest: string) => Promise<void>, |
| 21 | + source: string, |
| 22 | + destination: string, |
| 23 | + timeoutMs = 60_000, |
| 24 | + delayCapMs = 100, |
| 25 | +): Promise<void> { |
| 26 | + if (process.platform !== "win32") { |
| 27 | + return renameFn(source, destination); |
| 28 | + } |
| 29 | + const startTime = Date.now(); |
| 30 | + for (let attempt = 1; ; attempt++) { |
| 31 | + try { |
| 32 | + return await renameFn(source, destination); |
| 33 | + } catch (err) { |
| 34 | + const code = (err as NodeJS.ErrnoException).code; |
| 35 | + if ( |
| 36 | + !code || |
| 37 | + !transientRenameCodes.has(code) || |
| 38 | + Date.now() - startTime >= timeoutMs |
| 39 | + ) { |
| 40 | + throw err; |
| 41 | + } |
| 42 | + const delay = Math.min(delayCapMs, attempt * 10); |
| 43 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Generate a temporary file path by appending a suffix with a random component. |
| 50 | + * The suffix describes the purpose of the temp file (e.g. "temp", "old"). |
| 51 | + * Example: tempFilePath("/a/b", "temp") → "/a/b.temp-k7x3f9qw" |
| 52 | + */ |
| 53 | +export function tempFilePath(basePath: string, suffix: string): string { |
| 54 | + return `${basePath}.${suffix}-${crypto.randomUUID().substring(0, 8)}`; |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Atomically writes to `outputPath` via a sibling temp file and rename. |
| 59 | + * The parent directory must already exist. On failure the destination is |
| 60 | + * left untouched, the temp file is best-effort removed, and the writer |
| 61 | + * error is always rethrown. `onCleanupError` receives any error from the |
| 62 | + * cleanup attempt; its own throws are swallowed. |
| 63 | + */ |
| 64 | +export async function writeAtomically<T>( |
| 65 | + outputPath: string, |
| 66 | + write: (tempPath: string) => Promise<T>, |
| 67 | + onCleanupError: (err: unknown, tempPath: string) => void, |
| 68 | +): Promise<T> { |
| 69 | + const tempPath = tempFilePath(outputPath, "temp"); |
| 70 | + try { |
| 71 | + const result = await write(tempPath); |
| 72 | + await renameWithRetry(fs.rename, tempPath, outputPath); |
| 73 | + return result; |
| 74 | + } catch (err) { |
| 75 | + try { |
| 76 | + await fs.rm(tempPath, { force: true }).catch((rmErr) => { |
| 77 | + onCleanupError(rmErr, tempPath); |
| 78 | + }); |
| 79 | + } catch { |
| 80 | + // onCleanupError threw; the writer error below takes precedence. |
| 81 | + } |
| 82 | + throw err; |
| 83 | + } |
| 84 | +} |
0 commit comments