// atomicWriteSync: temp file, then rename over the target. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import fs from 'fs'; import os from 'os'; import path from 'path'; import { atomicWriteSync } from '../utils/atomic-write'; let dir: string; const target = () => path.join(dir, 'state.json'); const realPlatform = process.platform; const eperm = () => Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }); beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'node9-atomic-write-')); }); afterEach(() => { Object.defineProperty(process, 'platform', { value: realPlatform }); vi.restoreAllMocks(); fs.rmSync(dir, { recursive: true, force: true }); }); /** renameSync fails `times` times with EPERM, then behaves. */ function renameFails(times: number): () => number { const realRename = fs.renameSync; let left = times; vi.spyOn(fs, 'renameSync').mockImplementation(((a: fs.PathLike, b: fs.PathLike) => { if (left > 0) { left--; throw eperm(); } return realRename(a, b); }) as typeof fs.renameSync); return () => left; } describe('atomicWriteSync', () => { it('writes the file and leaves no temp file', () => { atomicWriteSync(target(), 'hello'); expect(fs.readFileSync(target(), 'utf-8')).toBe('hello'); expect(fs.readdirSync(dir)).toEqual(['state.json']); }); it('on Windows, retries a rename the target refuses for a moment', () => { // REGRESSION (CI windows-latest): a rename over a file another process // has open (the virus scanner reading what was just written) fails with // EPERM until the handle closes. Thrown at once, the write was lost. Object.defineProperty(process, 'platform', { value: 'win32' }); fs.writeFileSync(target(), 'old'); const left = renameFails(3); atomicWriteSync(target(), 'new'); expect(left()).toBe(0); expect(fs.readFileSync(target(), 'utf-8')).toBe('new'); expect(fs.readdirSync(dir)).toEqual(['state.json']); }); it('on Windows, gives up after a short wait and removes the temp file', () => { Object.defineProperty(process, 'platform', { value: 'win32' }); fs.writeFileSync(target(), 'old'); renameFails(Number.POSITIVE_INFINITY); const started = Date.now(); expect(() => atomicWriteSync(target(), 'new')).toThrow(/EPERM/); expect(Date.now() - started).toBeLessThan(2000); expect(fs.readFileSync(target(), 'utf-8')).toBe('old'); expect(fs.readdirSync(dir)).toEqual(['state.json']); }); it('elsewhere, a failed rename throws at once', () => { Object.defineProperty(process, 'platform', { value: 'linux' }); const left = renameFails(1); expect(() => atomicWriteSync(target(), 'new')).toThrow(/EPERM/); expect(left()).toBe(0); }); });