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
| 1 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 2 | import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Path from "effect/Path"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 11 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 12 | |
| 13 | const ProcessIdentity = Schema.Struct({ |
| 14 | pid: Schema.Int, |
| 15 | startTime: Schema.String, |
| 16 | command: Schema.optional(Schema.String), |
| 17 | }); |
| 18 | type ProcessIdentity = typeof ProcessIdentity.Type; |
| 19 | |
| 20 | const RelayClientEntry = Schema.Struct({ |
| 21 | version: Schema.Literal(1), |
| 22 | client: ProcessIdentity, |
| 23 | // A process may rewrite its own argv, so the owner is identified by pid and start time. |
| 24 | owner: ProcessIdentity, |
| 25 | }); |
| 26 | type RelayClientEntry = typeof RelayClientEntry.Type; |
| 27 | const RelayClientEntryJson = Schema.fromJsonString(RelayClientEntry); |
| 28 | const decodeEntry = Schema.decodeUnknownOption(RelayClientEntryJson); |
| 29 | const encodeEntry = Schema.encodeEffect(RelayClientEntryJson); |
| 30 | |
| 31 | /** Remembers running relay clients so a server can stop the ones a crashed server left behind. */ |
| 32 | export class RelayClientLedger extends Context.Service< |
| 33 | RelayClientLedger, |
| 34 | { |
| 35 | /** Records a started relay client; the returned effect forgets it once it has stopped. */ |
| 36 | readonly track: (pid: number) => Effect.Effect<Effect.Effect<void>>; |
| 37 | } |
| 38 | >()("t3/cloud/RelayClientLedger") {} |
| 39 | |
| 40 | const ENTRY_DIRECTORY = "relay-clients"; |
| 41 | const ENTRY_FILE = /^\d+\.json$/; |
| 42 | const STOP_POLL_INTERVAL = "50 millis"; |
| 43 | const STOP_POLL_ATTEMPTS = 40; |
| 44 | |
| 45 | interface ObservedProcess { |
| 46 | readonly startTime: string; |
| 47 | readonly command: string; |
| 48 | readonly zombie: boolean; |
| 49 | } |
| 50 | |
| 51 | // ps lstart needs C locale and UTC for stable parsing. |
| 52 | const DARWIN_PS_LINE = /^\s*(\d+)\s+(\S+)\s+(\w{3} \w{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4})\s+(.*)$/; |
| 53 | |
| 54 | const processExists = (pid: number) => { |
| 55 | try { |
| 56 | process.kill(pid, 0); |
| 57 | return true; |
| 58 | } catch (cause) { |
| 59 | return (cause as NodeJS.ErrnoException | undefined)?.code !== "ESRCH"; |
| 60 | } |
| 61 | }; |
| 62 | |
| 63 | const signal = (pid: number, name: NodeJS.Signals) => { |
| 64 | try { |
| 65 | process.kill(pid, name); |
| 66 | } catch {} |
| 67 | }; |
| 68 | |
| 69 | export const make = Effect.fn("RelayClientLedger.make")(function* (input: { |
| 70 | readonly stateDir: string; |
| 71 | readonly ownerPid?: number; |
| 72 | }) { |
| 73 | const fs = yield* FileSystem.FileSystem; |
| 74 | const path = yield* Path.Path; |
| 75 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 76 | const platform = yield* HostProcess.Platform; |
| 77 | const directory = path.join(input.stateDir, ENTRY_DIRECTORY); |
| 78 | const recordable = platform === "linux" || platform === "darwin"; |
| 79 | |
| 80 | const observeLinux = Effect.fnUntraced(function* (pid: number) { |
| 81 | const stat = yield* fs.readFileString(`/proc/${pid}/stat`); |
| 82 | const fields = stat |
| 83 | .slice(stat.lastIndexOf(")") + 2) |
| 84 | .trim() |
| 85 | .split(/\s+/); |
| 86 | const startTime = fields[19]; |
| 87 | if (startTime === undefined) return undefined; |
| 88 | const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`); |
| 89 | return { |
| 90 | startTime, |
| 91 | command: cmdline.replace(/\0$/, "").replaceAll("\0", " "), |
| 92 | zombie: fields[0] === "Z", |
| 93 | } satisfies ObservedProcess; |
| 94 | }); |
| 95 | |
| 96 | const observeDarwin = (pid: number) => |
| 97 | spawner |
| 98 | .string( |
| 99 | ChildProcess.make("/bin/ps", ["-ww", "-o", "pid=,stat=,lstart=,args=", "-p", String(pid)], { |
| 100 | env: { LC_ALL: "C", TZ: "UTC" }, |
| 101 | extendEnv: true, |
| 102 | stdin: "ignore", |
| 103 | stderr: "ignore", |
| 104 | }), |
| 105 | ) |
| 106 | .pipe( |
| 107 | Effect.timeout("5 seconds"), |
| 108 | Effect.map((output) => { |
| 109 | for (const line of output.split("\n")) { |
| 110 | const match = DARWIN_PS_LINE.exec(line); |
| 111 | if (match === null || Number(match[1]) !== pid) continue; |
| 112 | return { |
| 113 | zombie: match[2]!.startsWith("Z"), |
| 114 | startTime: match[3]!, |
| 115 | command: match[4]!.trimEnd(), |
| 116 | } satisfies ObservedProcess; |
| 117 | } |
| 118 | return undefined; |
| 119 | }), |
| 120 | ); |
| 121 | |
| 122 | const observe = (pid: number): Effect.Effect<ObservedProcess | undefined> => { |
| 123 | if (platform === "linux") return observeLinux(pid).pipe(Effect.orElseSucceed(() => undefined)); |
| 124 | if (platform === "darwin") |
| 125 | return observeDarwin(pid).pipe(Effect.orElseSucceed(() => undefined)); |
| 126 | return Effect.undefined; |
| 127 | }; |
| 128 | |
| 129 | // "unknown" means the pid exists but could not be read, so nothing may be concluded about it. |
| 130 | const compare = (identity: ProcessIdentity) => |
| 131 | observe(identity.pid).pipe( |
| 132 | Effect.map((observed): "same" | "gone" | "unknown" => { |
| 133 | if (observed === undefined) return processExists(identity.pid) ? "unknown" : "gone"; |
| 134 | return !observed.zombie && |
| 135 | observed.startTime === identity.startTime && |
| 136 | (identity.command === undefined || observed.command === identity.command) |
| 137 | ? "same" |
| 138 | : "gone"; |
| 139 | }), |
| 140 | ); |
| 141 | |
| 142 | const identify = (pid: number) => |
| 143 | observe(pid).pipe( |
| 144 | Effect.map((observed) => |
| 145 | observed === undefined || observed.zombie |
| 146 | ? undefined |
| 147 | : { pid, startTime: observed.startTime, command: observed.command }, |
| 148 | ), |
| 149 | ); |
| 150 | |
| 151 | const ownerProcess = yield* identify(input.ownerPid ?? process.pid); |
| 152 | const owner = |
| 153 | ownerProcess === undefined |
| 154 | ? undefined |
| 155 | : { pid: ownerProcess.pid, startTime: ownerProcess.startTime }; |
| 156 | |
| 157 | const track: RelayClientLedger["Service"]["track"] = Effect.fn("RelayClientLedger.track")( |
| 158 | function* (pid) { |
| 159 | if (!recordable) return Effect.void; |
| 160 | const client = yield* identify(pid); |
| 161 | if (owner === undefined || client?.command === undefined) { |
| 162 | yield* Effect.logWarning( |
| 163 | "Could not record the relay client; it will keep running if this server crashes", |
| 164 | { pid }, |
| 165 | ); |
| 166 | return Effect.void; |
| 167 | } |
| 168 | const entryPath = path.join(directory, `${pid}.json`); |
| 169 | yield* writeFileStringAtomically({ |
| 170 | filePath: entryPath, |
| 171 | contents: yield* encodeEntry({ version: 1, client, owner }), |
| 172 | }).pipe( |
| 173 | Effect.provideService(FileSystem.FileSystem, fs), |
| 174 | Effect.provideService(Path.Path, path), |
| 175 | ); |
| 176 | return fs |
| 177 | .remove(entryPath, { force: true }) |
| 178 | .pipe( |
| 179 | Effect.catchCause((cause) => |
| 180 | Effect.logWarning("Could not forget a stopped relay client", { cause }), |
| 181 | ), |
| 182 | ); |
| 183 | }, |
| 184 | Effect.catchCause((cause) => |
| 185 | Effect.logWarning("Could not record the relay client", { cause }).pipe( |
| 186 | Effect.as(Effect.void), |
| 187 | ), |
| 188 | ), |
| 189 | ); |
| 190 | |
| 191 | // Signals only a process that still has the recorded pid, start time and command line, |
| 192 | // so a recycled pid is never touched. Returns whether the client is gone. |
| 193 | const stopOrphan = Effect.fn("RelayClientLedger.stopOrphan")(function* (client: ProcessIdentity) { |
| 194 | let state = yield* compare(client); |
| 195 | if (state !== "same") return state === "gone"; |
| 196 | yield* Effect.logInfo("Stopping a relay client left by a previous T3 Code server", { |
| 197 | pid: client.pid, |
| 198 | }); |
| 199 | for (const name of ["SIGTERM", "SIGKILL"] as const) { |
| 200 | signal(client.pid, name); |
| 201 | for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && state === "same"; attempt++) { |
| 202 | yield* Effect.sleep(STOP_POLL_INTERVAL); |
| 203 | state = yield* compare(client); |
| 204 | } |
| 205 | if (state !== "same") break; |
| 206 | } |
| 207 | return state === "gone"; |
| 208 | }); |
| 209 | |
| 210 | const reapEntry = Effect.fn("RelayClientLedger.reapEntry")( |
| 211 | function* (entryPath: string) { |
| 212 | const entry = decodeEntry(yield* fs.readFileString(entryPath)); |
| 213 | if (Option.isSome(entry)) { |
| 214 | if ((yield* compare(entry.value.owner)) !== "gone") return; |
| 215 | if (!(yield* stopOrphan(entry.value.client))) return; |
| 216 | } |
| 217 | yield* fs.remove(entryPath, { force: true }); |
| 218 | }, |
| 219 | (effect, entryPath) => |
| 220 | effect.pipe( |
| 221 | Effect.catchCause((cause) => |
| 222 | Effect.logWarning("Could not clean up a recorded relay client", { entryPath, cause }), |
| 223 | ), |
| 224 | ), |
| 225 | ); |
| 226 | |
| 227 | const reapOrphans = Effect.gen(function* () { |
| 228 | if (!recordable) return; |
| 229 | const names = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); |
| 230 | yield* Effect.forEach( |
| 231 | names.filter((name) => ENTRY_FILE.test(name)), |
| 232 | (name) => reapEntry(path.join(directory, name)), |
| 233 | { concurrency: "unbounded", discard: true }, |
| 234 | ); |
| 235 | }); |
| 236 | |
| 237 | return { track, reapOrphans }; |
| 238 | }); |
| 239 | |
| 240 | // Reaping finishes before any connector starts, so exactly one serves the tunnel. |
| 241 | export const layer = (input: { readonly stateDir: string }) => |
| 242 | Layer.effect( |
| 243 | RelayClientLedger, |
| 244 | Effect.gen(function* () { |
| 245 | const ledger = yield* make(input); |
| 246 | yield* ledger.reapOrphans; |
| 247 | return RelayClientLedger.of({ track: ledger.track }); |
| 248 | }), |
| 249 | ); |
| 250 | |
| 251 | export const layerTest = Layer.succeed( |
| 252 | RelayClientLedger, |
| 253 | RelayClientLedger.of({ |
| 254 | track: Effect.fn("RelayClientLedger.track")(function () { |
| 255 | return Effect.succeed(Effect.void); |
| 256 | }), |
| 257 | }), |
| 258 | ); |