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

atomicWrite.test.ts

233 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 yield* writeFileStringAtomically({ filePath, contents: "newer" });
126​
127 assert.isTrue(Exit.isFailure(yield* advanceUntilDone(stale)));
128 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
129 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
130 }),
131 );
132});
133​
134// Advance one retry at a time because real target-stat I/O runs outside the test clock.
135const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
136 Effect.gen(function* () {
137 while (fiber.pollUnsafe() === undefined) {
138 yield* TestClock.adjust("100 millis");
139 // 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
140 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
141 }
142 return yield* Fiber.join(fiber);
143 });
144​
145const renameError = (code: string, path: string) =>
146 PlatformError.systemError({
147 _tag: "Unknown",
148 module: "FileSystem",
149 method: "rename",
150 pathOrDescriptor: path,
151 cause: Object.assign(new Error(`${code}, rename`), { code }),
152 });
153​
154it.effect("surfaces an unreadable link instead of writing over it", () =>
155 Effect.gen(function* () {
156 const readLinkFailure = PlatformError.systemError({
157 _tag: "Unknown",
158 module: "FileSystem",
159 method: "readLink",
160 pathOrDescriptor: "/home/settings.json",
161 });
162​
163 const failure = yield* writeFileStringAtomically({
164 filePath: "/home/settings.json",
165 contents: "after",
166 }).pipe(Effect.flip);
167​
168 assert.deepStrictEqual(failure, readLinkFailure);
169 }).pipe(
170 Effect.provide(
171 Layer.mergeAll(
172 Path.layer,
173 FileSystem.layerNoop({
174 readLink: () =>
175 Effect.fail(
176 PlatformError.systemError({
177 _tag: "Unknown",
178 module: "FileSystem",
179 method: "readLink",
180 pathOrDescriptor: "/home/settings.json",
181 }),
182 ),
183 rename: () => Effect.die("an unreadable link must not be replaced"),
184 }),
185 ),
186 ),
187 ),
188);
189​
190it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
191 Effect.gen(function* () {
192 const renamed: Array<string> = [];
193 const removed: Array<string> = [];
194 const fileSystem = FileSystem.layerNoop({
195 readLink: (path) =>
196 Effect.fail(
197 PlatformError.systemError({
198 _tag: "NotFound",
199 module: "FileSystem",
200 method: "readLink",
201 pathOrDescriptor: path,
202 }),
203 ),
204 makeDirectory: () => Effect.void,
205 makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
206 writeFileString: () => Effect.void,
207 rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
208 remove: (path) =>
209 Effect.sync(() => void removed.push(path)).pipe(
210 Effect.andThen(
211 Effect.fail(
212 PlatformError.systemError({
213 _tag: "PermissionDenied",
214 module: "FileSystem",
215 method: "remove",
216 pathOrDescriptor: path,
217 }),
218 ),
219 ),
220 ),
221 });
222​
223 const result = yield* Effect.exit(
224 writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
225 Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
226 ),
227 );
228​
229 assert.deepStrictEqual(result, Exit.void);
230 assert.deepStrictEqual(renamed, ["/home/settings.json"]);
231 assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
232 }),
233);