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

atomicWrite.test.ts

350 lines13.3 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("creates a missing file and its directory", () =>
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, "nested", "settings.json");
102​
103 yield* writeFileStringAtomically({ filePath, contents: "fresh" });
104​
105 assert.strictEqual(yield* fs.readFileString(filePath), "fresh");
106 }),
107 );
108​
109 it.effect("waits out a Windows scanner holding the target, then replaces it", () =>
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 lockedTwice = 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, lockedTwice),
133 Effect.provideService(HostProcess.Platform, "win32"),
134 Effect.forkChild,
135 );
136 yield* Deferred.await(firstAttempt);
137 yield* advanceUntilDone(writing);
138​
139 assert.strictEqual(attempts, 3);
140 assert.strictEqual(yield* fs.readFileString(filePath), "after");
141 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
142 }),
143 );
144​
145 it.effect("gives up on a Windows lock that does not clear and keeps the old contents", () =>
146 Effect.gen(function* () {
147 const fs = yield* FileSystem.FileSystem;
148 const path = yield* Path.Path;
149 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
150 const filePath = path.join(root, "settings.json");
151 yield* fs.writeFileString(filePath, "before");
152 const firstAttempt = yield* Deferred.make<void>();
153 let attempts = 0;
154 const locked = FileSystem.make({
155 ...fs,
156 rename: (_from, to) =>
157 Effect.suspend(() => {
158 attempts += 1;
159 return Deferred.succeed(firstAttempt, undefined).pipe(
160 Effect.andThen(Effect.fail(renameError("EPERM", to))),
161 );
162 }),
163 });
164​
165 const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
166 Effect.provideService(FileSystem.FileSystem, locked),
167 Effect.provideService(HostProcess.Platform, "win32"),
168 Effect.exit,
169 Effect.forkChild,
170 );
171 yield* Deferred.await(firstAttempt);
172​
173 assert.isTrue(Exit.isFailure(yield* advanceUntilDone(writing)));
174 assert.isAbove(attempts, 1);
175 assert.strictEqual(yield* fs.readFileString(filePath), "before");
176 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
177 }),
178 );
179​
180 it.effect("does not replace a newer save that landed while the lock was held", () =>
181 Effect.gen(function* () {
182 const fs = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
185 const filePath = path.join(root, "settings.json");
186 yield* fs.writeFileString(filePath, "before");
187 const firstAttempt = yield* Deferred.make<void>();
188 let attempts = 0;
189 const lockedOnce = FileSystem.make({
190 ...fs,
191 rename: (from, to) =>
192 Effect.suspend(() => {
193 attempts += 1;
194 return attempts === 1
195 ? Deferred.succeed(firstAttempt, undefined).pipe(
196 Effect.andThen(Effect.fail(renameError("EBUSY", to))),
197 )
198 : fs.rename(from, to);
199 }),
200 });
201​
202 const stale = yield* writeFileStringAtomically({ filePath, contents: "stale" }).pipe(
203 Effect.provideService(FileSystem.FileSystem, lockedOnce),
204 Effect.provideService(HostProcess.Platform, "win32"),
205 Effect.exit,
206 Effect.forkChild,
207 );
208 yield* Deferred.await(firstAttempt);
209 // Another process saves once the lock clears, before the waiting write retries.
210 yield* writeFileStringAtomically({ filePath, contents: "newer" });
211​
212 assert.isTrue(Exit.isFailure(yield* advanceUntilDone(stale)));
213 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
214 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
215 }),
216 );
217​
218 it.effect("fails at once on a read-only Windows target", () =>
219 Effect.gen(function* () {
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
223 const filePath = path.join(root, "settings.json");
224 yield* fs.writeFileString(filePath, "before");
225 yield* Effect.acquireRelease(fs.chmod(filePath, 0o444), () =>
226 fs.chmod(filePath, 0o644).pipe(Effect.ignore),
227 );
228 let attempts = 0;
229 const denied = FileSystem.make({
230 ...fs,
231 rename: (_from, to) =>
232 Effect.suspend(() => {
233 attempts += 1;
234 return Effect.fail(renameError("EPERM", to));
235 }),
236 });
237​
238 const writing = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
239 Effect.provideService(FileSystem.FileSystem, denied),
240 Effect.provideService(HostProcess.Platform, "win32"),
241 Effect.exit,
242 Effect.forkChild,
243 );
244 assert.isTrue(Exit.isFailure(yield* advanceUntilDone(writing)));
245 assert.strictEqual(attempts, 1);
246 assert.strictEqual(yield* fs.readFileString(filePath), "before");
247 }),
248 );
249});
250​
251// Retries stat the real target between waits, and that I/O finishes outside the
252// test clock, so the clock moves one wait at a time until the write settles.
253const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
254 Effect.gen(function* () {
255 while (fiber.pollUnsafe() === undefined) {
256 yield* TestClock.adjust("100 millis");
257 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
258 }
259 return yield* Fiber.join(fiber);
260 });
261​
262const renameError = (code: string, path: string) =>
263 PlatformError.systemError({
264 _tag: "Unknown",
265 module: "FileSystem",
266 method: "rename",
267 pathOrDescriptor: path,
268 cause: Object.assign(new Error(`${code}, rename`), { code }),
269 });
270​
271it.effect("surfaces an unreadable link instead of writing over it", () =>
272 Effect.gen(function* () {
273 const readLinkFailure = PlatformError.systemError({
274 _tag: "Unknown",
275 module: "FileSystem",
276 method: "readLink",
277 pathOrDescriptor: "/home/settings.json",
278 });
279​
280 const failure = yield* writeFileStringAtomically({
281 filePath: "/home/settings.json",
282 contents: "after",
283 }).pipe(Effect.flip);
284​
285 assert.deepStrictEqual(failure, readLinkFailure);
286 }).pipe(
287 Effect.provide(
288 Layer.mergeAll(
289 Path.layer,
290 FileSystem.layerNoop({
291 readLink: () =>
292 Effect.fail(
293 PlatformError.systemError({
294 _tag: "Unknown",
295 module: "FileSystem",
296 method: "readLink",
297 pathOrDescriptor: "/home/settings.json",
298 }),
299 ),
300 rename: () => Effect.die("an unreadable link must not be replaced"),
301 }),
302 ),
303 ),
304 ),
305);
306​
307it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
308 Effect.gen(function* () {
309 const renamed: Array<string> = [];
310 const removed: Array<string> = [];
311 const fileSystem = FileSystem.layerNoop({
312 readLink: (path) =>
313 Effect.fail(
314 PlatformError.systemError({
315 _tag: "NotFound",
316 module: "FileSystem",
317 method: "readLink",
318 pathOrDescriptor: path,
319 }),
320 ),
321 makeDirectory: () => Effect.void,
322 makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
323 writeFileString: () => Effect.void,
324 rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
325 remove: (path) =>
326 Effect.sync(() => void removed.push(path)).pipe(
327 Effect.andThen(
328 Effect.fail(
329 PlatformError.systemError({
330 _tag: "PermissionDenied",
331 module: "FileSystem",
332 method: "remove",
333 pathOrDescriptor: path,
334 }),
335 ),
336 ),
337 ),
338 });
339​
340 const result = yield* Effect.exit(
341 writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
342 Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
343 ),
344 );
345​
346 assert.deepStrictEqual(result, Exit.void);
347 assert.deepStrictEqual(renamed, ["/home/settings.json"]);
348 assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
349 }),
350);