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, 04:45 UTC
| 1 | import * as Clock from "effect/Clock"; |
| 2 | import * as Data from "effect/Data"; |
| 3 | import * as Duration from "effect/Duration"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Semaphore from "effect/Semaphore"; |
| 10 | import { rootDir } from "./Paths.ts"; |
| 11 | |
| 12 | const semaphores = new Map<string, Semaphore.Semaphore>(); |
| 13 | |
| 14 | // Keep STALE well above REFRESH — a saturated machine can starve the |
| 15 | // heartbeat fiber for seconds. |
| 16 | const STALE = Duration.seconds(30); |
| 17 | const REFRESH = Duration.seconds(10); |
| 18 | const RETRY_INTERVAL = Duration.millis(50); |
| 19 | const DEFAULT_TIMEOUT = Duration.minutes(2); |
| 20 | // How often to remind the user that a lock wait / locked operation is still |
| 21 | // outstanding. Long enough that healthy runs never print it. |
| 22 | const STALL_INTERVAL = Duration.seconds(30); |
| 23 | |
| 24 | class LockHeld extends Data.TaggedError("LockHeld") {} |
| 25 | |
| 26 | class LockTimeout extends Data.TaggedError("LockTimeout")<{ |
| 27 | readonly lockPath: string; |
| 28 | readonly timeout: Duration.Input; |
| 29 | readonly message: string; |
| 30 | }> {} |
| 31 | |
| 32 | /** |
| 33 | * Make a lock key safe to use as a file name on every platform. |
| 34 | * |
| 35 | * Keys are derived from user-controlled values (profile names), which |
| 36 | * have shown up in production containing shell placeholders like |
| 37 | * `${ALCHEMY_PROFILE:-default}` — `:`/`{`/`$` are invalid in Windows |
| 38 | * file names and mkdir fails with EINVAL. Collapse anything outside a |
| 39 | * conservative allow-list to `_`. |
| 40 | * |
| 41 | * @internal exported for unit testing. |
| 42 | */ |
| 43 | export const sanitizeLockKey = (key: string): string => key.replace(/[^A-Za-z0-9._-]/g, "_"); |
| 44 | |
| 45 | /** |
| 46 | * Take the cross-process lock. On success the ambient scope owns it: a |
| 47 | * finalizer removes it and a forked heartbeat keeps its mtime fresh. |
| 48 | */ |
| 49 | const acquireFileLock = Effect.fn(function* (lockPath: string, timeout: Duration.Input) { |
| 50 | const fs = yield* FileSystem.FileSystem; |
| 51 | const path = yield* Path.Path; |
| 52 | const ownerPath = path.join(lockPath, "owner"); |
| 53 | const owner = yield* Effect.sync(() => crypto.randomUUID()); |
| 54 | |
| 55 | yield* fs.makeDirectory(path.dirname(lockPath), { recursive: true }); |
| 56 | |
| 57 | // Reap a lock whose crashed holder stopped refreshing its mtime. |
| 58 | const reapStale = Effect.gen(function* () { |
| 59 | const info = yield* fs.stat(lockPath); |
| 60 | const now = yield* Clock.currentTimeMillis; |
| 61 | const isStale = Option.exists( |
| 62 | info.mtime, |
| 63 | (mtime) => mtime.getTime() < now - Duration.toMillis(STALE), |
| 64 | ); |
| 65 | if (isStale) { |
| 66 | yield* fs.remove(lockPath, { recursive: true, force: true }); |
| 67 | } |
| 68 | }).pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.void)); |
| 69 | |
| 70 | // A non-recursive mkdir is the atomic test-and-set; the owner marker lets |
| 71 | // release and refresh verify the lock wasn't reaped and re-taken. |
| 72 | yield* Effect.acquireRelease( |
| 73 | fs |
| 74 | .makeDirectory(lockPath) |
| 75 | .pipe( |
| 76 | Effect.andThen( |
| 77 | fs |
| 78 | .writeFileString(ownerPath, owner) |
| 79 | .pipe( |
| 80 | Effect.onError(() => |
| 81 | fs.remove(lockPath, { recursive: true, force: true }).pipe(Effect.ignore), |
| 82 | ), |
| 83 | ), |
| 84 | ), |
| 85 | ), |
| 86 | () => |
| 87 | fs.readFileString(ownerPath).pipe( |
| 88 | Effect.filterOrFail((current) => current === owner), |
| 89 | Effect.andThen(fs.remove(lockPath, { recursive: true, force: true })), |
| 90 | Effect.ignore, |
| 91 | ), |
| 92 | ).pipe( |
| 93 | Effect.catchReason("PlatformError", "AlreadyExists", () => |
| 94 | reapStale.pipe(Effect.andThen(Effect.fail(new LockHeld()))), |
| 95 | ), |
| 96 | Effect.retry({ |
| 97 | while: (error) => error._tag === "LockHeld", |
| 98 | schedule: Schedule.spaced(RETRY_INTERVAL).pipe(Schedule.upTo({ duration: timeout })), |
| 99 | }), |
| 100 | Effect.catchTag("LockHeld", () => |
| 101 | Effect.die( |
| 102 | new LockTimeout({ |
| 103 | lockPath, |
| 104 | timeout, |
| 105 | message: |
| 106 | `Timed out waiting for the alchemy auth lock '${lockPath}' — another alchemy ` + |
| 107 | `process has held it for over ${Duration.toSeconds(timeout)}s. If no other ` + |
| 108 | `alchemy process is running, delete the lock directory and retry.`, |
| 109 | }), |
| 110 | ), |
| 111 | ), |
| 112 | ); |
| 113 | |
| 114 | yield* fs.readFileString(ownerPath).pipe( |
| 115 | Effect.filterOrFail((current) => current === owner), |
| 116 | Effect.andThen(Clock.currentTimeMillis.pipe(Effect.map((now) => new Date(now)))), |
| 117 | // NB: utimes interprets a bare number as *seconds* since epoch. |
| 118 | Effect.flatMap((now) => fs.utimes(lockPath, now, now)), |
| 119 | Effect.repeat(Schedule.spaced(REFRESH)), |
| 120 | Effect.catch(() => |
| 121 | Effect.logWarning( |
| 122 | `auth lock compromised (continuing): '${lockPath}' is no longer owned by this process`, |
| 123 | ), |
| 124 | ), |
| 125 | // Acquisition returns while this fiber refreshes until the lock scope ends. |
| 126 | Effect.forkScoped, |
| 127 | ); |
| 128 | }); |
| 129 | |
| 130 | type Phase = { current: "waiting" | "held" }; |
| 131 | |
| 132 | /** |
| 133 | * Periodic "I am not dead, I am stuck here" notice, forked for the lifetime |
| 134 | * of a {@link withLock} call. |
| 135 | * Logged as a warning: the console logger shows it above the noise floor |
| 136 | * (telemetry merges with it rather than replacing it), and JSON output and |
| 137 | * the run log carry it too. |
| 138 | */ |
| 139 | const stallNotice = (lockPath: string, label: string, phase: Phase, interval: Duration.Input) => |
| 140 | Effect.gen(function* () { |
| 141 | const start = yield* Clock.currentTimeMillis; |
| 142 | const notice = Effect.gen(function* () { |
| 143 | // Report real elapsed time, not an accumulated interval count — the |
| 144 | // notice cadence and the reported wait must not drift apart. |
| 145 | const now = yield* Clock.currentTimeMillis; |
| 146 | const seconds = Math.round((now - start) / 1000); |
| 147 | yield* Effect.logWarning( |
| 148 | phase.current === "waiting" |
| 149 | ? `alchemy: ${seconds}s waiting for the auth lock '${lockPath}' (${label}). ` + |
| 150 | `Another alchemy process holds it; if none is running, delete that directory.` |
| 151 | : `alchemy: ${label} has been running for ${seconds}s while holding the auth lock ` + |
| 152 | `'${lockPath}'. Re-run with --log-level debug for detail.`, |
| 153 | ); |
| 154 | }); |
| 155 | // `Effect.schedule` (unlike `Effect.repeat`) consults the schedule |
| 156 | // before the first run, and `Schedule.fixed`'s first recurrence comes |
| 157 | // after one full interval — so notices fire at interval, 2*interval, … |
| 158 | // on true wall-clock boundaries. |
| 159 | yield* Effect.schedule(notice, Schedule.fixed(interval)); |
| 160 | }); |
| 161 | |
| 162 | /** |
| 163 | * Serialise execution of `effect` for the same `key`, both within this |
| 164 | * process (a semaphore) and across processes on the same machine (an atomic |
| 165 | * lock directory whose mtime is refreshed while held so another process can |
| 166 | * recover it after a crash). |
| 167 | * |
| 168 | * Failure to create or acquire the lock is fatal. Authentication writes its |
| 169 | * profile state beneath the same root, so continuing without a writable lock |
| 170 | * cannot produce a valid deployment and would permit concurrent corruption. |
| 171 | */ |
| 172 | export const withLock = <A, E, R>( |
| 173 | key: string, |
| 174 | effect: Effect.Effect<A, E, R>, |
| 175 | options?: { |
| 176 | readonly timeout?: Duration.Input; |
| 177 | /** |
| 178 | * Human-readable name of the work being serialised, used in the debug |
| 179 | * log lines and the stall notice. Defaults to `key`. |
| 180 | */ |
| 181 | readonly label?: string; |
| 182 | /** |
| 183 | * Print a periodic notice to stderr while this lock is being waited on |
| 184 | * or held (see {@link stallNotice}). Pass `false` for flows that |
| 185 | * legitimately block on the user — a browser OAuth round-trip, an |
| 186 | * `aws sso login` child process — where a repeating notice would be |
| 187 | * both wrong and destructive to the prompt on screen. |
| 188 | * |
| 189 | * @default true |
| 190 | */ |
| 191 | readonly watchdog?: boolean; |
| 192 | /** |
| 193 | * Interval between stall notices. |
| 194 | * |
| 195 | * @internal exposed so tests need not wait 30 real seconds. |
| 196 | */ |
| 197 | readonly stallInterval?: Duration.Input; |
| 198 | }, |
| 199 | ) => { |
| 200 | const safeKey = sanitizeLockKey(key); |
| 201 | const label = options?.label ?? key; |
| 202 | let semaphore = semaphores.get(safeKey); |
| 203 | if (semaphore === undefined) { |
| 204 | semaphore = Semaphore.makeUnsafe(1); |
| 205 | semaphores.set(safeKey, semaphore); |
| 206 | } |
| 207 | return semaphore.withPermit( |
| 208 | Effect.gen(function* () { |
| 209 | const path = yield* Path.Path; |
| 210 | const lockPath = path.join(rootDir(), "lock", `${safeKey}.lock`); |
| 211 | const phase: Phase = { current: "waiting" }; |
| 212 | if (options?.watchdog !== false) { |
| 213 | yield* Effect.forkScoped( |
| 214 | stallNotice(lockPath, label, phase, options?.stallInterval ?? STALL_INTERVAL), |
| 215 | ); |
| 216 | } |
| 217 | yield* Effect.logDebug(`auth lock: acquiring '${lockPath}' for ${label}`); |
| 218 | yield* acquireFileLock(lockPath, options?.timeout ?? DEFAULT_TIMEOUT).pipe(Effect.orDie); |
| 219 | phase.current = "held"; |
| 220 | yield* Effect.logDebug(`auth lock: acquired '${lockPath}' for ${label}`); |
| 221 | return yield* effect.pipe( |
| 222 | Effect.onExit(() => Effect.logDebug(`auth lock: releasing '${lockPath}' for ${label}`)), |
| 223 | ); |
| 224 | }).pipe(Effect.scoped), |
| 225 | ); |
| 226 | }; |
| 227 | |
| 228 | /** |
| 229 | * Serialize an operation with every credential mutation for a profile. The |
| 230 | * lock key is shared by every credential operation for the profile, |
| 231 | * including profile-wide rename and delete operations. |
| 232 | */ |
| 233 | export const withProfileCredentialsLock = <A, E, R>( |
| 234 | profileName: string, |
| 235 | effect: Effect.Effect<A, E, R>, |
| 236 | ) => withLock(`profile-credentials-${profileName}`, effect); |