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

ProcessDiagnostics.ts

462 lines14.3 KB

1import type {
2 ServerProcessDiagnosticsEntry,
3 ServerProcessDiagnosticsResult,
4 ServerProcessSignal,
5 ServerSignalProcessResult,
6} from "@t3tools/contracts";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15​
16import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
17​
18export interface ProcessRow {
19 readonly pid: number;
20 readonly ppid: number;
21 readonly pgid: number | null;
22 readonly status: string;
23 readonly cpuPercent: number;
24 readonly rssBytes: number;
25 readonly elapsed: string;
26 readonly command: string;
28​
29const PROCESS_QUERY_TIMEOUT_MS = 1_000;
30const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
31const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
32​
33export interface ProcessDiagnosticsShape {
34 readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
35 readonly signal: (input: {
36 readonly pid: number;
37 readonly signal: ServerProcessSignal;
38 }) => Effect.Effect<ServerSignalProcessResult>;
40​
41export class ProcessDiagnostics extends Context.Service<
42 ProcessDiagnostics,
43 ProcessDiagnosticsShape
44>()("t3/diagnostics/ProcessDiagnostics") {}
45​
46class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
47 "ProcessDiagnosticsError",
48 {
49 message: Schema.String,
50 cause: Schema.optional(Schema.Defect),
51 },
52) {}
53const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
54​
55function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
56 return new ProcessDiagnosticsError({
57 message,
58 ...(cause === undefined ? {} : { cause }),
59 });
61​
62function parsePositiveInt(value: string): number | null {
63 const parsed = Number.parseInt(value, 10);
64 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
66​
67function parseNonNegativeInt(value: string): number | null {
68 const parsed = Number.parseInt(value, 10);
69 return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
71​
72function parseNumber(value: string): number | null {
73 const parsed = Number.parseFloat(value);
74 return Number.isFinite(parsed) ? parsed : null;
76​
77export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
78 const rows: ProcessRow[] = [];
79 const rowPattern =
80 /^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
81​
82 for (const line of output.split(/\r?\n/)) {
83 if (line.trim().length === 0) continue;
84​
85 const match = rowPattern.exec(line);
86 if (!match) continue;
87​
88 const pidText = match[1];
89 const ppidText = match[2];
90 const pgidText = match[3];
91 const status = match[4];
92 const cpuText = match[5];
93 const rssText = match[6];
94 const elapsed = match[7];
95 const command = match[8];
96 if (
97 pidText === undefined ||
98 ppidText === undefined ||
99 pgidText === undefined ||
100 status === undefined ||
101 cpuText === undefined ||
102 rssText === undefined ||
103 elapsed === undefined ||
104 command === undefined
105 ) {
106 continue;
107 }
108​
109 const pid = parsePositiveInt(pidText);
110 const ppid = parseNonNegativeInt(ppidText);
111 const pgid = Number.parseInt(pgidText, 10);
112 const cpuPercent = parseNumber(cpuText);
113 const rssKiB = parseNonNegativeInt(rssText);
114 if (
115 pid === null ||
116 ppid === null ||
117 !Number.isInteger(pgid) ||
118 cpuPercent === null ||
119 rssKiB === null ||
120 !status ||
121 !elapsed ||
122 !command
123 ) {
124 continue;
125 }
126​
127 rows.push({
128 pid,
129 ppid,
130 pgid,
131 status,
132 cpuPercent,
133 rssBytes: rssKiB * 1024,
134 elapsed,
135 command,
136 });
137 }
138​
139 return rows;
141​
142function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
143 if (typeof value !== "object" || value === null) return null;
144 const record = value as Record<string, unknown>;
145 const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
146 const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
147 const commandLine =
148 typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
149 ? record.CommandLine
150 : typeof record.Name === "string"
151 ? record.Name
152 : null;
153 const workingSet =
154 typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
155 ? Math.max(0, Math.round(record.WorkingSetSize))
156 : 0;
157 const cpuPercent =
158 typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
159 ? Math.max(0, record.PercentProcessorTime)
160 : 0;
161​
162 if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
163 return {
164 pid,
165 ppid,
166 pgid: null,
167 status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
168 cpuPercent,
169 rssBytes: workingSet,
170 elapsed: "",
171 command: commandLine,
172 };
174​
175function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
176 if (output.trim().length === 0) return [];
177 try {
178 const parsed = JSON.parse(output) as unknown;
179 const records = Array.isArray(parsed) ? parsed : [parsed];
180 return records.flatMap((record) => {
181 const row = normalizeWindowsProcessRow(record);
182 return row ? [row] : [];
183 });
184 } catch {
185 return [];
186 }
188​
189export function buildDescendantEntries(
190 rows: ReadonlyArray<ProcessRow>,
191 serverPid: number,
192): ReadonlyArray<ServerProcessDiagnosticsEntry> {
193 const childrenByParent = new Map<number, ProcessRow[]>();
194 for (const row of rows) {
195 const children = childrenByParent.get(row.ppid) ?? [];
196 children.push(row);
197 childrenByParent.set(row.ppid, children);
198 }
199​
200 const entries: ServerProcessDiagnosticsEntry[] = [];
201 const visited = new Set<number>();
202 const stack = [...(childrenByParent.get(serverPid) ?? [])]
203 .toSorted((left, right) => left.pid - right.pid)
204 .map((row) => ({ row, depth: 0 }));
205​
206 while (stack.length > 0) {
207 const item = stack.shift();
208 if (!item || visited.has(item.row.pid)) continue;
209 visited.add(item.row.pid);
210​
211 const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
212 (left, right) => left.pid - right.pid,
213 );
214 entries.push({
215 pid: item.row.pid,
216 ppid: item.row.ppid,
217 pgid: Option.fromNullishOr(item.row.pgid),
218 status: item.row.status,
219 cpuPercent: item.row.cpuPercent,
220 rssBytes: item.row.rssBytes,
221 elapsed: item.row.elapsed || "n/a",
222 command: item.row.command,
223 depth: item.depth,
224 childPids: children.map((child) => child.pid),
225 });
226​
227 stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
228 }
229​
230 return entries;
232​
233export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
234 if (row.ppid !== serverPid) return false;
235​
236 const command = row.command.trim();
237 return (
238 /(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
239 (/\bpowershell(?:\.exe)?\b/i.test(command) &&
240 /\bGet-CimInstance\s+Win32_Process\b/i.test(command))
241 );
243​
244function makeResult(input: {
245 readonly serverPid: number;
246 readonly rows: ReadonlyArray<ProcessRow>;
247 readonly readAt: DateTime.Utc;
248 readonly error?: string;
249}): ServerProcessDiagnosticsResult {
250 const readAt = input.readAt;
251 const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
252 const processes = buildDescendantEntries(rows, input.serverPid);
253 const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
254 const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
255​
256 return {
257 serverPid: input.serverPid,
258 readAt,
259 processCount: processes.length,
260 totalRssBytes,
261 totalCpuPercent,
262 processes,
263 error: input.error ? Option.some({ message: input.error }) : Option.none(),
264 };
266​
267interface ProcessOutput {
268 readonly exitCode: number;
269 readonly stdout: string;
270 readonly stderr: string;
272​
273const runProcess = Effect.fn("runProcess")(
274 function* (input: {
275 readonly command: string;
276 readonly args: ReadonlyArray<string>;
277 readonly errorMessage: string;
278 }) {
279 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
280 const child = yield* spawner.spawn(
281 ChildProcess.make(input.command, input.args, {
282 cwd: process.cwd(),
283 shell: process.platform === "win32",
284 }),
285 );
286 const [stdout, stderr, exitCode] = yield* Effect.all(
287 [
288 collectUint8StreamText({
289 stream: child.stdout,
290 maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
291 truncatedMarker: "\n\n[truncated]",
292 }),
293 collectUint8StreamText({
294 stream: child.stderr,
295 maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
296 truncatedMarker: "\n\n[truncated]",
297 }),
298 child.exitCode,
299 ],
300 { concurrency: "unbounded" },
301 );
302​
303 return {
304 exitCode,
305 stdout: stdout.text,
306 stderr: stderr.text,
307 } satisfies ProcessOutput;
308 },
309 (effect, input) =>
310 effect.pipe(
311 Effect.scoped,
312 Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
313 Effect.flatMap((result) =>
314 Option.match(result, {
315 onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
316 onSome: Effect.succeed,
317 }),
318 ),
319 Effect.mapError((cause) =>
320 isProcessDiagnosticsError(cause)
321 ? cause
322 : toProcessDiagnosticsError(input.errorMessage, cause),
323 ),
324 ),
325);
326​
327function readPosixProcessRows(): Effect.Effect<
328 ReadonlyArray<ProcessRow>,
329 ProcessDiagnosticsError,
330 ChildProcessSpawner.ChildProcessSpawner
331> {
332 return runProcess({
333 command: "ps",
334 args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
335 errorMessage: "Failed to query process diagnostics.",
336 }).pipe(
337 Effect.flatMap((result) =>
338 result.exitCode !== 0
339 ? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
340 : Effect.succeed(parsePosixProcessRows(result.stdout)),
341 ),
342 );
344​
345function readWindowsProcessRows(): Effect.Effect<
346 ReadonlyArray<ProcessRow>,
347 ProcessDiagnosticsError,
348 ChildProcessSpawner.ChildProcessSpawner
349> {
350 const command = [
351 "$processes = Get-CimInstance Win32_Process | ForEach-Object {",
352 '$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
353 "[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
354 "};",
355 "$processes | ConvertTo-Json -Compress -Depth 3",
356 ].join(" ");
357​
358 return runProcess({
359 command: "powershell.exe",
360 args: ["-NoProfile", "-NonInteractive", "-Command", command],
361 errorMessage: "Failed to query process diagnostics.",
362 }).pipe(
363 Effect.flatMap((result) =>
364 result.exitCode !== 0
365 ? Effect.fail(
366 toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
367 )
368 : Effect.succeed(parseWindowsProcessRows(result.stdout)),
369 ),
370 );
372​
373export const readProcessRows = (platform = process.platform) =>
374 platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
375​
376export function aggregateProcessDiagnostics(input: {
377 readonly serverPid: number;
378 readonly rows: ReadonlyArray<ProcessRow>;
379 readonly readAt: DateTime.Utc;
380}): ServerProcessDiagnosticsResult {
381 return makeResult(input);
383​
384function assertDescendantPid(
385 pid: number,
386): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
387 if (pid === process.pid) {
388 return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
389 }
390​
391 return readProcessRows().pipe(
392 Effect.flatMap((rows) => {
393 const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
394 const descendant = buildDescendantEntries(filteredRows, process.pid).some(
395 (entry) => entry.pid === pid,
396 );
397 return descendant
398 ? Effect.void
399 : Effect.fail(
400 toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
401 );
402 }),
403 );
405​
406export const make = Effect.fn("makeProcessDiagnostics")(function* () {
407 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
408​
409 const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
410 const readAt = yield* DateTime.now;
411 const rows = yield* readProcessRows().pipe(
412 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
413 );
414 return makeResult({ serverPid: process.pid, rows, readAt });
415 }).pipe(
416 Effect.catch((error: ProcessDiagnosticsError) =>
417 DateTime.now.pipe(
418 Effect.map((readAt) =>
419 makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
420 ),
421 ),
422 ),
423 );
424​
425 const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
426 function* (input) {
427 return yield* assertDescendantPid(input.pid).pipe(
428 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
429 Effect.flatMap(() =>
430 Effect.try({
431 try: () => {
432 process.kill(input.pid, input.signal);
433 return {
434 pid: input.pid,
435 signal: input.signal,
436 signaled: true,
437 message: Option.none(),
438 };
439 },
440 catch: (cause) =>
441 toProcessDiagnosticsError(
442 `Failed to signal process ${input.pid} with ${input.signal}.`,
443 cause,
444 ),
445 }),
446 ),
447 Effect.catch((error: ProcessDiagnosticsError) =>
448 Effect.succeed({
449 pid: input.pid,
450 signal: input.signal,
451 signaled: false,
452 message: Option.some(error.message),
453 }),
454 ),
455 );
456 },
457 );
458​
459 return ProcessDiagnostics.of({ read, signal });
460});
461​
462export const layer = Layer.effect(ProcessDiagnostics, make());