Open History to see the last commit
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("does not replace a newer save that landed while the lock was held", () =>
158 Effect.gen(function* () {
159 const fs = yield* FileSystem.FileSystem;
160 const path = yield* Path.Path;
161 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
162 const filePath = path.join(root, "settings.json");
163 yield* fs.writeFileString(filePath, "before");
164 const firstAttempt = yield* Deferred.make<void>();
165 let attempts = 0;
166 const lockedOnce = FileSystem.make({
167 ...fs,
168 rename: (from, to) =>
169 Effect.suspend(() => {
170 attempts += 1;
171 return attempts === 1
172 ? Deferred.succeed(firstAttempt, undefined).pipe(
173 Effect.andThen(Effect.fail(renameError("EBUSY", to))),
174 )
175 : fs.rename(from, to);
176 }),
177 });
178
179 const stale = yield* writeFileStringAtomically({ filePath, contents: "stale" }).pipe(
180 Effect.provideService(FileSystem.FileSystem, lockedOnce),
181 Effect.provideService(HostProcess.Platform, "win32"),
182 Effect.exit,
183 Effect.forkChild,
184 );
185 yield* Deferred.await(firstAttempt);
186 yield* writeFileStringAtomically({ filePath, contents: "newer" });
187
188 yield* TestClock.adjust("100 millis");
189 assert.isTrue(Exit.isFailure(yield* Fiber.join(stale)));
190 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
191 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
192 }),
193 );
194});
195
196const renameError = (code: string, path: string) =>
197 PlatformError.systemError({
198 _tag: "Unknown",
199 module: "FileSystem",
200 method: "rename",
201 pathOrDescriptor: path,
202 cause: Object.assign(new Error(`${code}, rename`), { code }),
203 });
204
205it.effect("surfaces an unreadable link instead of writing over it", () =>
206 Effect.gen(function* () {
207 const readLinkFailure = PlatformError.systemError({
208 _tag: "Unknown",
209 module: "FileSystem",
210 method: "readLink",
211 pathOrDescriptor: "/home/settings.json",
212 });
213
214 const failure = yield* writeFileStringAtomically({
215 filePath: "/home/settings.json",
216 contents: "after",
217 }).pipe(Effect.flip);
218
219 assert.deepStrictEqual(failure, readLinkFailure);
220 }).pipe(
221 Effect.provide(
222 Layer.mergeAll(
223 Path.layer,
224 FileSystem.layerNoop({
225 readLink: () =>
226 Effect.fail(
227 PlatformError.systemError({
228 _tag: "Unknown",
229 module: "FileSystem",
230 method: "readLink",
231 pathOrDescriptor: "/home/settings.json",
232 }),
233 ),
234 rename: () => Effect.die("an unreadable link must not be replaced"),
235 }),
236 ),
237 ),
238 ),
239);
240
241it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
242 Effect.gen(function* () {
243 const renamed: Array<string> = [];
244 const removed: Array<string> = [];
245 const fileSystem = FileSystem.layerNoop({
246 readLink: (path) =>
247 Effect.fail(
248 PlatformError.systemError({
249 _tag: "NotFound",
250 module: "FileSystem",
251 method: "readLink",
252 pathOrDescriptor: path,
253 }),
254 ),
255 makeDirectory: () => Effect.void,
256 makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
257 writeFileString: () => Effect.void,
258 rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
259 remove: (path) =>
260 Effect.sync(() => void removed.push(path)).pipe(
261 Effect.andThen(
262 Effect.fail(
263 PlatformError.systemError({
264 _tag: "PermissionDenied",
265 module: "FileSystem",
266 method: "remove",
267 pathOrDescriptor: path,
268 }),
269 ),
270 ),
271 ),
272 });
273
274 const result = yield* Effect.exit(
275 writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
276 Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
277 ),
278 );
279
280 assert.deepStrictEqual(result, Exit.void);
281 assert.deepStrictEqual(renamed, ["/home/settings.json"]);
282 assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
283 }),
284);