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

atomicWrite.test.ts

487 lines19.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.each(HostProcess.Platform.defaultValue() === "linux" ? [39, 40, 41] : [])(
18 "matches native file access for a chain of %i symlinks",
19 (hops) =>
20 Effect.gen(function* () {
21 const fs = yield* FileSystem.FileSystem;
22 const path = yield* Path.Path;
23 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
24 const destination = path.join(root, "settings.json");
25 const first = path.join(root, "link-0");
26 yield* fs.writeFileString(destination, "before");
27 for (let index = hops - 1; index >= 0; index--) {
28 const target = index === hops - 1 ? "settings.json" : `link-${index + 1}`;
29 yield* fs.symlink(target, path.join(root, `link-${index}`));
30 }
31​
32 const read = yield* Effect.exit(fs.readFileString(first));
33 const write = yield* Effect.exit(
34 writeFileStringAtomically({ filePath: first, contents: "after" }),
35 );
36​
37 assert.strictEqual(Exit.isSuccess(read), hops <= 40);
38 assert.strictEqual(Exit.isSuccess(write), Exit.isSuccess(read));
39 assert.strictEqual(
40 yield* fs.readFileString(destination),
41 Exit.isSuccess(read) ? "after" : "before",
42 );
43 assert.strictEqual(yield* fs.readLink(first), "link-1");
44 }),
45 );
46​
47 it.effect("streams iterable contents across write batches", () =>
48 Effect.gen(function* () {
49 const fs = yield* FileSystem.FileSystem;
50 const path = yield* Path.Path;
51 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
52 const filePath = path.join(root, "cache.json");
53 yield* fs.writeFileString(filePath, "a much longer previous document");
54 const chunks = ["é".repeat(700_000), "🙂".repeat(400_000), "end"];
55​
56 yield* writeFileStringAtomically({ filePath, contents: chunks.values() });
57​
58 assert.strictEqual(yield* fs.readFileString(filePath), chunks.join(""));
59 assert.deepStrictEqual(yield* fs.readDirectory(root), ["cache.json"]);
60 }),
61 );
62​
63 it.effect("keeps a symlinked file linked and rewrites its destination", () =>
64 Effect.gen(function* () {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
68 const destination = path.join(root, "dotfiles", "settings.json");
69 const link = path.join(root, "home", "settings.json");
70 yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
71 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
72 yield* fs.writeFileString(destination, "before");
73 yield* fs.symlink(destination, link);
74​
75 yield* writeFileStringAtomically({ filePath: link, contents: "after" });
76​
77 assert.strictEqual(yield* fs.readLink(link), destination);
78 assert.strictEqual(yield* fs.readFileString(destination), "after");
79 }),
80 );
81​
82 it.effect.each(HostProcess.Platform.defaultValue() === "linux" ? [255] : [])(
83 "saves a file whose name is %i bytes long",
84 (length) =>
85 Effect.gen(function* () {
86 const fs = yield* FileSystem.FileSystem;
87 const path = yield* Path.Path;
88 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
89 const filePath = path.join(root, `${"s".repeat(length - 5)}.json`);
90​
91 yield* writeFileStringAtomically({ filePath, contents: "after" });
92​
93 assert.strictEqual(yield* fs.readFileString(filePath), "after");
94 }),
95 );
96​
97 it.effect("keeps a dangling symlink linked and creates its destination", () =>
98 Effect.gen(function* () {
99 const fs = yield* FileSystem.FileSystem;
100 const path = yield* Path.Path;
101 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
102 const destination = path.join(root, "dotfiles", "settings.json");
103 const link = path.join(root, "home", "settings.json");
104 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
105 yield* fs.symlink(destination, link);
106​
107 yield* writeFileStringAtomically({ filePath: link, contents: "fresh" });
108​
109 assert.strictEqual(yield* fs.readLink(link), destination);
110 assert.strictEqual(yield* fs.readFileString(destination), "fresh");
111 }),
112 );
113​
114 it.effect("fails on a symlink cycle without replacing either link", () =>
115 Effect.gen(function* () {
116 const fs = yield* FileSystem.FileSystem;
117 const path = yield* Path.Path;
118 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
119 const first = path.join(root, "first.json");
120 const second = path.join(root, "second.json");
121 yield* fs.symlink(second, first);
122 yield* fs.symlink(first, second);
123​
124 const result = yield* Effect.exit(
125 writeFileStringAtomically({ filePath: first, contents: "after" }),
126 );
127​
128 assert.isTrue(Exit.isFailure(result));
129 assert.strictEqual(yield* fs.readLink(first), second);
130 assert.strictEqual(yield* fs.readLink(second), first);
131 }),
132 );
133​
134 it.effect("resolves a relative link through a symlinked parent directory", () =>
135 Effect.gen(function* () {
136 const fs = yield* FileSystem.FileSystem;
137 const path = yield* Path.Path;
138 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
139 const destination = path.join(root, "dotfiles", "config", "settings.json");
140 const linkedState = path.join(root, "dotfiles", "state");
141 const home = path.join(root, "home");
142 const link = path.join(home, "state", "settings.json");
143 yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
144 yield* fs.makeDirectory(linkedState, { recursive: true });
145 yield* fs.makeDirectory(home, { recursive: true });
146 yield* fs.symlink(linkedState, path.join(home, "state"));
147 yield* fs.writeFileString(destination, "before");
148 yield* fs.symlink("../config/settings.json", link);
149​
150 yield* writeFileStringAtomically({ filePath: link, contents: "after" });
151​
152 assert.strictEqual(yield* fs.readLink(link), "../config/settings.json");
153 assert.strictEqual(yield* fs.readFileString(destination), "after");
154 }),
155 );
156​
157 it.effect.each(HostProcess.Platform.defaultValue() === "linux" ? [true, false] : [])(
158 "follows directory symlinks before '..' in a link target (destination exists: %s)",
159 (destinationExists) =>
160 Effect.gen(function* () {
161 const fs = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
164 const nested = path.join(root, "actual", "nested");
165 const link = path.join(root, "settings-link");
166 yield* fs.makeDirectory(nested, { recursive: true });
167 yield* fs.symlink("actual/nested", path.join(root, "alias"));
168 yield* fs.symlink("alias/../settings.json", link);
169 if (destinationExists) {
170 yield* fs.writeFileString(path.join(root, "actual", "settings.json"), "before");
171 }
172​
173 yield* writeFileStringAtomically({ filePath: link, contents: "after" });
174​
175 assert.strictEqual(yield* fs.readFileString(link), "after");
176 assert.isFalse(yield* fs.exists(path.join(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 yield* writeFileStringAtomically({ filePath, contents: "newer" });
210​
211 yield* TestClock.adjust("100 millis");
212 assert.isTrue(Exit.isFailure(yield* Fiber.join(stale)));
213 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
214 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
215 }),
216 );
217​
218 // Read-only and unreadable targets still save, since the mode lands after the temp file opens.
219 it.effect.each(HostProcess.Platform.defaultValue() === "win32" ? [] : ["644", "444", "000"])(
220 "keeps the %s permissions of the file it replaces",
221 (octal) =>
222 Effect.gen(function* () {
223 const fs = yield* FileSystem.FileSystem;
224 const path = yield* Path.Path;
225 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
226 const filePath = path.join(root, "settings.json");
227 const mode = Number.parseInt(octal, 8);
228 yield* fs.writeFileString(filePath, "before");
229 yield* fs.chmod(filePath, mode);
230​
231 yield* writeFileStringAtomically({ filePath, contents: "after" });
232​
233 assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, mode);
234 yield* fs.chmod(filePath, 0o600);
235 assert.strictEqual(yield* fs.readFileString(filePath), "after");
236 }),
237 );
238​
239 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
240 "creates a new file readable only by its owner",
241 () =>
242 Effect.gen(function* () {
243 const fs = yield* FileSystem.FileSystem;
244 const path = yield* Path.Path;
245 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
246 const filePath = path.join(root, "settings.json");
247​
248 yield* writeFileStringAtomically({ filePath, contents: "fresh" });
249​
250 assert.strictEqual(((yield* fs.stat(filePath)).mode & 0o777).toString(8), "600");
251 }),
252 );
253​
254 // Root ignores the missing read bit, so only a regular user sees the failure.
255 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)(
256 "saves when the umask removes owner read access",
257 () =>
258 Effect.gen(function* () {
259 const fs = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
262 const filePath = path.join(root, "settings.json");
263 yield* fs.writeFileString(filePath, "before");
264 yield* fs.chmod(filePath, 0o600);
265 yield* Effect.acquireRelease(
266 Effect.sync(() => process.umask(0o400)),
267 (previous) => Effect.sync(() => process.umask(previous)),
268 );
269​
270 yield* writeFileStringAtomically({ filePath, contents: "after" });
271​
272 assert.strictEqual(yield* fs.readFileString(filePath), "after");
273 assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, 0o600);
274 }),
275 );
276​
277 it.effect("syncs the contents before the rename and the directory after it", () =>
278 Effect.gen(function* () {
279 const fs = yield* FileSystem.FileSystem;
280 const path = yield* Path.Path;
281 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
282 const filePath = path.join(root, "settings.json");
283 const events: Array<string> = [];
284 const recording = FileSystem.make({
285 ...fs,
286 open: (openedPath, options) =>
287 fs.open(openedPath, options).pipe(
288 // The real handle keeps its methods on its prototype, so it is extended, not spread.
289 Effect.map((file): FileSystem.File =>
290 Object.create(file, {
291 sync: {
292 value: file.sync.pipe(
293 Effect.tap(() =>
294 Effect.sync(() => {
295 events.push(openedPath === root ? "sync directory" : "sync temp file");
296 }),
297 ),
298 ),
299 },
300 }),
301 ),
302 ),
303 rename: (from, to) =>
304 fs
305 .rename(from, to)
306 .pipe(
307 Effect.tap(() =>
308 Effect.sync(() =>
309 events.push(from === filePath ? "rename target" : "rename temp file"),
310 ),
311 ),
312 ),
313 });
314​
315 yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
316 Effect.provideService(FileSystem.FileSystem, recording),
317 );
318​
319 assert.strictEqual(yield* fs.readFileString(filePath), "after");
320 // Windows cannot open a directory to sync it.
321 assert.deepStrictEqual(
322 events,
323 HostProcess.Platform.defaultValue() === "win32"
324 ? ["sync temp file", "rename temp file"]
325 : ["sync temp file", "rename temp file", "sync directory"],
326 );
327 }),
328 );
329​
330 // EIO means the rename may not survive a crash; ENOTSUP means directories cannot sync at all.
331 it.effect.each(
332 HostProcess.Platform.defaultValue() === "win32"
333 ? []
334 : [
335 { code: "EIO", fails: true },
336 { code: "ENOTSUP", fails: false },
337 ],
338 )("handles a directory sync failing with $code after the rename", ({ code, fails }) =>
339 Effect.gen(function* () {
340 const fs = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
343 const filePath = path.join(root, "settings.json");
344 const syncFailure = PlatformError.systemError({
345 _tag: "Unknown",
346 module: "FileSystem",
347 method: "sync",
348 pathOrDescriptor: root,
349 cause: Object.assign(new Error(`${code}, fsync`), { code }),
350 });
351 const failingDirectorySync = FileSystem.make({
352 ...fs,
353 open: (openedPath, options) =>
354 fs
355 .open(openedPath, options)
356 .pipe(
357 Effect.map((file): FileSystem.File =>
358 openedPath === root
359 ? Object.create(file, { sync: { value: Effect.fail(syncFailure) } })
360 : file,
361 ),
362 ),
363 });
364​
365 const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
366 Effect.provideService(FileSystem.FileSystem, failingDirectorySync),
367 Effect.exit,
368 );
369​
370 assert.deepStrictEqual(exit, fails ? Exit.fail(syncFailure) : Exit.void);
371 assert.strictEqual(yield* fs.readFileString(filePath), "after");
372 }),
373 );
374​
375 // Injected because root ignores a chmod that drops read access.
376 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
377 "saves when its directory cannot be opened for the sync",
378 () =>
379 Effect.gen(function* () {
380 const fs = yield* FileSystem.FileSystem;
381 const path = yield* Path.Path;
382 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
383 const filePath = path.join(root, "settings.json");
384 yield* fs.writeFileString(filePath, "before");
385 const openFailure = PlatformError.systemError({
386 _tag: "PermissionDenied",
387 module: "FileSystem",
388 method: "open",
389 pathOrDescriptor: root,
390 });
391 const unopenableDirectory = FileSystem.make({
392 ...fs,
393 open: (openedPath, options) =>
394 openedPath === root ? Effect.fail(openFailure) : fs.open(openedPath, options),
395 });
396​
397 const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
398 Effect.provideService(FileSystem.FileSystem, unopenableDirectory),
399 Effect.exit,
400 );
401​
402 assert.deepStrictEqual(exit, Exit.void);
403 assert.strictEqual(yield* fs.readFileString(filePath), "after");
404 }),
405 );
406​
407 it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
408 Effect.gen(function* () {
409 const fs = yield* FileSystem.FileSystem;
410 const path = yield* Path.Path;
411 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
412 const filePath = path.join(root, "settings.json");
413 const removeAttempts: Array<string> = [];
414 const unremovable = FileSystem.make({
415 ...fs,
416 remove: (removedPath) =>
417 Effect.suspend(() => {
418 removeAttempts.push(removedPath);
419 return Effect.fail(
420 PlatformError.systemError({
421 _tag: "PermissionDenied",
422 module: "FileSystem",
423 method: "remove",
424 pathOrDescriptor: removedPath,
425 }),
426 );
427 }),
428 });
429​
430 yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
431 Effect.provideService(FileSystem.FileSystem, unremovable),
432 );
433​
434 assert.strictEqual(yield* fs.readFileString(filePath), "after");
435 assert.strictEqual(removeAttempts.length, 1);
436 assert.deepStrictEqual(
437 (yield* fs.readDirectory(root)).toSorted(),
438 [path.basename(removeAttempts[0]!), "settings.json"].toSorted(),
439 );
440 }),
441 );
442});
443​
444const renameError = (code: string, path: string) =>
445 PlatformError.systemError({
446 _tag: "Unknown",
447 module: "FileSystem",
448 method: "rename",
449 pathOrDescriptor: path,
450 cause: Object.assign(new Error(`${code}, rename`), { code }),
451 });
452​
453it.effect("surfaces an unreadable link instead of writing over it", () =>
454 Effect.gen(function* () {
455 const readLinkFailure = PlatformError.systemError({
456 _tag: "Unknown",
457 module: "FileSystem",
458 method: "readLink",
459 pathOrDescriptor: "/home/settings.json",
460 });
461​
462 const failure = yield* writeFileStringAtomically({
463 filePath: "/home/settings.json",
464 contents: "after",
465 }).pipe(Effect.flip);
466​
467 assert.deepStrictEqual(failure, readLinkFailure);
468 }).pipe(
469 Effect.provide(
470 Layer.mergeAll(
471 Path.layer,
472 FileSystem.layerNoop({
473 readLink: () =>
474 Effect.fail(
475 PlatformError.systemError({
476 _tag: "Unknown",
477 module: "FileSystem",
478 method: "readLink",
479 pathOrDescriptor: "/home/settings.json",
480 }),
481 ),
482 rename: () => Effect.die("an unreadable link must not be replaced"),
483 }),
484 ),
485 ),
486 ),
487);