Open History to see the last commit
1import assert from "node:assert/strict";
2import { mkdtemp, readFile, writeFile, rm, access } from "node:fs/promises";
3import os from "node:os";
4import path from "node:path";
5import { spawn } from "node:child_process";
6import test from "node:test";
7
8const isWindows = process.platform === "win32";
9
10async function waitForFile(filePath, timeoutMs = 5_000) {
11 const started = Date.now();
12 while (Date.now() - started < timeoutMs) {
13 try {
14 await access(filePath);
15 return;
16 } catch {
17 await new Promise((resolve) => setTimeout(resolve, 25));
18 }
19 }
20 throw new Error(`Timed out waiting for ${filePath}`);
21}
22
23test(
24 "Windows atomic replacement survives a temporarily exclusive target handle",
25 { skip: !isWindows },
26 async () => {
27 const [Effect, FileSystem, NodeServices, retryModule] = await Promise.all([
28 import("effect/Effect"),
29 import("effect/FileSystem"),
30 import("@effect/platform-node/NodeServices"),
31 import("../packages/shared/src/windowsFileRetry.ts"),
32 ]);
33 const root = await mkdtemp(path.join(os.tmpdir(), "t3-persist-Ω-"));
34 const target = path.join(root, "state José", "desktop-settings.json");
35 const temporary = `${target}.next.tmp`;
36 const ready = path.join(root, "lock-ready.txt");
37 const ps1 = path.join(root, "hold-lock.ps1");
38 await writeFile(target, "before\n", { recursive: false }).catch(async (error) => {
39 if (error?.code !== "ENOENT") throw error;
40 const { mkdir } = await import("node:fs/promises");
41 await mkdir(path.dirname(target), { recursive: true });
42 await writeFile(target, "before\n");
43 });
44 await writeFile(temporary, "after\n");
45 await writeFile(
46 ps1,
47 [
48 "param([string]$Target, [string]$Ready)",
49 "$stream = [System.IO.File]::Open($Target, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)",
50 "try {",
51 " [System.IO.File]::WriteAllText($Ready, 'ready')",
52 " Start-Sleep -Milliseconds 700",
53 "} finally {",
54 " $stream.Dispose()",
55 "}",
56 ].join("\r\n"),
57 );
58
59 const locker = spawn(
60 "powershell.exe",
61 ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", ps1, target, ready],
62 { stdio: ["ignore", "pipe", "pipe"] },
63 );
64 let stderr = "";
65 locker.stderr.setEncoding("utf8");
66 locker.stderr.on("data", (chunk) => {
67 stderr += chunk;
68 });
69
70 try {
71 await waitForFile(ready);
72 let attempts = 0;
73 await Effect.runPromise(
74 Effect.gen(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 yield* retryModule.retryWindowsFileSystemOperation(
77 Effect.suspend(() => {
78 attempts += 1;
79 return fs.rename(temporary, target);
80 }),
81 );
82 }).pipe(Effect.provide(NodeServices.layer)),
83 );
84 const exitCode = await new Promise((resolve, reject) => {
85 locker.once("error", reject);
86 locker.once("exit", resolve);
87 });
88 assert.equal(exitCode, 0, stderr);
89 assert.ok(attempts > 1, `expected a Windows sharing violation retry, attempts=${attempts}`);
90 assert.equal(await readFile(target, "utf8"), "after\n");
91 } finally {
92 if (locker.exitCode === null) locker.kill();
93 await rm(root, { recursive: true, force: true });
94 }
95 },
96);