The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as FileSystem from "effect/FileSystem"; |
| 3 | import * as Option from "effect/Option"; |
| 4 | import * as Path from "effect/Path"; |
| 5 | import type * as PlatformError from "effect/PlatformError"; |
| 6 | import * as Result from "effect/Result"; |
| 7 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 8 | import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; |
| 9 | |
| 10 | /** Windows open-file locks block renames; the same codes can mean permanent denial, so bound retries. */ |
| 11 | export 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. |
| 17 | const LOCKED_RENAME_RETRIES = 20; |
| 18 | const LOCKED_RENAME_RETRY_DELAY = "100 millis"; |
| 19 | const CHUNK_WRITE_LENGTH = 1 << 20; |
| 20 | |
| 21 | // Saves keep the replaced file's mode and create new files owner-only; chmod, since the umask narrows an open mode. |
| 22 | const replacedMode = (fs: FileSystem.FileSystem, targetPath: string) => |
| 23 | fs.stat(targetPath).pipe( |
| 24 | Effect.map((info) => info.mode & 0o777), |
| 25 | Effect.catchIf( |
| 26 | (error) => error.reason._tag === "NotFound", |
| 27 | () => Effect.succeed(0o600), |
| 28 | ), |
| 29 | ); |
| 30 | |
| 31 | const isUnsupportedSync = (error: PlatformError.PlatformError) => { |
| 32 | const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code; |
| 33 | return code === "EINVAL" || code === "ENOTSUP" || code === "ENOSYS"; |
| 34 | }; |
| 35 | |
| 36 | /** Resolves symlink targets before renaming so writes preserve the link. Iterable contents stream in bounded batches. */ |
| 37 | export const writeFileStringAtomically = (input: { |
| 38 | readonly filePath: string; |
| 39 | readonly contents: string | Iterable<string>; |
| 40 | }) => |
| 41 | Effect.scoped( |
| 42 | Effect.gen(function* () { |
| 43 | const fs = yield* FileSystem.FileSystem; |
| 44 | const path = yield* Path.Path; |
| 45 | const platform = yield* HostProcess.Platform; |
| 46 | const targetPath = yield* resolveSymlinkTarget(input.filePath); |
| 47 | const targetDirectory = path.dirname(targetPath); |
| 48 | |
| 49 | yield* fs.makeDirectory(targetDirectory, { recursive: true }); |
| 50 | // Cleanup failure must not fail a write that already landed. |
| 51 | const tempDirectory = yield* Effect.acquireRelease( |
| 52 | fs.makeTempDirectory({ |
| 53 | directory: targetDirectory, |
| 54 | prefix: "t3-write-", |
| 55 | }), |
| 56 | (directory) => fs.remove(directory, { recursive: true }).pipe(Effect.ignore({ log: true })), |
| 57 | ); |
| 58 | const tempPath = path.join(tempDirectory, "contents.tmp"); |
| 59 | |
| 60 | // One write-only handle: a reopen fails when the umask or the chmod drops access. |
| 61 | // Without the sync, a crash soon after the rename can leave the target empty. |
| 62 | // Closed before the rename, which Windows refuses for open files. |
| 63 | yield* Effect.scoped( |
| 64 | Effect.gen(function* () { |
| 65 | const file = yield* fs.open(tempPath, { flag: "w" }); |
| 66 | const encoder = new TextEncoder(); |
| 67 | const contents = input.contents; |
| 68 | if (typeof contents === "string") { |
| 69 | yield* file.writeAll(encoder.encode(contents)); |
| 70 | } else { |
| 71 | let batch: string[] = []; |
| 72 | let batchLength = 0; |
| 73 | for (const chunk of contents) { |
| 74 | batch.push(chunk); |
| 75 | batchLength += chunk.length; |
| 76 | if (batchLength < CHUNK_WRITE_LENGTH) continue; |
| 77 | yield* file.writeAll(encoder.encode(batch.join(""))); |
| 78 | batch = []; |
| 79 | batchLength = 0; |
| 80 | } |
| 81 | if (batchLength > 0) yield* file.writeAll(encoder.encode(batch.join(""))); |
| 82 | } |
| 83 | if (platform !== "win32") { |
| 84 | yield* fs.chmod(tempPath, yield* replacedMode(fs, targetPath)); |
| 85 | } |
| 86 | yield* file.sync; |
| 87 | }), |
| 88 | ); |
| 89 | if (platform !== "win32") { |
| 90 | yield* fs.rename(tempPath, targetPath); |
| 91 | // Persists the rename. A directory without read access cannot be opened to sync, and |
| 92 | // replacing in one needs only write and search access, so that save stands. |
| 93 | return yield* fs.open(targetDirectory, { flag: "r" }).pipe( |
| 94 | Effect.flatMap((directory) => directory.sync), |
| 95 | Effect.scoped, |
| 96 | Effect.catchIf( |
| 97 | (error) => error.reason._tag === "PermissionDenied" || isUnsupportedSync(error), |
| 98 | (error) => Effect.logWarning(error), |
| 99 | ), |
| 100 | ); |
| 101 | } |
| 102 | |
| 103 | // Stop retrying if another save changes the target; read-only targets also return permanent EPERM. |
| 104 | const targetVersion = fs.stat(targetPath).pipe( |
| 105 | Effect.map((info) => ({ |
| 106 | id: `${Option.getOrUndefined(info.ino)}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}`, |
| 107 | readOnly: (info.mode & 0o200) === 0, |
| 108 | })), |
| 109 | Effect.catchIf( |
| 110 | (error) => error.reason._tag === "NotFound", |
| 111 | () => Effect.succeed({ id: "missing", readOnly: false }), |
| 112 | ), |
| 113 | Effect.option, |
| 114 | ); |
| 115 | const before = yield* targetVersion; |
| 116 | const firstAttempt = yield* Effect.result(fs.rename(tempPath, targetPath)); |
| 117 | if (Result.isSuccess(firstAttempt)) return; |
| 118 | const lockError = firstAttempt.failure; |
| 119 | if (!isWindowsRenameLock(lockError) || Option.isNone(before) || before.value.readOnly) { |
| 120 | return yield* lockError; |
| 121 | } |
| 122 | for (let retry = 0; retry < LOCKED_RENAME_RETRIES; retry += 1) { |
| 123 | yield* Effect.sleep(LOCKED_RENAME_RETRY_DELAY); |
| 124 | const current = yield* targetVersion; |
| 125 | if (Option.isNone(current) || current.value.id !== before.value.id) break; |
| 126 | const attempt = yield* Effect.result(fs.rename(tempPath, targetPath)); |
| 127 | if (Result.isSuccess(attempt)) return; |
| 128 | if (!isWindowsRenameLock(attempt.failure)) return yield* attempt.failure; |
| 129 | } |
| 130 | return yield* lockError; |
| 131 | }), |
| 132 | ); |