Skip to content

Commit f2f463b

Browse files
yaacovcorcosclaude
andcommitted
fix(server): Windows saves no longer fail while a scanner holds the file
On Windows, replacing a file fails with EPERM, EACCES, or EBUSY while another process such as a virus scanner or the search indexer briefly has it open. writeFileStringAtomically renamed the temp file over the target once, so settings, keybindings, and cache writes failed outright. Retry the rename on those codes on Windows with a short capped backoff (about 3 seconds in total). Other errors and other platforms still fail at once, and the target keeps its old contents until a rename succeeds. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 9bd1d80 commit f2f463b

2 files changed

Lines changed: 143 additions & 1 deletion

File tree

‎apps/server/src/atomicWrite.test.ts‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
23
import { assert, it } from "@effect/vitest";
4+
import * as Deferred from "effect/Deferred";
35
import * as Effect from "effect/Effect";
46
import * as Exit from "effect/Exit";
7+
import * as Fiber from "effect/Fiber";
58
import * as FileSystem from "effect/FileSystem";
69
import * as Layer from "effect/Layer";
710
import * as Path from "effect/Path";
811
import * as PlatformError from "effect/PlatformError";
12+
import * as TestClock from "effect/testing/TestClock";
913

1014
import { writeFileStringAtomically } from "./atomicWrite.ts";
1115

@@ -101,6 +105,113 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
101105
assert.strictEqual(yield* fs.readFileString(filePath), "fresh");
102106
}),
103107
);
108+
109+
it.effect("retries a Windows replacement while another process holds the target", () =>
110+
Effect.gen(function* () {
111+
const fs = yield* FileSystem.FileSystem;
112+
const path = yield* Path.Path;
113+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
114+
const filePath = path.join(root, "settings.json");
115+
yield* fs.writeFileString(filePath, "before");
116+
const firstAttempt = yield* Deferred.make<void>();
117+
let attempts = 0;
118+
const lockedOnce = FileSystem.make({
119+
...fs,
120+
rename: (from, to) =>
121+
Effect.suspend(() => {
122+
attempts += 1;
123+
return attempts <= 2
124+
? Deferred.succeed(firstAttempt, undefined).pipe(
125+
Effect.andThen(Effect.fail(renameError("EBUSY", to))),
126+
)
127+
: fs.rename(from, to);
128+
}),
129+
});
130+
131+
const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
132+
Effect.provideService(FileSystem.FileSystem, lockedOnce),
133+
Effect.provideService(HostProcessPlatform, "win32"),
134+
Effect.forkChild,
135+
);
136+
yield* Deferred.await(firstAttempt);
137+
yield* TestClock.adjust("1 second");
138+
yield* Fiber.join(writing);
139+
140+
assert.strictEqual(attempts, 3);
141+
assert.strictEqual(yield* fs.readFileString(filePath), "after");
142+
assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
143+
}),
144+
);
145+
146+
it.effect("gives up on a Windows lock that does not clear and keeps the old contents", () =>
147+
Effect.gen(function* () {
148+
const fs = yield* FileSystem.FileSystem;
149+
const path = yield* Path.Path;
150+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
151+
const filePath = path.join(root, "settings.json");
152+
yield* fs.writeFileString(filePath, "before");
153+
const firstAttempt = yield* Deferred.make<void>();
154+
let attempts = 0;
155+
const locked = FileSystem.make({
156+
...fs,
157+
rename: (_from, to) =>
158+
Effect.suspend(() => {
159+
attempts += 1;
160+
return Deferred.succeed(firstAttempt, undefined).pipe(
161+
Effect.andThen(Effect.fail(renameError("EPERM", to))),
162+
);
163+
}),
164+
});
165+
166+
const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
167+
Effect.provideService(FileSystem.FileSystem, locked),
168+
Effect.provideService(HostProcessPlatform, "win32"),
169+
Effect.exit,
170+
Effect.forkChild,
171+
);
172+
yield* Deferred.await(firstAttempt);
173+
yield* TestClock.adjust("1 minute");
174+
175+
assert.isTrue(Exit.isFailure(yield* Fiber.join(writing)));
176+
assert.isAbove(attempts, 1);
177+
assert.strictEqual(yield* fs.readFileString(filePath), "before");
178+
assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
179+
}),
180+
);
181+
182+
it.effect("fails a rename at once outside Windows or for other errors", () =>
183+
Effect.gen(function* () {
184+
const fs = yield* FileSystem.FileSystem;
185+
const path = yield* Path.Path;
186+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
187+
for (const [platform, code] of [
188+
["linux", "EPERM"],
189+
["win32", "EXDEV"],
190+
] as const) {
191+
let attempts = 0;
192+
const failing = FileSystem.make({
193+
...fs,
194+
rename: (_from, to) =>
195+
Effect.suspend(() => {
196+
attempts += 1;
197+
return Effect.fail(renameError(code, to));
198+
}),
199+
});
200+
201+
const result = yield* writeFileStringAtomically({
202+
filePath: path.join(root, `${platform}.json`),
203+
contents: "after",
204+
}).pipe(
205+
Effect.provideService(FileSystem.FileSystem, failing),
206+
Effect.provideService(HostProcessPlatform, platform),
207+
Effect.exit,
208+
);
209+
210+
assert.isTrue(Exit.isFailure(result));
211+
assert.strictEqual(attempts, 1);
212+
}
213+
}),
214+
);
104215
});
105216

