Skip to content

Commit cb44a1d

Browse files
committed
fix: preserve async filesystem injection
1 parent 1d037a2 commit cb44a1d

8 files changed

Lines changed: 34 additions & 60 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
### Compatibility
1414

15-
- Add optional `promises.fchmod` and `fchmodSync` operations to the injectable atomic-replacement filesystem types. Custom adapters that pass `mode` or `preserveExistingMode` must implement the matching descriptor operation and now fail before mutation when it is absent; adapters that request neither option remain compatible.
15+
- Add an optional `fchmodSync` operation to the injectable synchronous atomic-replacement filesystem type. Async adapters need no new member because their required `open()` returns a mode-capable `FileHandle`; custom sync adapters that pass `mode` or `preserveExistingMode` now fail before mutation when `fchmodSync` is absent, while adapters that request neither option remain compatible.
1616

1717
## 0.5.1 - 2026-08-01
1818

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ await replaceFileAtomic({
290290
});
291291
```
292292

293-
`replaceFileAtomicSync()` covers the synchronous case with the same options shape. Both accept an injectable `fileSystem` for tests; custom adapters using `mode` or `preserveExistingMode` provide the optional descriptor-bound `promises.fchmod` or `fchmodSync` operation.
293+
`replaceFileAtomicSync()` covers the synchronous case with the same options shape. Both accept an injectable `fileSystem` for tests. Async adapters use `chmod()` on the `FileHandle` returned by their required `open()` operation; custom sync adapters using `mode` or `preserveExistingMode` provide the optional descriptor-bound `fchmodSync` operation.
294294

295295
## External outputs
296296

‎docs/atomic.md‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -205,31 +205,23 @@ await replaceFileAtomic({
205205
fileSystem: {
206206
promises: {
207207
...realFs,
208-
fchmod: async (handle, mode) => handle.chmod(mode),
209208
writeFile: async (...args) => { ops.push("write"); return realFs.writeFile(...args); },
210209
rename: async (...args) => { ops.push("rename"); return realFs.rename(...args); },
211210
},
212211
},
213212
});
214213
```
215214

216-
The injectable interfaces add optional descriptor-mode operations:
215+
The synchronous injectable interface adds one optional descriptor-mode operation:
217216

218217
```ts
219-
type ReplaceFileAtomicFileSystem = {
220-
promises: {
221-
// other required operations omitted
222-
fchmod?: (handle: import("node:fs/promises").FileHandle, mode: number) => Promise<void>;
223-
};
224-
};
225-
226218
type ReplaceFileAtomicSyncFileSystem = {
227219
// other required operations omitted
228220
fchmodSync?: typeof import("node:fs").fchmodSync;
229221
};
230222
```
231223

232-
The built-in filesystem always applies the resolved mode through the temporary file descriptor. A custom filesystem that passes `mode` or `preserveExistingMode` must supply the matching descriptor operation; omission fails before any file is created and never falls back to `chmod(destination)`. Existing custom filesystems that request neither option may omit the new member. Copy fallback applies the mode through its pinned destination descriptor as well, preserving exact modes despite the process umask.
224+
The async interface already requires `open()`, whose `FileHandle` supplies `chmod()`, so injecting `node:fs` or another conforming adapter needs no new async member. A custom synchronous filesystem that passes `mode` or `preserveExistingMode` must supply `fchmodSync`; omission fails before any file is created and never falls back to `chmod(destination)`. Existing synchronous adapters that request neither option may omit it. Copy fallback applies the mode through its pinned destination descriptor as well, preserving exact modes despite the process umask.
233225

234226
## See also
235227

‎docs/types.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
The types most callers reach for. Shared data shapes are exported from `@openclaw/fs-safe/types`; method-specific option/result types live next to their subpath.
44

