Open History to see the last commit
1import type {
2 ResourceTelemetryProcessCategory,
3 ServerProcessResourceHistoryInput,
4 ServerProcessResourceHistoryResult,
5} from "@t3tools/contracts";
6import * as Context from "effect/Context";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10
11import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
12
13export class ProcessResourceMonitor extends Context.Service<
14 ProcessResourceMonitor,
15 {
16 readonly readHistory: (
17 input: ServerProcessResourceHistoryInput,
18 ) => Effect.Effect<ServerProcessResourceHistoryResult>;
19 }
20>()("t3/diagnostics/ProcessResourceMonitor") {}
21
22function isLegacyBackendCategory(category: ResourceTelemetryProcessCategory): boolean {
23 return (
24 category === "server" ||
25 category === "server-child" ||
26 category === "provider-root" ||
27 category === "terminal-root"
28 );
29}
30
31export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
32 const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
33 const readHistory: ProcessResourceMonitor["Service"]["readHistory"] = (input) =>
34 telemetry.readHistory(input).pipe(
35 Effect.map((history) => {
36 const topProcesses = history.topProcesses
37 .filter((entry) => isLegacyBackendCategory(entry.category))
38 .map((entry) => ({
39 processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,
40 pid: entry.identity.pid,
41 ppid: entry.ppid,
42 command: entry.command || entry.name || "unknown",
43 depth: entry.depth,
44 isServerRoot: entry.category === "server",
45 firstSeenAt: entry.firstSeenAt,
46 lastSeenAt: entry.lastSeenAt,
47 currentCpuPercent: entry.currentCpuPercent,
48 avgCpuPercent: entry.avgCpuPercent,
49 maxCpuPercent: entry.maxCpuPercent,
50 cpuSecondsApprox: entry.cpuTimeMs / 1_000,
51 currentRssBytes: entry.currentRssBytes,
52 maxRssBytes: entry.peakRssBytes,
53 sampleCount: entry.sampleCount,
54 }));
55 return {
56 readAt: history.readAt,
57 windowMs: history.windowMs,
58 bucketMs: history.bucketMs,
59 sampleIntervalMs: history.sampleIntervalMs,
60 retainedSampleCount: history.retainedSampleCount,
61 totalCpuSecondsApprox: topProcesses.reduce(
62 (total, entry) => total + entry.cpuSecondsApprox,
63 0,
64 ),
65 buckets: (history.legacyBackendBuckets ?? history.buckets).map((bucket) => ({
66 startedAt: bucket.startedAt,
67 endedAt: bucket.endedAt,
68 avgCpuPercent: bucket.avgCpuPercent,
69 maxCpuPercent: bucket.maxCpuPercent,
70 maxRssBytes: bucket.maxRssBytes,
71 maxProcessCount: bucket.maxProcessCount,
72 })),
73 topProcesses,
74 error: history.health.native.lastError.pipe(
75 Option.map((message) => ({
76 failureTag: "ProcessDiagnosticsQueryFailedError" as const,
77 message,
78 })),
79 ),
80 };
81 }),
82 );
83
84 return ProcessResourceMonitor.of({ readHistory });
85});
86
87export const layer = Layer.effect(ProcessResourceMonitor, make());