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

ProcessDiagnostics.ts

461 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 }),
284 );
285 const [stdout, stderr, exitCode] = yield* Effect.all(
286 [
287 collectUint8StreamText({
288 stream: child.stdout,
289 maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
290 truncatedMarker: "\n\n[truncated]",
291 }),
292 collectUint8StreamText({
293 stream: child.stderr,
294 maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
295 truncatedMarker: "\n\n[truncated]",
296 }),
297 child.exitCode,
298 ],
299 { concurrency: "unbounded" },
300 );
301​
302 return {
303 exitCode,
304 stdout: stdout.text,
305 stderr: stderr.text,
306 } satisfies ProcessOutput;
307 },
308 (effect, input) =>
309 effect.pipe(
310 Effect.scoped,
311 Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
312 Effect.flatMap((result) =>
313 Option.match(result, {
314 onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
315 onSome: Effect.succeed,
316 }),
317 ),
318 Effect.mapError((cause) =>
319 isProcessDiagnosticsError(cause)
320 ? cause
321 : toProcessDiagnosticsError(input.errorMessage, cause),
322 ),
323 ),
324);
325​
326function readPosixProcessRows(): Effect.Effect<
327 ReadonlyArray<ProcessRow>,
328 ProcessDiagnosticsError,
329 ChildProcessSpawner.ChildProcessSpawner
330> {
331 return runProcess({
332 command: "ps",
333 args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
334 errorMessage: "Failed to query process diagnostics.",
335 }).pipe(
336 Effect.flatMap((result) =>
337 result.exitCode !== 0
338 ? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
339 : Effect.succeed(parsePosixProcessRows(result.stdout)),
340 ),
341 );
343​
344function readWindowsProcessRows(): Effect.Effect<
345 ReadonlyArray<ProcessRow>,
346 ProcessDiagnosticsError,
347 ChildProcessSpawner.ChildProcessSpawner
348> {
349 const command = [
350 "$processes = Get-CimInstance Win32_Process | ForEach-Object {",
351 '$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
352 "[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
353 "};",
354 "$processes | ConvertTo-Json -Compress -Depth 3",
355 ].join(" ");
356​
357 return runProcess({
358 command: "powershell.exe",
359 args: ["-NoProfile", "-NonInteractive", "-Command", command],
360 errorMessage: "Failed to query process diagnostics.",
361 }).pipe(
362 Effect.flatMap((result) =>
363 result.exitCode !== 0
364 ? Effect.fail(
365 toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
366 )
367 : Effect.succeed(parseWindowsProcessRows(result.stdout)),
368 ),
369 );
371​
372export const readProcessRows = (platform = process.platform) =>
373 platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
374​
375export function aggregateProcessDiagnostics(input: {
376 readonly serverPid: number;
377 readonly rows: ReadonlyArray<ProcessRow>;
378 readonly readAt: DateTime.Utc;
379}): ServerProcessDiagnosticsResult {
380 return makeResult(input);
382​
383function assertDescendantPid(
384 pid: number,
385): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
386 if (pid === process.pid) {
387 return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
388 }
389​
390 return readProcessRows().pipe(
391 Effect.flatMap((rows) => {
392 const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
393 const descendant = buildDescendantEntries(filteredRows, process.pid).some(
394 (entry) => entry.pid === pid,
395 );
396 return descendant
397 ? Effect.void
398 : Effect.fail(
399 toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
400 );
401 }),
402 );
404​
405export const make = Effect.fn("makeProcessDiagnostics")(function* () {
406 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
407​
408 const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
409 const readAt = yield* DateTime.now;
410 const rows = yield* readProcessRows().pipe(
411 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
412 );
413 return makeResult({ serverPid: process.pid, rows, readAt });
414 }).pipe(
415 Effect.catch((error: ProcessDiagnosticsError) =>
416 DateTime.now.pipe(
417 Effect.map((readAt) =>
418 makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
419 ),
420 ),
421 ),
422 );
423​
424 const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
425 function* (input) {
426 return yield* assertDescendantPid(input.pid).pipe(
427 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
428 Effect.flatMap(() =>
429 Effect.try({
430 try: () => {
431 process.kill(input.pid, input.signal);
432 return {
433 pid: input.pid,
434 signal: input.signal,
435 signaled: true,
436 message: Option.none(),
437 };
438 },
439 catch: (cause) =>
440 toProcessDiagnosticsError(
441 `Failed to signal process ${input.pid} with ${input.signal}.`,
442 cause,
443 ),
444 }),
445 ),
446 Effect.catch((error: ProcessDiagnosticsError) =>
447 Effect.succeed({
448 pid: input.pid,
449 signal: input.signal,
450 signaled: false,
451 message: Option.some(error.message),
452 }),
453 ),
454 );
455 },
456 );
457​
458 return ProcessDiagnostics.of({ read, signal });
459});
460​
461export const layer = Layer.effect(ProcessDiagnostics, make());