Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

atomicWrite.test.ts

235 lines9.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as TestClock from "effect/testing/TestClock";
12​
13import { writeFileStringAtomically } from "./atomicWrite.ts";
14import * as HostProcess from "./HostProcess.ts";
15​
16it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
17 it.effect("keeps a symlinked file linked and rewrites its destination", () =>
18 Effect.gen(function* () {
19 const fs = yield* FileSystem.FileSystem;
20 const path = yield* Path.Path;
21 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
22 const destination = path.join(root, "dotfiles", "settings.json");
23 const link = path.join(root, "home", "settings.json");
24 yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
25 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
26 yield* fs.writeFileString(destination, "before");
27 yield* fs.symlink(destination, link);
28​
29 yield* writeFileStringAtomically({ filePath: link, contents: "after" });
30​
31 assert.strictEqual(yield* fs.readLink(link), destination);
32 assert.strictEqual(yield* fs.readFileString(destination), "after");
33 }),
34 );
35​
36 it.effect("keeps a dangling symlink linked and creates its destination", () =>
37 Effect.gen(function* () {
38 const fs = yield* FileSystem.FileSystem;
39 const path = yield* Path.Path;
40 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
41 const destination = path.join(root, "dotfiles", "settings.json");
42 const link = path.join(root, "home", "settings.json");
43 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
44 yield* fs.symlink(destination, link);
45​
46 yield* writeFileStringAtomically({ filePath: link, contents: "fresh" });
47​
48 assert.strictEqual(yield* fs.readLink(link), destination);
49 assert.strictEqual(yield* fs.readFileString(destination), "fresh");
50 }),
51 );
52​
53 it.effect("fails on a symlink cycle without replacing either link", () =>
54 Effect.gen(function* () {
55 const fs = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
58 const first = path.join(root, "first.json");
59 const second = path.join(root, "second.json");
60 yield* fs.symlink(second, first);
61 yield* fs.symlink(first, second);
62​
63 const result = yield* Effect.exit(
64 writeFileStringAtomically({ filePath: first, contents: "after" }),
65 );
66​
67 assert.isTrue(Exit.isFailure(result));
68 assert.strictEqual(yield* fs.readLink(first), second);
69 assert.strictEqual(yield* fs.readLink(second), first);
70 }),
71 );
72​
73 it.effect("resolves a relative link through a symlinked parent directory", () =>
74 Effect.gen(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
78 const destination = path.join(root, "dotfiles", "config", "settings.json");
79 const linkedState = path.join(root, "dotfiles", "state");
80 const home = path.join(root, "home");
81 const link = path.join(home, "state", "settings.json");
82 yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
83 yield* fs.makeDirectory(linkedState, { recursive: true });
84 yield* fs.makeDirectory(home, { recursive: true });
85 yield* fs.symlink(linkedState, path.join(home, "state"));
86 yield* fs.writeFileString(destination, "before");
87 yield* fs.symlink("../config/settings.json", link);
88​
89 yield* writeFileStringAtomically({ filePath: link, contents: "after" });
90​
91 assert.strictEqual(yield* fs.readLink(link), "../config/settings.json");
92 assert.strictEqual(yield* fs.readFileString(destination), "after");
93 }),
94 );
95​
96 it.effect("does not replace a newer save that landed while the lock was held", () =>
97 Effect.gen(function* () {
98 const fs = yield* FileSystem.FileSystem;
99 const path = yield* Path.Path;
100 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
101 const filePath = path.join(root, "settings.json");
102 yield* fs.writeFileString(filePath, "before");
103 const firstAttempt = yield* Deferred.make<void>();
104 let attempts = 0;
105 const lockedOnce = FileSystem.make({
106 ...fs,
107 rename: (from, to) =>
108 Effect.suspend(() => {
109 attempts += 1;
110 return attempts === 1
111 ? Deferred.succeed(firstAttempt, undefined).pipe(
112 Effect.andThen(Effect.fail(renameError("EBUSY", to))),
113 )
114 : fs.rename(from, to);
115 }),
116 });
117​
118 const stale = yield* writeFileStringAtomically({ filePath, contents: "stale" }).pipe(
119 Effect.provideService(FileSystem.FileSystem, lockedOnce),
120 Effect.provideService(HostProcess.Platform, "win32"),
121 Effect.exit,
122 Effect.forkChild,
123 );
124 yield* Deferred.await(firstAttempt);
125 // Another process saves once the lock clears, before the waiting write retries.
126 yield* writeFileStringAtomically({ filePath, contents: "newer" });
127​
128 assert.isTrue(Exit.isFailure(yield* advanceUntilDone(stale)));
129 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
130 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
131 }),
132 );
133});
134​
135// Retries stat the real target between waits, and that I/O finishes outside the
136// test clock, so the clock moves one wait at a time until the write settles.
137const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
138 Effect.gen(function* () {
139 while (fiber.pollUnsafe() === undefined) {
140 yield* TestClock.adjust("100 millis");
141 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a macrotask boundary so the real stat I/O can finish; time moves only via TestClock
142 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
143 }
144 return yield* Fiber.join(fiber);
145 });
146​
147const renameError = (code: string, path: string) =>
148 PlatformError.systemError({
149 _tag: "Unknown",
150 module: "FileSystem",
151 method: "rename",
152 pathOrDescriptor: path,
153 cause: Object.assign(new Error(`${code}, rename`), { code }),
154 });
155​
156it.effect("surfaces an unreadable link instead of writing over it", () =>
157 Effect.gen(function* () {
158 const readLinkFailure = PlatformError.systemError({
159 _tag: "Unknown",
160 module: "FileSystem",
161 method: "readLink",
162 pathOrDescriptor: "/home/settings.json",
163 });
164​
165 const failure = yield* writeFileStringAtomically({
166 filePath: "/home/settings.json",
167 contents: "after",
168 }).pipe(Effect.flip);
169​
170 assert.deepStrictEqual(failure, readLinkFailure);
171 }).pipe(
172 Effect.provide(
173 Layer.mergeAll(
174 Path.layer,
175 FileSystem.layerNoop({
176 readLink: () =>
177 Effect.fail(
178 PlatformError.systemError({
179 _tag: "Unknown",
180 module: "FileSystem",
181 method: "readLink",
182 pathOrDescriptor: "/home/settings.json",
183 }),
184 ),
185 rename: () => Effect.die("an unreadable link must not be replaced"),
186 }),
187 ),
188 ),
189 ),
190);
191​
192it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
193 Effect.gen(function* () {
194 const renamed: Array<string> = [];
195 const removed: Array<string> = [];
196 const fileSystem = FileSystem.layerNoop({
197 readLink: (path) =>
198 Effect.fail(
199 PlatformError.systemError({
200 _tag: "NotFound",
201 module: "FileSystem",
202 method: "readLink",
203 pathOrDescriptor: path,
204 }),
205 ),
206 makeDirectory: () => Effect.void,
207 makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
208 writeFileString: () => Effect.void,
209 rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
210 remove: (path) =>
211 Effect.sync(() => void removed.push(path)).pipe(
212 Effect.andThen(
213 Effect.fail(
214 PlatformError.systemError({
215 _tag: "PermissionDenied",
216 module: "FileSystem",
217 method: "remove",
218 pathOrDescriptor: path,
219 }),
220 ),
221 ),
222 ),
223 });
224​
225 const result = yield* Effect.exit(
226 writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
227 Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
228 ),
229 );
230​
231 assert.deepStrictEqual(result, Exit.void);
232 assert.deepStrictEqual(renamed, ["/home/settings.json"]);
233 assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
234 }),
235);