Skip to content
TypeScript

fix(shared): Windows saves no longer fail while a scanner holds the file (#21062)

Dara Adedeji9494dbaff62e
diff --git a/packages/shared/src/atomicWrite.test.ts b/packages/shared/src/atomicWrite.test.ts
index 1ff88296383..83d85b050d8 100644
--- a/packages/shared/src/atomicWrite.test.ts
+++ b/packages/shared/src/atomicWrite.test.ts
@@ -1,13 +1,17 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
+import * as TestClock from "effect/testing/TestClock";
import { writeFileStringAtomically } from "./atomicWrite.ts";
+import * as HostProcess from "./HostProcess.ts";
it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
it.effect("keeps a symlinked file linked and rewrites its destination", () =>
@@ -101,8 +105,169 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
assert.strictEqual(yield* fs.readFileString(filePath), "fresh");
}),
);
+
+ it.effect("waits out a Windows scanner holding the target, then replaces it", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
+ const filePath = path.join(root, "settings.json");
+ yield* fs.writeFileString(filePath, "before");
+ const firstAttempt = yield* Deferred.make<void>();
+ let attempts = 0;
+ const lockedTwice = FileSystem.make({
+ ...fs,
+ rename: (from, to) =>
+ Effect.suspend(() => {
+ attempts += 1;
+ return attempts <= 2
+ ? Deferred.succeed(firstAttempt, undefined).pipe(
+ Effect.andThen(Effect.fail(renameError("EBUSY", to))),
+ )
+ : fs.rename(from, to);
+ }),
+ });
+
+ const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
+ Effect.provideService(FileSystem.FileSystem, lockedTwice),
+ Effect.provideService(HostProcess.Platform, "win32"),
+ Effect.forkChild,
+ );
+ yield* Deferred.await(firstAttempt);
+ yield* advanceUntilDone(writing);
+
+ assert.strictEqual(attempts, 3);
+ assert.strictEqual(yield* fs.readFileString(filePath), "after");
+ assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
+ }),
+ );
+
+ it.effect("gives up on a Windows lock that does not clear and keeps the old contents", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
+ const filePath = path.join(root, "settings.json");
+ yield* fs.writeFileString(filePath, "before");
+ const firstAttempt = yield* Deferred.make<void>();
+ let attempts = 0;
+ const locked = FileSystem.make({
+ ...fs,
+ rename: (_from, to) =>
+ Effect.suspend(() => {
+ attempts += 1;
+ return Deferred.succeed(firstAttempt, undefined).pipe(
+ Effect.andThen(Effect.fail(renameError("EPERM", to))),
+ );
+ }),
+ });
+
+ const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
+ Effect.provideService(FileSystem.FileSystem, locked),
+ Effect.provideService(HostProcess.Platform, "win32"),
+ Effect.exit,
+ Effect.forkChild,
+ );
+ yield* Deferred.await(firstAttempt);
+
+ assert.isTrue(Exit.isFailure(yield* advanceUntilDone(writing)));
+ assert.isAbove(attempts, 1);
+ assert.strictEqual(yield* fs.readFileString(filePath), "before");
+ assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
+ }),
+ );
+
+ it.effect("does not replace a newer save that landed while the lock was held", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
+ const filePath = path.join(root, "settings.json");
+ yield* fs.writeFileString(filePath, "before");
+ const firstAttempt = yield* Deferred.make<void>();
+ let attempts = 0;
+ const lockedOnce = FileSystem.make({
+ ...fs,
+ rename: (from, to) =>
+ Effect.suspend(() => {
+ attempts += 1;
+ return attempts === 1
+ ? Deferred.succeed(firstAttempt, undefined).pipe(
+ Effect.andThen(Effect.fail(renameError("EBUSY", to))),
+ )
+ : fs.rename(from, to);
+ }),
+ });
+
+ const stale = yield* writeFileStringAtomically({ filePath, contents: "stale" }).pipe(
+ Effect.provideService(FileSystem.FileSystem, lockedOnce),
+ Effect.provideService(HostProcess.Platform, "win32"),
+ Effect.exit,
+ Effect.forkChild,
+ );
+ yield* Deferred.await(firstAttempt);
+ // Another process saves once the lock clears, before the waiting write retries.
+ yield* writeFileStringAtomically({ filePath, contents: "newer" });
+
+ assert.isTrue(Exit.isFailure(yield* advanceUntilDone(stale)));
+ assert.strictEqual(yield* fs.readFileString(filePath), "newer");
+ assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
+ }),
+ );
+
+ it.effect("fails at once on a read-only Windows target", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
+ const filePath = path.join(root, "settings.json");
+ yield* fs.writeFileString(filePath, "before");
+ yield* Effect.acquireRelease(fs.chmod(filePath, 0o444), () =>
+ fs.chmod(filePath, 0o644).pipe(Effect.ignore),
+ );
+ let attempts = 0;
+ const denied = FileSystem.make({
+ ...fs,
+ rename: (_from, to) =>
+ Effect.suspend(() => {
+ attempts += 1;
+ return Effect.fail(renameError("EPERM", to));
+ }),
+ });
+
+ const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
+ Effect.provideService(FileSystem.FileSystem, denied),
+ Effect.provideService(HostProcess.Platform, "win32"),
+ Effect.exit,
+ Effect.forkChild,
+ );
+ assert.isTrue(Exit.isFailure(yield* advanceUntilDone(writing)));
+ assert.strictEqual(attempts, 1);
+ assert.strictEqual(yield* fs.readFileString(filePath), "before");
+ }),
+ );
});
+// Retries stat the real target between waits, and that I/O finishes outside the
+// test clock, so the clock moves one wait at a time until the write settles.
+const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
+ Effect.gen(function* () {
+ while (fiber.pollUnsafe() === undefined) {
+ yield* TestClock.adjust("100 millis");
+ yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
+ }
+ return yield* Fiber.join(fiber);
+ });
+
+const renameError = (code: string, path: string) =>
+ PlatformError.systemError({
+ _tag: "Unknown",
+ module: "FileSystem",
+ method: "rename",
+ pathOrDescriptor: path,
+ cause: Object.assign(new Error(`${code}, rename`), { code }),
+ });
+
it.effect("surfaces an unreadable link instead of writing over it", () =>
Effect.gen(function* () {
const readLinkFailure = PlatformError.systemError({
diff --git a/packages/shared/src/atomicWrite.ts b/packages/shared/src/atomicWrite.ts
index 23a84429a33..709614d86fd 100644
--- a/packages/shared/src/atomicWrite.ts
+++ b/packages/shared/src/atomicWrite.ts
@@ -1,8 +1,27 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
+import * as Option from "effect/Option";
import * as Path from "effect/Path";
+import type * as PlatformError from "effect/PlatformError";
+import * as Result from "effect/Result";
+import * as HostProcess from "@t3tools/shared/HostProcess";
import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
+/**
+ * Windows refuses to rename over or away from a file another process holds open
+ * without delete sharing, such as a virus scanner or the search indexer. The same
+ * codes also mean a denial that never clears, so retries need a bound.
+ */
+export const isWindowsRenameLock = (error: PlatformError.PlatformError) => {
+ const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
+ return code === "EBUSY" || code === "EPERM" || code === "EACCES";
+};
+
+// About 2 seconds in total. Settings and keybinding saves wait on this while holding
+// their write lock, so a denial that is not a brief scan has to surface quickly.
+const LOCKED_RENAME_RETRIES = 20;
+const LOCKED_RENAME_RETRY_DELAY = "100 millis";
+
/**
* A symlinked target is resolved first so the link survives and its destination is
* rewritten, since renaming over the link itself would swap it for a regular file.
@@ -15,6 +34,7 @@ export const writeFileStringAtomically = (input: {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
+ const platform = yield* HostProcess.Platform;
const targetPath = yield* resolveSymlinkTarget(input.filePath);
const targetDirectory = path.dirname(targetPath);
@@ -32,6 +52,37 @@ export const writeFileStringAtomically = (input: {
const tempPath = path.join(tempDirectory, "contents.tmp");
yield* fs.writeFileString(tempPath, input.contents);
- yield* fs.rename(tempPath, targetPath);
+ if (platform !== "win32") return yield* fs.rename(tempPath, targetPath);
+
+ // A retry must not replace a save another process landed while this one
+ // waited, so it gives up once the target is no longer the file seen here.
+ // A read-only target fails with the same EPERM as a held one but never clears.
+ const targetVersion = fs.stat(targetPath).pipe(
+ Effect.map((info) => ({
+ id: `${Option.getOrUndefined(info.ino)}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`,
+ readOnly: (info.mode & 0o200) === 0,
+ })),
+ Effect.catchIf(
+ (error) => error.reason._tag === "NotFound",
+ () => Effect.succeed({ id: "missing", readOnly: false }),
+ ),
+ Effect.option,
+ );
+ const before = yield* targetVersion;
+ const firstAttempt = yield* Effect.result(fs.rename(tempPath, targetPath));
+ if (Result.isSuccess(firstAttempt)) return;
+ const lockError = firstAttempt.failure;
+ if (!isWindowsRenameLock(lockError) || Option.isNone(before) || before.value.readOnly) {
+ return yield* lockError;
+ }
+ for (let retry = 0; retry < LOCKED_RENAME_RETRIES; retry += 1) {
+ yield* Effect.sleep(LOCKED_RENAME_RETRY_DELAY);
+ const current = yield* targetVersion;
+ if (Option.isNone(current) || current.value.id !== before.value.id) break;
+ const attempt = yield* Effect.result(fs.rename(tempPath, targetPath));
+ if (Result.isSuccess(attempt)) return;
+ if (!isWindowsRenameLock(attempt.failure)) return yield* attempt.failure;
+ }
+ return yield* lockError;
}),
);
diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts
index 6e13806e2fa..09a901d1068 100644
--- a/packages/shared/src/relayClient.ts
+++ b/packages/shared/src/relayClient.ts
@@ -21,6 +21,7 @@ import * as Schedule from "effect/Schedule";
import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
+import { isWindowsRenameLock } from "./atomicWrite.ts";
import * as HostProcess from "./HostProcess.ts";
export const CLOUDFLARED_VERSION = "2026.10.0";
@@ -199,13 +200,6 @@ function isAlreadyExists(error: PlatformError.PlatformError): boolean {
return error.reason._tag === "AlreadyExists";
}
-// Windows refuses to rename a file another process briefly holds open, such as a virus
-// scanner reading the binary that just ran. These codes clear once it lets go.
-function isTransientWindowsLock(error: PlatformError.PlatformError): boolean {
- const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
- return code === "EBUSY" || code === "EPERM" || code === "EACCES";
-}
-
const wrapInstallFailure =
(
reason: RelayClientInstallError["reason"],
@@ -400,7 +394,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
Effect.retry({
times: ACTIVATE_RETRY_COUNT,
schedule: Schedule.spaced(ACTIVATE_RETRY_DELAY),
- while: (error) => platform === "win32" && isTransientWindowsLock(error),
+ while: (error) => platform === "win32" && isWindowsRenameLock(error),
}),
);