|
| 1 | +import type { ResourceTelemetryProcess } from "@t3tools/contracts"; |
| 2 | +import * as Effect from "effect/Effect"; |
| 3 | +import * as Layer from "effect/Layer"; |
| 4 | +import * as Metric from "effect/Metric"; |
| 5 | + |
| 6 | +import * as ServerConfig from "../config.ts"; |
| 7 | +import { metricAttributes } from "../observability/Metrics.ts"; |
| 8 | +import * as ResourceTelemetry from "./ResourceTelemetry.ts"; |
| 9 | + |
| 10 | +const SAMPLE_INTERVAL = "1 minute"; |
| 11 | + |
| 12 | +const residentBytes = Metric.gauge("t3_process_group_resident_bytes", { |
| 13 | + description: "Resident memory of the server's processes, summed by group.", |
| 14 | + attributes: { unit: "By" }, |
| 15 | +}); |
| 16 | +const cpuPercent = Metric.gauge("t3_process_group_cpu_percent", { |
| 17 | + description: "CPU use of the server's processes, summed by group; 100 is one full core.", |
| 18 | + attributes: { unit: "%" }, |
| 19 | +}); |
| 20 | +const processCount = Metric.gauge("t3_process_group_count", { |
| 21 | + description: "Processes in each group.", |
| 22 | + attributes: { unit: "{process}" }, |
| 23 | +}); |
| 24 | + |
| 25 | +// Each direct child of the server names the group of its whole subtree. A fixed set keeps one |
| 26 | +// series per group per server, however many agents and processes come and go. |
| 27 | +const PROVIDER_GROUPS: ReadonlyArray<readonly [RegExp, string]> = [ |
| 28 | + [/codex/, "codex"], |
| 29 | + [/claude/, "claude"], |
| 30 | + [/cursor/, "cursor"], |
| 31 | + [/opencode/, "opencode"], |
| 32 | + [/grok/, "grok"], |
| 33 | + [/antigravity|gemini/, "antigravity"], |
| 34 | +]; |
| 35 | +const OTHER_GROUPS: ReadonlyArray<readonly [RegExp, string]> = [ |
| 36 | + [/chrom/, "browser"], |
| 37 | + [/^(?:ba|z|fi|da|c)?sh(?:\.exe)?$|^pwsh|^powershell|^cmd\.exe$/, "terminal"], |
| 38 | +]; |
| 39 | +// A CLI shipped as a script runs under a JavaScript runtime, so its process name is the |
| 40 | +// runtime's (older Claude packages run `node .../@anthropic-ai/claude-code/cli.js`). Only those |
| 41 | +// are matched by command line; any other name is matched by name alone, so a shell or `git` |
| 42 | +// whose arguments mention a provider stays in its own group. |
| 43 | +const SCRIPT_RUNTIME = /^(?:node|bun|deno)(?:\.exe)?$/; |
| 44 | + |
| 45 | +const match = (groups: ReadonlyArray<readonly [RegExp, string]>, text: string) => |
| 46 | + groups.find(([pattern]) => pattern.test(text))?.[1]; |
| 47 | + |
| 48 | +const childGroup = (name: string, command: string) => { |
| 49 | + const lowerName = name.toLowerCase(); |
| 50 | + if (SCRIPT_RUNTIME.test(lowerName)) |
| 51 | + return match(PROVIDER_GROUPS, command.toLowerCase()) ?? "other"; |
| 52 | + return match(PROVIDER_GROUPS, lowerName) ?? match(OTHER_GROUPS, lowerName) ?? "other"; |
| 53 | +}; |
| 54 | + |
| 55 | +export interface ProcessGroupTotals { |
| 56 | + readonly residentBytes: number; |
| 57 | + readonly cpuPercent: number; |
| 58 | + readonly count: number; |
| 59 | +} |
| 60 | + |
| 61 | +export function groupProcesses( |
| 62 | + processes: ReadonlyArray<ResourceTelemetryProcess>, |
| 63 | +): ReadonlyMap<string, ProcessGroupTotals> { |
| 64 | + const byPid = new Map(processes.map((process) => [process.identity.pid, process])); |
| 65 | + const serverPid = processes.find((process) => process.category === "server")?.identity.pid; |
| 66 | + const groupOf = (process: ResourceTelemetryProcess): string => { |
| 67 | + if (process.category === "server") return "server"; |
| 68 | + if (process.category === "resource-monitor") return "resource-monitor"; |
| 69 | + if (process.category.startsWith("electron-")) return "electron"; |
| 70 | + let current = process; |
| 71 | + // Bounded by the table size, in case a reused PID makes the parent chain loop. |
| 72 | + for (let step = 0; step < processes.length; step++) { |
| 73 | + if (current.ppid === serverPid) return childGroup(current.name, current.command); |
| 74 | + const parent = byPid.get(current.ppid); |
| 75 | + if (parent === undefined) break; |
| 76 | + current = parent; |
| 77 | + } |
| 78 | + return "other"; |
| 79 | + }; |
| 80 | + const totals = new Map<string, ProcessGroupTotals>(); |
| 81 | + for (const process of processes) { |
| 82 | + const group = groupOf(process); |
| 83 | + const total = totals.get(group) ?? { residentBytes: 0, cpuPercent: 0, count: 0 }; |
| 84 | + totals.set(group, { |
| 85 | + residentBytes: total.residentBytes + process.residentBytes, |
| 86 | + cpuPercent: total.cpuPercent + process.cpuPercent, |
| 87 | + count: total.count + 1, |
| 88 | + }); |
| 89 | + } |
| 90 | + return totals; |
| 91 | +} |
| 92 | + |
| 93 | +/** |
| 94 | + * Exports process totals by group while OTLP metrics export is on. Sampling walks the process |
| 95 | + * table, which an idle server otherwise never does, so only a server exporting metrics pays for |
| 96 | + * it, once a minute. |
| 97 | + */ |
| 98 | +export const layer = Layer.effectDiscard( |
| 99 | + Effect.gen(function* () { |
| 100 | + const config = yield* ServerConfig.ServerConfig; |
| 101 | + if (config.otlpMetricsUrl === undefined) return; |
| 102 | + const telemetry = yield* ResourceTelemetry.ResourceTelemetry; |
| 103 | + // A group that empties reads zero rather than holding its last value. |
| 104 | + const seen = new Set<string>(); |
| 105 | + const sample = Effect.fn("ProcessGroupMetrics.sample")(function* () { |
| 106 | + const totals = groupProcesses((yield* telemetry.refresh).processes); |
| 107 | + for (const group of totals.keys()) seen.add(group); |
| 108 | + for (const group of seen) { |
| 109 | + const total = totals.get(group) ?? { residentBytes: 0, cpuPercent: 0, count: 0 }; |
| 110 | + const attributes = metricAttributes({ group }); |
| 111 | + yield* Metric.update(Metric.withAttributes(residentBytes, attributes), total.residentBytes); |
| 112 | + yield* Metric.update(Metric.withAttributes(cpuPercent, attributes), total.cpuPercent); |
| 113 | + yield* Metric.update(Metric.withAttributes(processCount, attributes), total.count); |
| 114 | + } |
| 115 | + }); |
| 116 | + yield* sample().pipe( |
| 117 | + Effect.catch((error) => |
| 118 | + Effect.logDebug("process group metrics sample failed", { error: error.message }), |
| 119 | + ), |
| 120 | + Effect.andThen(Effect.sleep(SAMPLE_INTERVAL)), |
| 121 | + Effect.forever, |
| 122 | + Effect.forkScoped, |
| 123 | + ); |
| 124 | + }), |
| 125 | +); |
0 commit comments