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("keeps a dangling symlink linked and creates its destination", () =>
83 Effect.gen(function* () {
84 const fs = yield* FileSystem.FileSystem;
85 const path = yield* Path.Path;
86 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
87 const destination = path.join(root, "dotfiles", "settings.json");
88 const link = path.join(root, "home", "settings.json");
89 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
90 yield* fs.symlink(destination, link);
91
92 yield* writeFileStringAtomically({ filePath: link, contents: "fresh" });
93
94 assert.strictEqual(yield* fs.readLink(link), destination);
95 assert.strictEqual(yield* fs.readFileString(destination), "fresh");
96 }),
97 );
98
99 it.effect("fails on a symlink cycle without replacing either link", () =>
100 Effect.gen(function* () {
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
104 const first = path.join(root, "first.json");
105 const second = path.join(root, "second.json");
106 yield* fs.symlink(second, first);
107 yield* fs.symlink(first, second);
108
109 const result = yield* Effect.exit(
110 writeFileStringAtomically({ filePath: first, contents: "after" }),
111 );
112
113 assert.isTrue(Exit.isFailure(result));
114 assert.strictEqual(yield* fs.readLink(first), second);
115 assert.strictEqual(yield* fs.readLink(second), first);
116 }),
117 );
118
119 it.effect("resolves a relative link through a symlinked parent directory", () =>
120 Effect.gen(function* () {
121 const fs = yield* FileSystem.FileSystem;
122 const path = yield* Path.Path;
123 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
124 const destination = path.join(root, "dotfiles", "config", "settings.json");
125 const linkedState = path.join(root, "dotfiles", "state");
126 const home = path.join(root, "home");
127 const link = path.join(home, "state", "settings.json");
128 yield* fs.makeDirectory(path.dirname(destination), { recursive: true });
129 yield* fs.makeDirectory(linkedState, { recursive: true });
130 yield* fs.makeDirectory(home, { recursive: true });
131 yield* fs.symlink(linkedState, path.join(home, "state"));
132 yield* fs.writeFileString(destination, "before");
133 yield* fs.symlink("../config/settings.json", link);
134
135 yield* writeFileStringAtomically({ filePath: link, contents: "after" });
136
137 assert.strictEqual(yield* fs.readLink(link), "../config/settings.json");
138 assert.strictEqual(yield* fs.readFileString(destination), "after");
139 }),
140 );
141
142 it.effect("does not replace a newer save that landed while the lock was held", () =>
143 Effect.gen(function* () {
144 const fs = yield* FileSystem.FileSystem;
145 const path = yield* Path.Path;
146 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
147 const filePath = path.join(root, "settings.json");
148 yield* fs.writeFileString(filePath, "before");
149 const firstAttempt = yield* Deferred.make<void>();
150 let attempts = 0;
151 const lockedOnce = FileSystem.make({
152 ...fs,
153 rename: (from, to) =>
154 Effect.suspend(() => {
155 attempts += 1;
156 return attempts === 1
157 ? Deferred.succeed(firstAttempt, undefined).pipe(
158 Effect.andThen(Effect.fail(renameError("EBUSY", to))),
159 )
160 : fs.rename(from, to);
161 }),
162 });
163
164 const stale = yield* writeFileStringAtomically({ filePath, contents: "stale" }).pipe(
165 Effect.provideService(FileSystem.FileSystem, lockedOnce),
166 Effect.provideService(HostProcess.Platform, "win32"),
167 Effect.exit,
168 Effect.forkChild,
169 );
170 yield* Deferred.await(firstAttempt);
171 yield* writeFileStringAtomically({ filePath, contents: "newer" });
172
173 yield* TestClock.adjust("100 millis");
174 assert.isTrue(Exit.isFailure(yield* Fiber.join(stale)));
175 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
176 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
177 }),
178 );
179});
180
181const renameError = (code: string, path: string) =>
182 PlatformError.systemError({
183 _tag: "Unknown",
184 module: "FileSystem",
185 method: "rename",
186 pathOrDescriptor: path,
187 cause: Object.assign(new Error(`${code}, rename`), { code }),
188 });
189
190it.effect("surfaces an unreadable link instead of writing over it", () =>
191 Effect.gen(function* () {
192 const readLinkFailure = PlatformError.systemError({
193 _tag: "Unknown",
194 module: "FileSystem",
195 method: "readLink",
196 pathOrDescriptor: "/home/settings.json",
197 });
198
199 const failure = yield* writeFileStringAtomically({
200 filePath: "/home/settings.json",
201 contents: "after",
202 }).pipe(Effect.flip);
203
204 assert.deepStrictEqual(failure, readLinkFailure);
205 }).pipe(
206 Effect.provide(
207 Layer.mergeAll(
208 Path.layer,
209 FileSystem.layerNoop({
210 readLink: () =>
211 Effect.fail(
212 PlatformError.systemError({
213 _tag: "Unknown",
214 module: "FileSystem",
215 method: "readLink",
216 pathOrDescriptor: "/home/settings.json",
217 }),
218 ),
219 rename: () => Effect.die("an unreadable link must not be replaced"),
220 }),
221 ),
222 ),
223 ),
224);
225
226it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
227 Effect.gen(function* () {
228 const renamed: Array<string> = [];
229 const removed: Array<string> = [];
230 const fileSystem = FileSystem.layerNoop({
231 readLink: (path) =>
232 Effect.fail(
233 PlatformError.systemError({
234 _tag: "NotFound",
235 module: "FileSystem",
236 method: "readLink",
237 pathOrDescriptor: path,
238 }),
239 ),
240 makeDirectory: () => Effect.void,
241 makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
242 writeFileString: () => Effect.void,
243 rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
244 remove: (path) =>
245 Effect.sync(() => void removed.push(path)).pipe(
246 Effect.andThen(
247 Effect.fail(
248 PlatformError.systemError({
249 _tag: "PermissionDenied",
250 module: "FileSystem",
251 method: "remove",
252 pathOrDescriptor: path,
253 }),
254 ),
255 ),
256 ),
257 });
258
259 const result = yield* Effect.exit(
260 writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
261 Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
262 ),
263 );
264
265 assert.deepStrictEqual(result, Exit.void);
266 assert.deepStrictEqual(renamed, ["/home/settings.json"]);
267 assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
268 }),
269);