106217
it.effect("surfaces an unreadable link instead of writing over it", () =>
@@ -183,3 +294,12 @@ it.effect("succeeds when the write lands but its temp directory cannot be remove
183294
assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
184295
}),
185296
);
297+
298+
const renameError = (code: string, path: string) =>
299+
PlatformError.systemError({
300+
_tag: "Unknown",
301+
module: "FileSystem",
302+
method: "rename",
303+
pathOrDescriptor: path,
304+
cause: Object.assign(new Error(`${code}, rename`), { code }),
305+
});

‎apps/server/src/atomicWrite.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
1+
import * as Duration from "effect/Duration";
12
import * as Effect from "effect/Effect";
23
import * as FileSystem from "effect/FileSystem";
34
import * as Path from "effect/Path";
5+
import type * as PlatformError from "effect/PlatformError";
6+
import * as Schedule from "effect/Schedule";
7+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
48
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
59

10+
// Windows refuses to replace a file another process briefly holds open, such as
11+
// a virus scanner or the search indexer. These codes clear once it lets go.
12+
const isTransientWindowsLock = (error: PlatformError.PlatformError) => {
13+
const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
14+
return code === "EPERM" || code === "EACCES" || code === "EBUSY";
15+
};
16+
617
/**
718
* Replaces a file's contents via a sibling temp file and rename. A symlinked
819
* target is resolved first so the link survives and its destination is
@@ -16,6 +27,7 @@ export const writeFileStringAtomically = (input: {
1627
Effect.gen(function* () {
1728
const fs = yield* FileSystem.FileSystem;
1829
const path = yield* Path.Path;
30+
const platform = yield* HostProcessPlatform;
1931
const targetPath = yield* resolveSymlinkTarget(input.filePath);
2032
const targetDirectory = path.dirname(targetPath);
2133

@@ -33,6 +45,16 @@ export const writeFileStringAtomically = (input: {
3345
const tempPath = path.join(tempDirectory, "contents.tmp");
3446

3547
yield* fs.writeFileString(tempPath, input.contents);
36-
yield* fs.rename(tempPath, targetPath);
48+
yield* fs.rename(tempPath, targetPath).pipe(
49+
Effect.retry({
50+
times: 10,
51+
while: (error) => platform === "win32" && isTransientWindowsLock(error),
52+
schedule: Schedule.exponential("25 millis").pipe(
53+
Schedule.modifyDelay(({ duration }) =>
54+
Effect.succeed(Duration.min(duration, Duration.millis(500))),
55+
),
56+
),
57+
}),
58+
);
3759
}),
3860
);

0 commit comments

Comments
 (0)