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

atomicWrite.ts

88 lines4.0 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/**
11 * Windows refuses to rename over or away from a file another process holds open
12 * without delete sharing, such as a virus scanner or the search indexer. The same
13 * codes also mean a denial that never clears, so retries need a bound.
14 */
15export const isWindowsRenameLock = (error: PlatformError.PlatformError) => {
16 const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
17 return code === "EBUSY" || code === "EPERM" || code === "EACCES";
18};
19​
20// About 2 seconds in total. Settings and keybinding saves wait on this while holding
21// their write lock, so a denial that is not a brief scan has to surface quickly.
22const LOCKED_RENAME_RETRIES = 20;
23const LOCKED_RENAME_RETRY_DELAY = "100 millis";
24​
25/**
26 * A symlinked target is resolved first so the link survives and its destination is
27 * rewritten, since renaming over the link itself would swap it for a regular file.
28 */
29export const writeFileStringAtomically = (input: {
30 readonly filePath: string;
31 readonly contents: string;
32}) =>
33 Effect.scoped(
34 Effect.gen(function* () {
35 const fs = yield* FileSystem.FileSystem;
36 const path = yield* Path.Path;
37 const platform = yield* HostProcess.Platform;
38 const targetPath = yield* resolveSymlinkTarget(input.filePath);
39 const targetDirectory = path.dirname(targetPath);
40​
41 yield* fs.makeDirectory(targetDirectory, { recursive: true });
42 // The temp directory is cleanup, not part of the write: failing to remove
43 // it (a virus scanner holding it on Windows) must not fail a write that
44 // already landed.
45 const tempDirectory = yield* Effect.acquireRelease(
46 fs.makeTempDirectory({
47 directory: targetDirectory,
48 prefix: `${path.basename(targetPath)}.`,
49 }),
50 (directory) => fs.remove(directory, { recursive: true }).pipe(Effect.ignore({ log: true })),
51 );
52 const tempPath = path.join(tempDirectory, "contents.tmp");
53​
54 yield* fs.writeFileString(tempPath, input.contents);
55 if (platform !== "win32") return yield* fs.rename(tempPath, targetPath);
56​
57 // A retry must not replace a save another process landed while this one
58 // waited, so it gives up once the target is no longer the file seen here.
59 // A read-only target fails with the same EPERM as a held one but never clears.
60 const targetVersion = fs.stat(targetPath).pipe(
61 Effect.map((info) => ({
62 id: `${Option.getOrUndefined(info.ino)}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`,
63 readOnly: (info.mode & 0o200) === 0,
64 })),
65 Effect.catchIf(
66 (error) => error.reason._tag === "NotFound",
67 () => Effect.succeed({ id: "missing", readOnly: false }),
68 ),
69 Effect.option,
70 );
71 const before = yield* targetVersion;
72 const firstAttempt = yield* Effect.result(fs.rename(tempPath, targetPath));
73 if (Result.isSuccess(firstAttempt)) return;
74 const lockError = firstAttempt.failure;
75 if (!isWindowsRenameLock(lockError) || Option.isNone(before) || before.value.readOnly) {
76 return yield* lockError;
77 }
78 for (let retry = 0; retry < LOCKED_RENAME_RETRIES; retry += 1) {
79 yield* Effect.sleep(LOCKED_RENAME_RETRY_DELAY);
80 const current = yield* targetVersion;
81 if (Option.isNone(current) || current.value.id !== before.value.id) break;
82 const attempt = yield* Effect.result(fs.rename(tempPath, targetPath));
83 if (Result.isSuccess(attempt)) return;
84 if (!isWindowsRenameLock(attempt.failure)) return yield* attempt.failure;
85 }
86 return yield* lockError;
87 }),
88 );