5-
For atomic replacement, `ReplaceFileAtomicFileSystem` and `ReplaceFileAtomicSyncFileSystem` are exported from `@openclaw/fs-safe/atomic`. Their optional `promises.fchmod(handle, mode)` and `fchmodSync(fd, mode)` members let injected filesystems apply exact modes through pinned descriptors. Custom adapters that explicitly request `mode` or `preserveExistingMode` must implement the corresponding member; see [Atomic writes](atomic.md#test-injection).
5+
For atomic replacement, `ReplaceFileAtomicFileSystem` and `ReplaceFileAtomicSyncFileSystem` are exported from `@openclaw/fs-safe/atomic`. Async adapters use `chmod()` on the `FileHandle` returned by their required `open()` operation. The synchronous type adds optional `fchmodSync(fd, mode)`; custom sync adapters that explicitly request `mode` or `preserveExistingMode` must implement it. See [Atomic writes](atomic.md#test-injection).
66

77
```ts
88
import type {

‎src/replace-file-copy-fallback.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,6 @@ export async function copyFallbackReplace(params: {
300300
destinationHardlinks?: ReplaceFileDestinationHardlinkPolicy;
301301
restore: ReplaceFileCopyFallbackRestorePolicy;
302302
maxRestoreBytes?: number;
303-
fchmod?: (handle: FileHandle, mode: number) => Promise<void>;
304303
}): Promise<void> {
305304
const sourcePreview = await params.fsModule.lstat(params.src);
306305
if (sourcePreview.isSymbolicLink() || !sourcePreview.isFile()) {
@@ -351,9 +350,7 @@ export async function copyFallbackReplace(params: {
351350
);
352351
await destHandle.writeFile(replacement);
353352
}
354-
if (params.fchmod) {
355-
await params.fchmod(destHandle, sourceStat.mode);
356-
}
353+
await destHandle.chmod(sourceStat.mode);
357354
} finally {
358355
await destHandle?.close().catch(() => undefined);
359356
await sourceHandle.close().catch(() => undefined);

‎src/replace-file-descriptor.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,19 @@ type SyncTempFileSystem = Pick<
77
"closeSync" | "fstatSync" | "fsyncSync" | "openSync" | "writeFileSync"
88
>;
99

10-
export type AsyncFchmod = (handle: FileHandle, mode: number) => Promise<void>;
1110
export type SyncFchmod = (fd: number, mode: number) => void;
1211

1312
export async function writeTempFile(params: {
1413
fsModule: AsyncTempFileSystem;
1514
tempPath: string;
1615
content: string | Uint8Array;
1716
mode: number;
18-
fchmod?: AsyncFchmod;
1917
sync: boolean;
2018
}): Promise<Stats> {
2119
const handle = await params.fsModule.open(params.tempPath, "wx", params.mode);
2220
try {
2321
await params.fsModule.writeFile(handle, params.content);
24-
if (params.fchmod) {
25-
await params.fchmod(handle, params.mode);
26-
}
22+
await handle.chmod(params.mode);
2723
if (params.sync) {
2824
try {
2925
await handle.sync();

‎src/replace-file.ts‎

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto";
22
import syncFs from "node:fs";
33
import type { Stats } from "node:fs";
44
import fs from "node:fs/promises";
5-
import type { FileHandle } from "node:fs/promises";
65
import path from "node:path";
76
import {
87
assertDestinationHardlinkPolicy,
@@ -15,7 +14,6 @@ import {
1514
type ReplaceFileDestinationHardlinkPolicy,
1615
} from "./replace-file-copy-fallback.js";
1716
import {
18-
type AsyncFchmod,
1917
type SyncFchmod,
2018
writeTempFile,
2119
writeTempFileSync,
@@ -37,9 +35,7 @@ export type ReplaceFileAtomicFileSystem = {
3735
| "open"
3836
| "stat"
3937
| "lstat"
40-
> & {
41-
fchmod?: (handle: FileHandle, mode: number) => Promise<void>;
42-
};
38+
>;
4339
};
4440

4541
export type ReplaceFileAtomicSyncFileSystem = Pick<
@@ -127,7 +123,6 @@ async function renameWithRetry(params: {
127123
copyFallbackRestore: ReplaceFileCopyFallbackRestorePolicy;
128124
maxRestoreBytes?: number;
129125
destinationHardlinks?: ReplaceFileDestinationHardlinkPolicy;
130-
fchmod?: AsyncFchmod;
131126
}): Promise<ReplaceFileAtomicResult> {
132127
for (let attempt = 0; attempt <= params.maxRetries; attempt++) {
133128
try {
@@ -146,7 +141,6 @@ async function renameWithRetry(params: {
146141
destinationHardlinks: params.destinationHardlinks,
147142
restore: params.copyFallbackRestore,
148143
maxRestoreBytes: params.maxRestoreBytes,
149-
fchmod: params.fchmod,
150144
});
151145
return { method: "copy-fallback" };
152146
}
@@ -255,9 +249,9 @@ function resolveModeSync(options: ReplaceFileAtomicSyncOptions): number {
255249
return stat ? stat.mode : defaultMode;
256250
}
257251

258-
function missingFchmodError(member: "promises.fchmod" | "fchmodSync"): TypeError {
252+
function missingFchmodSyncError(): TypeError {
259253
return new TypeError(
260-
`fileSystem.${member} is required when mode or preserveExistingMode is specified`,
254+
"fileSystem.fchmodSync is required when mode or preserveExistingMode is specified",
261255
);
262256
}
263257

@@ -333,14 +327,6 @@ async function replaceFileAtomicUnserialized(
333327
const dir = path.dirname(filePath);
334328
const dirMode = options.dirMode ?? 0o700;
335329
const mode = await resolveMode(options);
336-
const fchmod = options.fileSystem?.promises.fchmod ?? (
337-
options.fileSystem === undefined
338-
? async (handle: FileHandle, requestedMode: number) => await handle.chmod(requestedMode)
339-
: undefined
340-
);
341-
if (!fchmod && (options.mode !== undefined || options.preserveExistingMode === true)) {
342-
throw missingFchmodError("promises.fchmod");
343-
}
344330
const tempPath = buildReplaceTempPath(filePath, options.tempPrefix);
345331
const unregisterTempPath = registerTempPathForExit(tempPath);
346332
let tempExists = false;
@@ -354,7 +340,6 @@ async function replaceFileAtomicUnserialized(
354340
tempPath,
355341
content: options.content,
356342
mode,
357-
fchmod,
358343
sync: options.syncTempFile === true,
359344
}));
360345
if (options.beforeRename) {
@@ -371,7 +356,6 @@ async function replaceFileAtomicUnserialized(
371356
copyFallbackRestore: options.copyFallbackRestore ?? "none",
372357
maxRestoreBytes: options.maxRestoreBytes,
373358
destinationHardlinks: options.destinationHardlinks,
374-
fchmod,
375359
});
376360
tempExists = false;
377361
unregisterTempPath();
@@ -409,7 +393,7 @@ export function replaceFileAtomicSync(
409393
options.fileSystem === undefined ? syncFs.fchmodSync : undefined
410394
);
411395
if (!fchmodSync && (options.mode !== undefined || options.preserveExistingMode === true)) {
412-
throw missingFchmodError("fchmodSync");
396+
throw missingFchmodSyncError();
413397
}
414398
const tempPath = buildReplaceTempPath(filePath, options.tempPrefix);
415399
const unregisterTempPath = registerTempPathForExit(tempPath);

‎test/atomic-fchmod-regression.test.ts‎

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ describe("atomic descriptor modes", () => {
3838
fileSystem: {
3939
promises: {
4040
...fs,
41-
fchmod: async (handle, mode) => await handle.chmod(mode),
4241
chmod: async (candidate, mode) => {
4342
chmodPaths.push(String(candidate));
4443
await fs.chmod(candidate, mode);
@@ -141,7 +140,6 @@ describe("atomic descriptor modes", () => {
141140
fileSystem: {
142141
promises: {
143142
...fs,
144-
fchmod: async (handle, mode) => await handle.chmod(mode),
145143
rename: async () => { throw renameDenied(); },
146144
},
147145
},
@@ -165,41 +163,48 @@ describe("atomic descriptor modes", () => {
165163
},
166164
);
167165

168-
it("fails closed before mutation when an injected filesystem cannot set an explicit mode", async () => {
166+
it.runIf(process.platform !== "win32")(
167+
"accepts node:fs injection with an explicit async mode",
168+
async () => {
169+
const root = await tempRoot("fs-safe-atomic-node-fs-");
170+
const filePath = path.join(root, "state.txt");
171+
const previousUmask = process.umask(0o077);
172+
try {
173+
await replaceFileAtomic({
174+
filePath,
175+
content: "injected",
176+
mode: 0o666,
177+
fileSystem: fsSync,
178+
});
179+
} finally {
180+
process.umask(previousUmask);
181+
}
182+
183+
await expect(fs.readFile(filePath, "utf8")).resolves.toBe("injected");
184+
expect((await fs.stat(filePath)).mode & 0o777).toBe(0o666);
185+
},
186+
);
187+
188+
it("fails closed before mutation when an injected sync filesystem cannot set an explicit mode", async () => {
169189
const root = await tempRoot("fs-safe-atomic-fchmod-missing-");
170-
const asyncPath = path.join(root, "async.txt");
171190
const syncPath = path.join(root, "sync.txt");
172-
const asyncDefaultPath = path.join(root, "async-default.txt");
173191
const syncDefaultPath = path.join(root, "sync-default.txt");
174192
const { fchmodSync: _fchmodSync, ...syncWithoutFchmod } = fsSync;
175193

176-
await expect(replaceFileAtomic({
177-
filePath: asyncPath,
178-
content: "async",
179-
mode: 0o600,
180-
fileSystem: { promises: { ...fs } },
181-
})).rejects.toThrow("fileSystem.promises.fchmod is required");
182194
expect(() => replaceFileAtomicSync({
183195
filePath: syncPath,
184196
content: "sync",
185197
mode: 0o600,
186198
fileSystem: syncWithoutFchmod,
187199
})).toThrow("fileSystem.fchmodSync is required");
188200

189-
await expect(fs.access(asyncPath)).rejects.toMatchObject({ code: "ENOENT" });
190201
await expect(fs.access(syncPath)).rejects.toMatchObject({ code: "ENOENT" });
191202

192-
await replaceFileAtomic({
193-
filePath: asyncDefaultPath,
194-
content: "async default",
195-
fileSystem: { promises: { ...fs } },
196-
});
197203
replaceFileAtomicSync({
198204
filePath: syncDefaultPath,
199205
content: "sync default",
200206
fileSystem: syncWithoutFchmod,
201207
});
202-
await expect(fs.readFile(asyncDefaultPath, "utf8")).resolves.toBe("async default");
203208
expect(fsSync.readFileSync(syncDefaultPath, "utf8")).toBe("sync default");
204209
});
205210
});

0 commit comments

Comments
 (0)