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