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

atomicWrite.test.ts

234 lines8.9 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 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
142 }
143 return yield* Fiber.join(fiber);
144 });
145​
146const renameError = (code: string, path: string) =>
147 PlatformError.systemError({
148 _tag: "Unknown",
149 module: "FileSystem",
150 method: "rename",
151 pathOrDescriptor: path,
152 cause: Object.assign(new Error(`${code}, rename`), { code }),
153 });
154​
155it.effect("surfaces an unreadable link instead of writing over it", () =>
156 Effect.gen(function* () {
157 const readLinkFailure = PlatformError.systemError({
158 _tag: "Unknown",
159 module: "FileSystem",
160 method: "readLink",
161 pathOrDescriptor: "/home/settings.json",
162 });
163​
164 const failure = yield* writeFileStringAtomically({
165 filePath: "/home/settings.json",
166 contents: "after",
167 }).pipe(Effect.flip);
168​
169 assert.deepStrictEqual(failure, readLinkFailure);
170 }).pipe(
171 Effect.provide(
172 Layer.mergeAll(
173 Path.layer,
174 FileSystem.layerNoop({
175 readLink: () =>
176 Effect.fail(
177 PlatformError.systemError({
178 _tag: "Unknown",
179 module: "FileSystem",
180 method: "readLink",
181 pathOrDescriptor: "/home/settings.json",
182 }),
183 ),
184 rename: () => Effect.die("an unreadable link must not be replaced"),
185 }),
186 ),
187 ),
188 ),
189);
190​
191it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
192 Effect.gen(function* () {
193 const renamed: Array<string> = [];
194 const removed: Array<string> = [];
195 const fileSystem = FileSystem.layerNoop({
196 readLink: (path) =>
197 Effect.fail(
198 PlatformError.systemError({
199 _tag: "NotFound",
200 module: "FileSystem",
201 method: "readLink",
202 pathOrDescriptor: path,
203 }),
204 ),
205 makeDirectory: () => Effect.void,
206 makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
207 writeFileString: () => Effect.void,
208 rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
209 remove: (path) =>
210 Effect.sync(() => void removed.push(path)).pipe(
211 Effect.andThen(
212 Effect.fail(
213 PlatformError.systemError({
214 _tag: "PermissionDenied",
215 module: "FileSystem",
216 method: "remove",
217 pathOrDescriptor: path,
218 }),
219 ),
220 ),
221 ),
222 });
223​
224 const result = yield* Effect.exit(
225 writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
226 Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
227 ),
228 );
229​
230 assert.deepStrictEqual(result, Exit.void);
231 assert.deepStrictEqual(renamed, ["/home/settings.json"]);
232 assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
233 }),
234);