The best way to control Claude Code, Codex and more from any computer or phone

main
ts 49 lines 2 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - v8.writeHeapSnapshot has no Effect equivalent.
2 import * as NodePath from "node:path";
3 import * as NodeV8 from "node:v8";
4
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import * as DateTime from "effect/DateTime";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as Schema from "effect/Schema";
11
12 import * as ServerConfig from "../config.ts";
13
14 class HeapSnapshotWriteError extends Schema.TaggedError<HeapSnapshotWriteError>()(
15 "HeapSnapshotWriteError",
16 { path: Schema.String, cause: Schema.Defect() },
17 ) {
18 override get message(): string {
19 return `Could not write a heap snapshot to ${this.path}.`;
20 }
21 }
22
23 const writeHeapSnapshot = Effect.fn("server.heapSnapshot", { root: true })(
24 function* (logsDir: string) {
25 const fs = yield* FileSystem.FileSystem;
26 const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");
27 const path = NodePath.join(logsDir, `server-${process.pid}-${timestamp}.heapsnapshot`);
28 yield* Effect.annotateCurrentSpan({ path });
29 yield* Effect.try({
30 try: () => NodeV8.writeHeapSnapshot(path),
31 catch: (cause) => new HeapSnapshotWriteError({ path, cause }),
32 }).pipe(Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore)));
33 yield* Effect.logInfo("Wrote heap snapshot.", { path });
34 },
35 Effect.catch((cause) => Effect.logWarning("Failed to write heap snapshot.", { cause })),
36 );
37
38 export const layer = Layer.effectDiscard(
39 Effect.gen(function* () {
40 if ((yield* HostProcess.Platform) === "win32") return;
41 const { logsDir } = yield* ServerConfig.ServerConfig;
42 const runFork = Effect.runForkWith(yield* Effect.context<FileSystem.FileSystem>());
43 const onSignal = () => void runFork(writeHeapSnapshot(logsDir));
44 yield* Effect.acquireRelease(
45 Effect.sync(() => process.on("SIGUSR2", onSignal)),
46 () => Effect.sync(() => process.off("SIGUSR2", onSignal)),
47 );
48 }),
49 );