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

ProcessDiagnostics.ts

166 lines5.4 KB

1import type {
2 ResourceTelemetryProcessCategory,
3 ServerProcessDiagnosticsEntry,
4 ServerProcessDiagnosticsResult,
5 ServerProcessSignal,
6 ServerSignalProcessResult,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13​
14import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
15​
16export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
17 "ProcessSignalFailed",
18 {
19 pid: Schema.Number,
20 signal: Schema.String,
21 cause: Schema.Defect(),
22 },
23) {
24 override get message(): string {
25 return `Failed to signal process ${this.pid} with ${this.signal}.`;
26 }
28​
29export class ProcessDiagnostics extends Context.Service<
30 ProcessDiagnostics,
31 {
32 readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
33 readonly signal: (input: {
34 readonly pid: number;
35 readonly startTimeMs: number;
36 readonly signal: ServerProcessSignal;
37 }) => Effect.Effect<ServerSignalProcessResult>;
38 }
39>()("t3/diagnostics/ProcessDiagnostics") {}
40​
41function formatElapsed(runTimeMs: number): string {
42 const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));
43 const hours = Math.floor(totalSeconds / 3_600);
44 const minutes = Math.floor((totalSeconds % 3_600) / 60);
45 const seconds = totalSeconds % 60;
46 return hours > 0
47 ? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
48 : `${minutes}:${String(seconds).padStart(2, "0")}`;
50​
51function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
52 return (
53 category === "server-child" || category === "provider-root" || category === "terminal-root"
54 );
56​
57export const make = Effect.fn("makeProcessDiagnostics")(function* () {
58 const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
59 const refreshedTelemetry = telemetry.refresh.pipe(Effect.catch(() => telemetry.latest));
60 const read: ProcessDiagnostics["Service"]["read"] = refreshedTelemetry.pipe(
61 Effect.map((snapshot) => {
62 const processes = snapshot.processes
63 .filter((entry) => canSignalCategory(entry.category))
64 .map((entry): ServerProcessDiagnosticsEntry => ({
65 pid: entry.identity.pid,
66 startTimeMs: entry.identity.startTimeMs,
67 ppid: entry.ppid,
68 pgid: Option.none(),
69 status: entry.status || "Unknown",
70 cpuPercent: entry.cpuPercent,
71 rssBytes: entry.residentBytes,
72 elapsed: formatElapsed(entry.runTimeMs),
73 command: entry.command || entry.name || "unknown",
74 depth: Math.max(0, entry.depth - 1),
75 childPids: entry.childPids,
76 }));
77 return {
78 serverPid: process.pid,
79 readAt: snapshot.readAt,
80 processCount: processes.length,
81 totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
82 totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
83 processes,
84 error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
85 };
86 }),
87 );
88​
89 const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
90 function* (input) {
91 if (input.pid === process.pid) {
92 return {
93 pid: input.pid,
94 signal: input.signal,
95 signaled: false,
96 message: Option.some("Refusing to signal the T3 server process."),
97 };
98 }
99 const current = yield* telemetry.refresh.pipe(Effect.option);
100 if (Option.isNone(current)) {
101 return {
102 pid: input.pid,
103 signal: input.signal,
104 signaled: false,
105 message: Option.some(
106 `Could not refresh process ${input.pid}; refusing to signal a stale identity.`,
107 ),
108 };
109 }
110 const selected = current.value.processes.find(
111 (entry) =>
112 entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
113 );
114 if (!selected) {
115 return {
116 pid: input.pid,
117 signal: input.signal,
118 signaled: false,
119 message: Option.some(
120 `Process ${input.pid} no longer matches the selected process identity.`,
121 ),
122 };
123 }
124 if (!canSignalCategory(selected.category)) {
125 return {
126 pid: input.pid,
127 signal: input.signal,
128 signaled: false,
129 message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
130 };
131 }
132 return yield* Effect.try({
133 try: () => {
134 process.kill(input.pid, input.signal);
135 return {
136 pid: input.pid,
137 signal: input.signal,
138 signaled: true,
139 message: Option.none(),
140 };
141 },
142 catch: (cause) =>
143 new ProcessSignalFailed({
144 pid: input.pid,
145 signal: input.signal,
146 cause,
147 }),
148 }).pipe(
149 Effect.catch((error) =>
150 Effect.succeed({
151 pid: input.pid,
152 signal: input.signal,
153 signaled: false,
154 message: Option.some(
155 error instanceof Error ? error.message : "Failed to signal process.",
156 ),
157 }),
158 ),
159 );
160 },
161 );
162​
163 return ProcessDiagnostics.of({ read, signal });
164});
165​
166export const layer = Layer.effect(ProcessDiagnostics, make());