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

atomicWrite.ts

76 lines3.4 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import type * as PlatformError from "effect/PlatformError";
6import * as Result from "effect/Result";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
9​
10/** Windows open-file locks block renames; the same codes can mean permanent denial, so bound retries. */
11export const isWindowsRenameLock = (error: PlatformError.PlatformError) => {
12 const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
13 return code === "EBUSY" || code === "EPERM" || code === "EACCES";
14};
15​
16// Bound denial delays to about two seconds because settings saves hold their write lock.
17const LOCKED_RENAME_RETRIES = 20;
18const LOCKED_RENAME_RETRY_DELAY = "100 millis";
19​
20/** Resolves symlink targets before renaming so writes preserve the link. */
21export const writeFileStringAtomically = (input: {
22 readonly filePath: string;
23 readonly contents: string;
24}) =>
25 Effect.scoped(
26 Effect.gen(function* () {
27 const fs = yield* FileSystem.FileSystem;
28 const path = yield* Path.Path;
29 const platform = yield* HostProcess.Platform;
30 const targetPath = yield* resolveSymlinkTarget(input.filePath);
31 const targetDirectory = path.dirname(targetPath);
32​
33 yield* fs.makeDirectory(targetDirectory, { recursive: true });
34 // Cleanup failure must not fail a write that already landed.
35 const tempDirectory = yield* Effect.acquireRelease(
36 fs.makeTempDirectory({
37 directory: targetDirectory,
38 prefix: `${path.basename(targetPath)}.`,
39 }),
40 (directory) => fs.remove(directory, { recursive: true }).pipe(Effect.ignore({ log: true })),
41 );
42 const tempPath = path.join(tempDirectory, "contents.tmp");
43​
44 yield* fs.writeFileString(tempPath, input.contents);
45 if (platform !== "win32") return yield* fs.rename(tempPath, targetPath);
46​
47 // Stop retrying if another save changes the target; read-only targets also return permanent EPERM.
48 const targetVersion = fs.stat(targetPath).pipe(
49 Effect.map((info) => ({
50 id: `${Option.getOrUndefined(info.ino)}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`,
51 readOnly: (info.mode & 0o200) === 0,
52 })),
53 Effect.catchIf(
54 (error) => error.reason._tag === "NotFound",
55 () => Effect.succeed({ id: "missing", readOnly: false }),
56 ),
57 Effect.option,
58 );
59 const before = yield* targetVersion;
60 const firstAttempt = yield* Effect.result(fs.rename(tempPath, targetPath));
61 if (Result.isSuccess(firstAttempt)) return;
62 const lockError = firstAttempt.failure;
63 if (!isWindowsRenameLock(lockError) || Option.isNone(before) || before.value.readOnly) {
64 return yield* lockError;
65 }
66 for (let retry = 0; retry < LOCKED_RENAME_RETRIES; retry += 1) {
67 yield* Effect.sleep(LOCKED_RENAME_RETRY_DELAY);
68 const current = yield* targetVersion;
69 if (Option.isNone(current) || current.value.id !== before.value.id) break;
70 const attempt = yield* Effect.result(fs.rename(tempPath, targetPath));
71 if (Result.isSuccess(attempt)) return;
72 if (!isWindowsRenameLock(attempt.failure)) return yield* attempt.failure;
73 }
74 return yield* lockError;
75 }),
76 );