@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 464 lines 18 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import * as Deferred from "effect/Deferred";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Path from "effect/Path";
10 import * as PlatformError from "effect/PlatformError";
11 import * as TestClock from "effect/testing/TestClock";
12
13 import { writeFileStringAtomically } from "./atomicWrite.ts";
14 import * as HostProcess from "./HostProcess.ts";
15
16 it.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 // Read-only and unreadable targets still save, since the mode lands after the temp file opens.
196 it.effect.each(HostProcess.Platform.defaultValue() === "win32" ? [] : ["644", "444", "000"])(
197 "keeps the %s permissions of the file it replaces",
198 (octal) =>
199 Effect.gen(function* () {
200 const fs = yield* FileSystem.FileSystem;
201 const path = yield* Path.Path;
202 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
203 const filePath = path.join(root, "settings.json");
204 const mode = Number.parseInt(octal, 8);
205 yield* fs.writeFileString(filePath, "before");
206 yield* fs.chmod(filePath, mode);
207
208 yield* writeFileStringAtomically({ filePath, contents: "after" });
209
210 assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, mode);
211 yield* fs.chmod(filePath, 0o600);
212 assert.strictEqual(yield* fs.readFileString(filePath), "after");
213 }),
214 );
215
216 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
217 "creates a new file readable only by its owner",
218 () =>
219 Effect.gen(function* () {
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
223 const filePath = path.join(root, "settings.json");
224
225 yield* writeFileStringAtomically({ filePath, contents: "fresh" });
226
227 assert.strictEqual(((yield* fs.stat(filePath)).mode & 0o777).toString(8), "600");
228 }),
229 );
230
231 // Root ignores the missing read bit, so only a regular user sees the failure.
232 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)(
233 "saves when the umask removes owner read access",
234 () =>
235 Effect.gen(function* () {
236 const fs = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
239 const filePath = path.join(root, "settings.json");
240 yield* fs.writeFileString(filePath, "before");
241 yield* fs.chmod(filePath, 0o600);
242 yield* Effect.acquireRelease(
243 Effect.sync(() => process.umask(0o400)),
244 (previous) => Effect.sync(() => process.umask(previous)),
245 );
246
247 yield* writeFileStringAtomically({ filePath, contents: "after" });
248
249 assert.strictEqual(yield* fs.readFileString(filePath), "after");
250 assert.strictEqual((yield* fs.stat(filePath)).mode & 0o777, 0o600);
251 }),
252 );
253
254 it.effect("syncs the contents before the rename and the directory after it", () =>
255 Effect.gen(function* () {
256 const fs = yield* FileSystem.FileSystem;
257 const path = yield* Path.Path;
258 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
259 const filePath = path.join(root, "settings.json");
260 const events: Array<string> = [];
261 const recording = FileSystem.make({
262 ...fs,
263 open: (openedPath, options) =>
264 fs.open(openedPath, options).pipe(
265 // The real handle keeps its methods on its prototype, so it is extended, not spread.
266 Effect.map((file): FileSystem.File =>
267 Object.create(file, {
268 sync: {
269 value: file.sync.pipe(
270 Effect.tap(() =>
271 Effect.sync(() => {
272 events.push(openedPath === root ? "sync directory" : "sync temp file");
273 }),
274 ),
275 ),
276 },
277 }),
278 ),
279 ),
280 rename: (from, to) =>
281 fs
282 .rename(from, to)
283 .pipe(
284 Effect.tap(() =>
285 Effect.sync(() =>
286 events.push(from === filePath ? "rename target" : "rename temp file"),
287 ),
288 ),
289 ),
290 });
291
292 yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
293 Effect.provideService(FileSystem.FileSystem, recording),
294 );
295
296 assert.strictEqual(yield* fs.readFileString(filePath), "after");
297 // Windows cannot open a directory to sync it.
298 assert.deepStrictEqual(
299 events,
300 HostProcess.Platform.defaultValue() === "win32"
301 ? ["sync temp file", "rename temp file"]
302 : ["sync temp file", "rename temp file", "sync directory"],
303 );
304 }),
305 );
306
307 // EIO means the rename may not survive a crash; ENOTSUP means directories cannot sync at all.
308 it.effect.each(
309 HostProcess.Platform.defaultValue() === "win32"
310 ? []
311 : [
312 { code: "EIO", fails: true },
313 { code: "ENOTSUP", fails: false },
314 ],
315 )("handles a directory sync failing with $code after the rename", ({ code, fails }) =>
316 Effect.gen(function* () {
317 const fs = yield* FileSystem.FileSystem;
318 const path = yield* Path.Path;
319 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
320 const filePath = path.join(root, "settings.json");
321 const syncFailure = PlatformError.systemError({
322 _tag: "Unknown",
323 module: "FileSystem",
324 method: "sync",
325 pathOrDescriptor: root,
326 cause: Object.assign(new Error(`${code}, fsync`), { code }),
327 });
328 const failingDirectorySync = FileSystem.make({
329 ...fs,
330 open: (openedPath, options) =>
331 fs
332 .open(openedPath, options)
333 .pipe(
334 Effect.map((file): FileSystem.File =>
335 openedPath === root
336 ? Object.create(file, { sync: { value: Effect.fail(syncFailure) } })
337 : file,
338 ),
339 ),
340 });
341
342 const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
343 Effect.provideService(FileSystem.FileSystem, failingDirectorySync),
344 Effect.exit,
345 );
346
347 assert.deepStrictEqual(exit, fails ? Exit.fail(syncFailure) : Exit.void);
348 assert.strictEqual(yield* fs.readFileString(filePath), "after");
349 }),
350 );
351
352 // Injected because root ignores a chmod that drops read access.
353 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
354 "saves when its directory cannot be opened for the sync",
355 () =>
356 Effect.gen(function* () {
357 const fs = yield* FileSystem.FileSystem;
358 const path = yield* Path.Path;
359 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
360 const filePath = path.join(root, "settings.json");
361 yield* fs.writeFileString(filePath, "before");
362 const openFailure = PlatformError.systemError({
363 _tag: "PermissionDenied",
364 module: "FileSystem",
365 method: "open",
366 pathOrDescriptor: root,
367 });
368 const unopenableDirectory = FileSystem.make({
369 ...fs,
370 open: (openedPath, options) =>
371 openedPath === root ? Effect.fail(openFailure) : fs.open(openedPath, options),
372 });
373
374 const exit = yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
375 Effect.provideService(FileSystem.FileSystem, unopenableDirectory),
376 Effect.exit,
377 );
378
379 assert.deepStrictEqual(exit, Exit.void);
380 assert.strictEqual(yield* fs.readFileString(filePath), "after");
381 }),
382 );
383
384 it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
385 Effect.gen(function* () {
386 const fs = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" });
389 const filePath = path.join(root, "settings.json");
390 const removeAttempts: Array<string> = [];
391 const unremovable = FileSystem.make({
392 ...fs,
393 remove: (removedPath) =>
394 Effect.suspend(() => {
395 removeAttempts.push(removedPath);
396 return Effect.fail(
397 PlatformError.systemError({
398 _tag: "PermissionDenied",
399 module: "FileSystem",
400 method: "remove",
401 pathOrDescriptor: removedPath,
402 }),
403 );
404 }),
405 });
406
407 yield* writeFileStringAtomically({ filePath, contents: "after" }).pipe(
408 Effect.provideService(FileSystem.FileSystem, unremovable),
409 );
410
411 assert.strictEqual(yield* fs.readFileString(filePath), "after");
412 assert.strictEqual(removeAttempts.length, 1);
413 assert.deepStrictEqual(
414 (yield* fs.readDirectory(root)).toSorted(),
415 [path.basename(removeAttempts[0]!), "settings.json"].toSorted(),
416 );
417 }),
418 );
419 });
420
421 const renameError = (code: string, path: string) =>
422 PlatformError.systemError({
423 _tag: "Unknown",
424 module: "FileSystem",
425 method: "rename",
426 pathOrDescriptor: path,
427 cause: Object.assign(new Error(`${code}, rename`), { code }),
428 });
429
430 it.effect("surfaces an unreadable link instead of writing over it", () =>
431 Effect.gen(function* () {
432 const readLinkFailure = PlatformError.systemError({
433 _tag: "Unknown",
434 module: "FileSystem",
435 method: "readLink",
436 pathOrDescriptor: "/home/settings.json",
437 });
438
439 const failure = yield* writeFileStringAtomically({
440 filePath: "/home/settings.json",
441 contents: "after",
442 }).pipe(Effect.flip);
443
444 assert.deepStrictEqual(failure, readLinkFailure);
445 }).pipe(
446 Effect.provide(
447 Layer.mergeAll(
448 Path.layer,
449 FileSystem.layerNoop({
450 readLink: () =>
451 Effect.fail(
452 PlatformError.systemError({
453 _tag: "Unknown",
454 module: "FileSystem",
455 method: "readLink",
456 pathOrDescriptor: "/home/settings.json",
457 }),
458 ),
459 rename: () => Effect.die("an unreadable link must not be replaced"),
460 }),
461 ),
462 ),
463 ),
464 );