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

ProcessDiagnostics.ts

575 lines17.8 KB

1import type {
2 ServerProcessDiagnosticsEntry,
3 ServerProcessDiagnosticsResult,
4 ServerProcessSignal,
5 ServerSignalProcessResult,
6} from "@t3tools/contracts";
7import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
8import * as Context from "effect/Context";
9import * as DateTime from "effect/DateTime";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15import * as ChildProcess from "effect/unstable/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
17​
18import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
19​
20export interface ProcessRow {
21 readonly pid: number;
22 readonly ppid: number;
23 readonly pgid: number | null;
24 readonly status: string;
25 readonly cpuPercent: number;
26 readonly rssBytes: number;
27 readonly elapsed: string;
28 readonly command: string;
30​
31const PROCESS_QUERY_TIMEOUT_MS = 1_000;
32const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
33const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
34​
35export class ProcessDiagnostics extends Context.Service<
36 ProcessDiagnostics,
37 {
38 readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
39 readonly signal: (input: {
40 readonly pid: number;
41 readonly signal: ServerProcessSignal;
42 }) => Effect.Effect<ServerSignalProcessResult>;
43 }
44>()("t3/diagnostics/ProcessDiagnostics") {}
45​
46class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
47 "ProcessDiagnosticsQueryTimeoutError",
48 {
49 command: Schema.String,
50 argCount: Schema.Number,
51 cwd: Schema.String,
52 timeoutMillis: Schema.Number,
53 },
54) {
55 override get message(): string {
56 return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
57 }
59​
60class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryFailedError>()(
61 "ProcessDiagnosticsQueryFailedError",
62 {
63 command: Schema.String,
64 argCount: Schema.Number,
65 cwd: Schema.String,
66 exitCode: Schema.optional(Schema.Number),
67 stdoutBytes: Schema.optional(Schema.Number),
68 stderrBytes: Schema.optional(Schema.Number),
69 stdoutTruncated: Schema.optional(Schema.Boolean),
70 stderrTruncated: Schema.optional(Schema.Boolean),
71 cause: Schema.optional(Schema.Defect()),
72 },
73) {
74 override get message(): string {
75 const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
76 return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
77 }
79​
80class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass<ProcessDiagnosticsServerProcessSignalError>()(
81 "ProcessDiagnosticsServerProcessSignalError",
82 { pid: Schema.Number },
83) {
84 override get message(): string {
85 return "Refusing to signal the T3 server process.";
86 }
88​
89class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
90 "ProcessDiagnosticsNotDescendantError",
91 {
92 pid: Schema.Number,
93 serverPid: Schema.Number,
94 },
95) {
96 override get message(): string {
97 return `Process ${this.pid} is not a live descendant of the T3 server.`;
98 }
100​
101class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
102 "ProcessDiagnosticsSignalFailedError",
103 {
104 pid: Schema.Number,
105 signal: Schema.String,
106 cause: Schema.Defect(),
107 },
108) {
109 override get message(): string {
110 return `Failed to signal process ${this.pid} with ${this.signal}.`;
111 }
113​
114const ProcessDiagnosticsError = Schema.Union([
115 ProcessDiagnosticsQueryTimeoutError,
116 ProcessDiagnosticsQueryFailedError,
117 ProcessDiagnosticsServerProcessSignalError,
118 ProcessDiagnosticsNotDescendantError,
119 ProcessDiagnosticsSignalFailedError,
120]);
121type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
122const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
123​
124function parsePositiveInt(value: string): number | null {
125 const parsed = Number.parseInt(value, 10);
126 return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
128​
129function parseNonNegativeInt(value: string): number | null {
130 const parsed = Number.parseInt(value, 10);
131 return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
133​
134function parseNumber(value: string): number | null {
135 const parsed = Number.parseFloat(value);
136 return Number.isFinite(parsed) ? parsed : null;
138​
139export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
140 const rows: ProcessRow[] = [];
141 const rowPattern =
142 /^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
143​
144 for (const line of output.split(/\r?\n/)) {
145 if (line.trim().length === 0) continue;
146​
147 const match = rowPattern.exec(line);
148 if (!match) continue;
149​
150 const pidText = match[1];
151 const ppidText = match[2];
152 const pgidText = match[3];
153 const status = match[4];
154 const cpuText = match[5];
155 const rssText = match[6];
156 const elapsed = match[7];
157 const command = match[8];
158 if (
159 pidText === undefined ||
160 ppidText === undefined ||
161 pgidText === undefined ||
162 status === undefined ||
163 cpuText === undefined ||
164 rssText === undefined ||
165 elapsed === undefined ||
166 command === undefined
167 ) {
168 continue;
169 }
170​
171 const pid = parsePositiveInt(pidText);
172 const ppid = parseNonNegativeInt(ppidText);
173 const pgid = Number.parseInt(pgidText, 10);
174 const cpuPercent = parseNumber(cpuText);
175 const rssKiB = parseNonNegativeInt(rssText);
176 if (
177 pid === null ||
178 ppid === null ||
179 !Number.isInteger(pgid) ||
180 cpuPercent === null ||
181 rssKiB === null ||
182 !status ||
183 !elapsed ||
184 !command
185 ) {
186 continue;
187 }
188​
189 rows.push({
190 pid,
191 ppid,
192 pgid,
193 status,
194 cpuPercent,
195 rssBytes: rssKiB * 1024,
196 elapsed,
197 command,
198 });
199 }
200​
201 return rows;
203​
204function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
205 if (typeof value !== "object" || value === null) return null;
206 const record = value as Record<string, unknown>;
207 const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
208 const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
209 const commandLine =
210 typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
211 ? record.CommandLine
212 : typeof record.Name === "string"
213 ? record.Name
214 : null;
215 const workingSet =
216 typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
217 ? Math.max(0, Math.round(record.WorkingSetSize))
218 : 0;
219 const cpuPercent =
220 typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
221 ? Math.max(0, record.PercentProcessorTime)
222 : 0;
223​
224 if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
225 return {
226 pid,
227 ppid,
228 pgid: null,
229 status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
230 cpuPercent,
231 rssBytes: workingSet,
232 elapsed: "",
233 command: commandLine,
234 };
236​
237function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
238 if (output.trim().length === 0) return [];
239 try {
240 const parsed = JSON.parse(output) as unknown;
241 const records = Array.isArray(parsed) ? parsed : [parsed];
242 return records.flatMap((record) => {
243 const row = normalizeWindowsProcessRow(record);
244 return row ? [row] : [];
245 });
246 } catch {
247 return [];
248 }
250​
251export function buildDescendantEntries(
252 rows: ReadonlyArray<ProcessRow>,
253 serverPid: number,
254): ReadonlyArray<ServerProcessDiagnosticsEntry> {
255 const childrenByParent = new Map<number, ProcessRow[]>();
256 for (const row of rows) {
257 const children = childrenByParent.get(row.ppid) ?? [];
258 children.push(row);
259 childrenByParent.set(row.ppid, children);
260 }
261​
262 const entries: ServerProcessDiagnosticsEntry[] = [];
263 const visited = new Set<number>();
264 const stack = [...(childrenByParent.get(serverPid) ?? [])]
265 .toSorted((left, right) => left.pid - right.pid)
266 .map((row) => ({ row, depth: 0 }));
267​
268 while (stack.length > 0) {
269 const item = stack.shift();
270 if (!item || visited.has(item.row.pid)) continue;
271 visited.add(item.row.pid);
272​
273 const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
274 (left, right) => left.pid - right.pid,
275 );
276 entries.push({
277 pid: item.row.pid,
278 ppid: item.row.ppid,
279 pgid: Option.fromNullishOr(item.row.pgid),
280 status: item.row.status,
281 cpuPercent: item.row.cpuPercent,
282 rssBytes: item.row.rssBytes,
283 elapsed: item.row.elapsed || "n/a",
284 command: item.row.command,
285 depth: item.depth,
286 childPids: children.map((child) => child.pid),
287 });
288​
289 stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
290 }
291​
292 return entries;
294​
295export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
296 if (row.ppid !== serverPid) return false;
297​
298 const command = row.command.trim();
299 return (
300 /(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
301 (/\bpowershell(?:\.exe)?\b/i.test(command) &&
302 /\bGet-CimInstance\s+Win32_Process\b/i.test(command))
303 );
305​
306function makeResult(input: {
307 readonly serverPid: number;
308 readonly rows: ReadonlyArray<ProcessRow>;
309 readonly readAt: DateTime.Utc;
310 readonly error?: string;
311}): ServerProcessDiagnosticsResult {
312 const readAt = input.readAt;
313 const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
314 const processes = buildDescendantEntries(rows, input.serverPid);
315 const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
316 const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
317​
318 return {
319 serverPid: input.serverPid,
320 readAt,
321 processCount: processes.length,
322 totalRssBytes,
323 totalCpuPercent,
324 processes,
325 error: input.error ? Option.some({ message: input.error }) : Option.none(),
326 };
328​
329interface ProcessOutput {
330 readonly cwd: string;
331 readonly exitCode: number;
332 readonly stdout: string;
333 readonly stdoutBytes: number;
334 readonly stdoutTruncated: boolean;
335 readonly stderr: string;
336 readonly stderrBytes: number;
337 readonly stderrTruncated: boolean;
339​
340const runProcess = Effect.fn("runProcess")(function* (input: {
341 readonly command: string;
342 readonly args: ReadonlyArray<string>;
343}) {
344 const cwd = process.cwd();
345 return yield* Effect.gen(function* () {
346 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
347 // `ps` and `powershell.exe` are real executables; spawning through cmd.exe
348 // shell mode would re-tokenize the PowerShell `-Command` payload (which
349 // contains pipes) before PowerShell ever sees it.
350 const child = yield* spawner.spawn(
351 ChildProcess.make(input.command, input.args, {
352 cwd,
353 }),
354 );
355 const [stdout, stderr, exitCode] = yield* Effect.all(
356 [
357 collectUint8StreamText({
358 stream: child.stdout,
359 maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
360 truncatedMarker: "\n\n[truncated]",
361 }),
362 collectUint8StreamText({
363 stream: child.stderr,
364 maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
365 truncatedMarker: "\n\n[truncated]",
366 }),
367 child.exitCode,
368 ],
369 { concurrency: "unbounded" },
370 );
371​
372 return {
373 cwd,
374 exitCode,
375 stdout: stdout.text,
376 stdoutBytes: stdout.bytes,
377 stdoutTruncated: stdout.truncated,
378 stderr: stderr.text,
379 stderrBytes: stderr.bytes,
380 stderrTruncated: stderr.truncated,
381 } satisfies ProcessOutput;
382 }).pipe(
383 Effect.scoped,
384 Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
385 Effect.flatMap((result) =>
386 Option.match(result, {
387 onNone: () =>
388 Effect.fail(
389 new ProcessDiagnosticsQueryTimeoutError({
390 command: input.command,
391 argCount: input.args.length,
392 cwd,
393 timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
394 }),
395 ),
396 onSome: Effect.succeed,
397 }),
398 ),
399 Effect.mapError((cause) =>
400 isProcessDiagnosticsError(cause)
401 ? cause
402 : new ProcessDiagnosticsQueryFailedError({
403 command: input.command,
404 argCount: input.args.length,
405 cwd,
406 cause,
407 }),
408 ),
409 );
410});
411​
412function readPosixProcessRows(): Effect.Effect<
413 ReadonlyArray<ProcessRow>,
414 ProcessDiagnosticsError,
415 ChildProcessSpawner.ChildProcessSpawner
416> {
417 return runProcess({
418 command: "ps",
419 args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
420 }).pipe(
421 Effect.flatMap((result) =>
422 result.exitCode !== 0
423 ? Effect.fail(
424 new ProcessDiagnosticsQueryFailedError({
425 command: "ps",
426 argCount: 2,
427 cwd: result.cwd,
428 exitCode: result.exitCode,
429 stdoutBytes: result.stdoutBytes,
430 stderrBytes: result.stderrBytes,
431 stdoutTruncated: result.stdoutTruncated,
432 stderrTruncated: result.stderrTruncated,
433 }),
434 )
435 : Effect.succeed(parsePosixProcessRows(result.stdout)),
436 ),
437 );
439​
440function readWindowsProcessRows(): Effect.Effect<
441 ReadonlyArray<ProcessRow>,
442 ProcessDiagnosticsError,
443 ChildProcessSpawner.ChildProcessSpawner
444> {
445 const command = [
446 "$processes = Get-CimInstance Win32_Process | ForEach-Object {",
447 '$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
448 "[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
449 "};",
450 "$processes | ConvertTo-Json -Compress -Depth 3",
451 ].join(" ");
452​
453 return runProcess({
454 command: "powershell.exe",
455 args: ["-NoProfile", "-NonInteractive", "-Command", command],
456 }).pipe(
457 Effect.flatMap((result) =>
458 result.exitCode !== 0
459 ? Effect.fail(
460 new ProcessDiagnosticsQueryFailedError({
461 command: "powershell.exe",
462 argCount: 4,
463 cwd: result.cwd,
464 exitCode: result.exitCode,
465 stdoutBytes: result.stdoutBytes,
466 stderrBytes: result.stderrBytes,
467 stdoutTruncated: result.stdoutTruncated,
468 stderrTruncated: result.stderrTruncated,
469 }),
470 )
471 : Effect.succeed(parseWindowsProcessRows(result.stdout)),
472 ),
473 );
475​
476export const readProcessRows = Effect.gen(function* () {
477 const platform = yield* HostProcessPlatform;
478 return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
479});
480​
481export function aggregateProcessDiagnostics(input: {
482 readonly serverPid: number;
483 readonly rows: ReadonlyArray<ProcessRow>;
484 readonly readAt: DateTime.Utc;
485}): ServerProcessDiagnosticsResult {
486 return makeResult(input);
488​
489function assertDescendantPid(
490 pid: number,
491): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
492 if (pid === process.pid) {
493 return Effect.fail(
494 new ProcessDiagnosticsServerProcessSignalError({
495 pid,
496 }),
497 );
498 }
499​
500 return readProcessRows.pipe(
501 Effect.flatMap((rows) => {
502 const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
503 const descendant = buildDescendantEntries(filteredRows, process.pid).some(
504 (entry) => entry.pid === pid,
505 );
506 return descendant
507 ? Effect.void
508 : Effect.fail(
509 new ProcessDiagnosticsNotDescendantError({
510 pid,
511 serverPid: process.pid,
512 }),
513 );
514 }),
515 );
517​
518export const make = Effect.gen(function* () {
519 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
520​
521 const read: ProcessDiagnostics["Service"]["read"] = Effect.gen(function* () {
522 const readAt = yield* DateTime.now;
523 const rows = yield* readProcessRows.pipe(
524 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
525 );
526 return makeResult({ serverPid: process.pid, rows, readAt });
527 }).pipe(
528 Effect.catch((error: ProcessDiagnosticsError) =>
529 DateTime.now.pipe(
530 Effect.map((readAt) =>
531 makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
532 ),
533 ),
534 ),
535 );
536​
537 const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
538 function* (input) {
539 return yield* assertDescendantPid(input.pid).pipe(
540 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
541 Effect.flatMap(() =>
542 Effect.try({
543 try: () => {
544 process.kill(input.pid, input.signal);
545 return {
546 pid: input.pid,
547 signal: input.signal,
548 signaled: true,
549 message: Option.none(),
550 };
551 },
552 catch: (cause) =>
553 new ProcessDiagnosticsSignalFailedError({
554 pid: input.pid,
555 signal: input.signal,
556 cause,
557 }),
558 }),
559 ),
560 Effect.catch((error: ProcessDiagnosticsError) =>
561 Effect.succeed({
562 pid: input.pid,
563 signal: input.signal,
564 signaled: false,
565 message: Option.some(error.message),
566 }),
567 ),
568 );
569 },
570 );
571​
572 return ProcessDiagnostics.of({ read, signal });
573});
574​
575export const layer = Layer.effect(ProcessDiagnostics, make);