Skip to content

Commit 4cdffd7

Browse files
committed
refactor: centralize atomic filesystem publication
1 parent 6e3134b commit 4cdffd7

15 files changed

Lines changed: 449 additions & 403 deletions
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { test, vi } from 'vitest';
5+
import { isAtomicPublishTemporaryPath } from '../../utils/atomic-file.ts';
6+
import { mkdtempForTestSync } from './tmp-dir.ts';
7+
8+
export type FilesystemErrno = 'EIO' | 'ENOSPC' | 'EMFILE';
9+
export type FilesystemFaultPoint = 'write' | 'rename';
10+
11+
export type FilesystemBoundaryFixture = {
12+
targetPath: string;
13+
run: () => unknown | Promise<unknown>;
14+
expected: 'throw' | 'return';
15+
verifyReturn?: (value: unknown, errno: FilesystemErrno) => void;
16+
};
17+
18+
export type FilesystemBoundaryOwner = (root: string) => FilesystemBoundaryFixture;
19+
20+
export const FILESYSTEM_ERRNOS: readonly FilesystemErrno[] = ['EIO', 'ENOSPC', 'EMFILE'];
21+
export const FILESYSTEM_FAULT_POINTS: readonly FilesystemFaultPoint[] = ['write', 'rename'];
22+
23+
/** Registers every fault row for a typed owner table. Missing required owners fail typechecking. */
24+
export function registerFilesystemBoundaryMatrix(
25+
owners: Readonly<Record<string, FilesystemBoundaryOwner>>,
26+
prefix: string,
27+
): void {
28+
for (const [ownerName, createFixture] of Object.entries(owners)) {
29+
for (const faultPoint of FILESYSTEM_FAULT_POINTS) {
30+
for (const errno of FILESYSTEM_ERRNOS) {
31+
test(`${prefix} ${ownerName} ${faultPoint} ${errno} leaves no unpublished temporary file`, async () => {
32+
const root = mkdtempForTestSync(
33+
`agent-device-${prefix}-${ownerName.replaceAll('/', '-')}-boundary-`,
34+
);
35+
const fixture = createFixture(root);
36+
const fault = installFilesystemFault({
37+
faultPoint,
38+
errno,
39+
targetPath: fixture.targetPath,
40+
});
41+
42+
let value: unknown;
43+
let thrown: unknown;
44+
try {
45+
value = await fixture.run();
46+
} catch (error) {
47+
thrown = error;
48+
}
49+
50+
if (fixture.expected === 'throw') {
51+
assert.ok(thrown, `${ownerName} should surface ${errno}`);
52+
assert.equal((thrown as NodeJS.ErrnoException).code, errno);
53+
} else {
54+
assert.equal(thrown, undefined);
55+
fixture.verifyReturn?.(value, errno);
56+
}
57+
assert.equal(fault.wasInjected(), true, `${ownerName} ${faultPoint} fault was injected`);
58+
assert.equal(fs.existsSync(fixture.targetPath), false);
59+
assert.deepEqual(listTemporaryFiles(root), []);
60+
});
61+
}
62+
}
63+
}
64+
}
65+
66+
export function installFilesystemFault(options: {
67+
faultPoint: FilesystemFaultPoint;
68+
errno: FilesystemErrno;
69+
targetPath: string;
70+
}): { wasInjected: () => boolean } {
71+
const failure = createErrno(options.errno);
72+
let injected = false;
73+
const temporaryDescriptors = new Set<number>();
74+
const isTargetOrTemporary = (value: unknown): boolean =>
75+
value === options.targetPath || isAtomicPublishTemporaryPath(value, options.targetPath);
76+
77+
if (options.faultPoint === 'write') {
78+
const originalOpenSync = fs.openSync;
79+
vi.spyOn(fs, 'openSync').mockImplementation((...args) => {
80+
const descriptor = Reflect.apply(originalOpenSync, fs, args);
81+
if (isAtomicPublishTemporaryPath(args[0], options.targetPath)) {
82+
temporaryDescriptors.add(descriptor);
83+
}
84+
return descriptor;
85+
});
86+
87+
const originalWriteFileSync = fs.writeFileSync;
88+
vi.spyOn(fs, 'writeFileSync').mockImplementation((...args) => {
89+
const destination = args[0];
90+
const writesPublishedTemporary =
91+
isAtomicPublishTemporaryPath(destination, options.targetPath) ||
92+
(typeof destination === 'number' && temporaryDescriptors.has(destination));
93+
if (writesPublishedTemporary) {
94+
injected = true;
95+
Reflect.apply(originalWriteFileSync, fs, args);
96+
throw failure;
97+
}
98+
return Reflect.apply(originalWriteFileSync, fs, args);
99+
});
100+
} else {
101+
const originalRenameSync = fs.renameSync;
102+
vi.spyOn(fs, 'renameSync').mockImplementation((...args) => {
103+
if (isTargetOrTemporary(args[0]) || isTargetOrTemporary(args[1])) {
104+
injected = true;
105+
throw failure;
106+
}
107+
return Reflect.apply(originalRenameSync, fs, args);
108+
});
109+
}
110+
111+
return { wasInjected: () => injected };
112+
}
113+
114+
function createErrno(errno: FilesystemErrno): NodeJS.ErrnoException {
115+
const error = new Error(`injected filesystem ${errno}`) as NodeJS.ErrnoException;
116+
error.code = errno;
117+
return error;
118+
}
119+
120+
function listTemporaryFiles(root: string): string[] {
121+
const temporaryFiles: string[] = [];
122+
123+
function visit(directory: string): void {
124+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
125+
const entryPath = path.join(directory, entry.name);
126+
if (entry.isDirectory()) visit(entryPath);
127+
else if (entry.name.endsWith('.tmp')) temporaryFiles.push(entryPath);
128+
}
129+
}
130+
131+
visit(root);
132+
return temporaryFiles;
133+
}

0 commit comments

Comments
 (0)