Open History to see the last commit
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 }
27}
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")}`;
49}
50
51function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
52 return (
53 category === "server-child" || category === "provider-root" || category === "terminal-root"
54 );
55}
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(
65 (entry): ServerProcessDiagnosticsEntry => ({
66 pid: entry.identity.pid,
67 startTimeMs: entry.identity.startTimeMs,
68 ppid: entry.ppid,
69 pgid: Option.none(),
70 status: entry.status || "Unknown",
71 cpuPercent: entry.cpuPercent,
72 rssBytes: entry.residentBytes,
73 elapsed: formatElapsed(entry.runTimeMs),
74 command: entry.command || entry.name || "unknown",
75 depth: Math.max(0, entry.depth - 1),
76 childPids: entry.childPids,
77 }),
78 );
79 return {
80 serverPid: process.pid,
81 readAt: snapshot.readAt,
82 processCount: processes.length,
83 totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
84 totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
85 processes,
86 error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
87 };
88 }),
89 );
90
91 const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
92 function* (input) {
93 if (input.pid === process.pid) {
94 return {
95 pid: input.pid,
96 signal: input.signal,
97 signaled: false,
98 message: Option.some("Refusing to signal the T3 server process."),
99 };
100 }
101 const current = yield* telemetry.refresh.pipe(Effect.option);
102 if (Option.isNone(current)) {
103 return {
104 pid: input.pid,
105 signal: input.signal,
106 signaled: false,
107 message: Option.some(
108 `Could not refresh process ${input.pid}; refusing to signal a stale identity.`,
109 ),
110 };
111 }
112 const selected = current.value.processes.find(
113 (entry) =>
114 entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
115 );
116 if (!selected) {
117 return {
118 pid: input.pid,
119 signal: input.signal,
120 signaled: false,
121 message: Option.some(
122 `Process ${input.pid} no longer matches the selected process identity.`,
123 ),
124 };
125 }
126 if (!canSignalCategory(selected.category)) {
127 return {
128 pid: input.pid,
129 signal: input.signal,
130 signaled: false,
131 message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
132 };
133 }
134 return yield* Effect.try({
135 try: () => {
136 process.kill(input.pid, input.signal);
137 return {
138 pid: input.pid,
139 signal: input.signal,
140 signaled: true,
141 message: Option.none(),
142 };
143 },
144 catch: (cause) =>
145 new ProcessSignalFailed({
146 pid: input.pid,
147 signal: input.signal,
148 cause,
149 }),
150 }).pipe(
151 Effect.catch((error) =>
152 Effect.succeed({
153 pid: input.pid,
154 signal: input.signal,
155 signaled: false,
156 message: Option.some(
157 error instanceof Error ? error.message : "Failed to signal process.",
158 ),
159 }),
160 ),
161 );
162 },
163 );
164
165 return ProcessDiagnostics.of({ read, signal });
166});
167
168export const layer = Layer.effect(ProcessDiagnostics, make());