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

ResourceTelemetryHistory.ts

290 lines10.9 KB

1import type {
2 DesktopHostTelemetrySnapshot,
3 ResourceMonitorSnapshotEvent,
4 ResourceTelemetryHealth,
5 ResourceTelemetryHistory,
6 ResourceTelemetryHistoryBucket,
7 ResourceTelemetryProcess,
8 ResourceTelemetryProcessSummary,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Option from "effect/Option";
12​
13import {
14 emptyTelemetryCounters,
15 mergeProcesses,
16 processIdentityKey,
17 type ProcessState,
18 type TelemetryCounters,
19} from "./Model.ts";
20​
21const MAX_HISTORY_WINDOW_MS = 60 * 60_000;
22​
23export function normalizeResourceTelemetryHistoryInput(input: {
24 readonly windowMs: number;
25 readonly bucketMs: number;
26}): { readonly windowMs: number; readonly bucketMs: number } {
27 const windowMs = Math.max(1_000, Math.min(MAX_HISTORY_WINDOW_MS, input.windowMs));
28 return {
29 windowMs,
30 bucketMs: Math.max(1_000, Math.min(windowMs, input.bucketMs)),
31 };
33​
34interface AggregateSample {
35 readonly sampledAtMs: number;
36 readonly cpuPercent: number;
37 readonly rssBytes: number;
38 readonly processCount: number;
39 readonly ioReadBytes: number;
40 readonly ioWriteBytes: number;
42​
43interface ProcessSample {
44 readonly sampledAtMs: number;
45 readonly process: ResourceTelemetryProcess;
46 readonly cpuTimeMs: number;
47 readonly ioReadBytes: number;
48 readonly ioWriteBytes: number;
50​
51export interface BuildResourceTelemetryHistoryInput {
52 readonly readAt: DateTime.Utc;
53 readonly windowMs: number;
54 readonly bucketMs: number;
55 readonly sampleIntervalMs: number;
56 readonly serverPid: number;
57 readonly sidecarPid: Option.Option<number>;
58 readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
59 readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;
60 readonly health: ResourceTelemetryHealth;
62​
63export type ResourceTelemetryHistoryWithLegacyBuckets = ResourceTelemetryHistory & {
64 readonly legacyBackendBuckets?: ReadonlyArray<ResourceTelemetryHistoryBucket>;
65};
66​
67function summarizeProcesses(
68 samples: ReadonlyArray<ProcessSample>,
69): ReadonlyArray<ResourceTelemetryProcessSummary> {
70 const groups = new Map<string, ProcessSample[]>();
71 for (const sample of samples) {
72 const identityKey = processIdentityKey(
73 sample.process.identity.pid,
74 sample.process.identity.startTimeMs,
75 );
76 const current = groups.get(identityKey) ?? [];
77 current.push(sample);
78 groups.set(identityKey, current);
79 }
80​
81 return [...groups.values()]
82 .map((processSamples): ResourceTelemetryProcessSummary => {
83 const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
84 const first = sorted[0]!;
85 const latest = sorted[sorted.length - 1]!;
86 const cpuTotal = sorted.reduce((total, sample) => total + sample.process.cpuPercent, 0);
87 return {
88 identity: latest.process.identity,
89 ppid: latest.process.ppid,
90 depth: latest.process.depth,
91 name: latest.process.name,
92 command: latest.process.command,
93 category: latest.process.category,
94 firstSeenAt: first.process.firstSeenAt,
95 lastSeenAt: latest.process.lastSeenAt,
96 currentCpuPercent: latest.process.cpuPercent,
97 avgCpuPercent: cpuTotal / sorted.length,
98 maxCpuPercent: Math.max(...sorted.map((sample) => sample.process.cpuPercent)),
99 cpuTimeMs: sorted.reduce((total, sample) => total + sample.cpuTimeMs, 0),
100 currentRssBytes: latest.process.residentBytes,
101 peakRssBytes: Math.max(...sorted.map((sample) => sample.process.residentBytes)),
102 ioReadBytes: sorted.reduce((total, sample) => total + sample.ioReadBytes, 0),
103 ioWriteBytes: sorted.reduce((total, sample) => total + sample.ioWriteBytes, 0),
104 ioSemantics: latest.process.ioSemantics,
105 sampleCount: sorted.length,
106 };
107 })
108 .toSorted(
109 (left, right) => right.cpuTimeMs - left.cpuTimeMs || right.peakRssBytes - left.peakRssBytes,
110 );
112​
113function buildBuckets(input: {
114 readonly samples: ReadonlyArray<AggregateSample>;
115 readonly nowMs: number;
116 readonly windowMs: number;
117 readonly bucketMs: number;
118}): ReadonlyArray<ResourceTelemetryHistoryBucket> {
119 const windowStartMs = input.nowMs - input.windowMs;
120 const buckets: ResourceTelemetryHistoryBucket[] = [];
121 for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) {
122 const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs);
123 const samples = input.samples.filter(
124 (sample) =>
125 sample.sampledAtMs >= startedAtMs &&
126 (endedAtMs === input.nowMs
127 ? sample.sampledAtMs <= endedAtMs
128 : sample.sampledAtMs < endedAtMs),
129 );
130 const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0);
131 buckets.push({
132 startedAt: DateTime.makeUnsafe(startedAtMs),
133 endedAt: DateTime.makeUnsafe(endedAtMs),
134 avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,
135 maxCpuPercent:
136 samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),
137 maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),
138 ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),
139 ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),
140 maxProcessCount:
141 samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),
142 });
143 }
144 return buckets;
146​
147export function buildResourceTelemetryHistory(
148 input: BuildResourceTelemetryHistoryInput,
149): ResourceTelemetryHistoryWithLegacyBuckets & {
150 readonly legacyBackendBuckets: ReadonlyArray<ResourceTelemetryHistoryBucket>;
151} {
152 const readAtMs = DateTime.toEpochMillis(input.readAt);
153 const { windowMs, bucketMs } = normalizeResourceTelemetryHistoryInput(input);
154 const windowStartMs = readAtMs - windowMs;
155 const eligibleSnapshots = input.snapshots
156 .filter((snapshot) => snapshot.sampledAtUnixMs <= readAtMs)
157 .toSorted((left, right) => left.sampledAtUnixMs - right.sampledAtUnixMs);
158 const snapshotsInWindow = eligibleSnapshots.filter(
159 (snapshot) => snapshot.sampledAtUnixMs >= windowStartMs,
160 );
161 const precedingSnapshot = eligibleSnapshots.findLast(
162 (snapshot) => snapshot.sampledAtUnixMs < windowStartMs,
163 );
164 const snapshots = precedingSnapshot
165 ? [precedingSnapshot, ...snapshotsInWindow]
166 : snapshotsInWindow;
167 const aggregateSamples: AggregateSample[] = [];
168 const legacyBackendAggregateSamples: AggregateSample[] = [];
169 const processSamples: ProcessSample[] = [];
170 let previous: ReadonlyMap<string, ProcessState> = new Map();
171 let counters: TelemetryCounters = emptyTelemetryCounters();
172 let previousSnapshotAtMs: number | undefined;
173​
174 for (const snapshot of snapshots) {
175 const deltaWindowFraction =
176 previousSnapshotAtMs !== undefined &&
177 previousSnapshotAtMs < windowStartMs &&
178 snapshot.sampledAtUnixMs > previousSnapshotAtMs
179 ? Math.max(
180 0,
181 Math.min(
182 1,
183 (snapshot.sampledAtUnixMs - windowStartMs) /
184 (snapshot.sampledAtUnixMs - previousSnapshotAtMs),
185 ),
186 )
187 : 1;
188 previousSnapshotAtMs = snapshot.sampledAtUnixMs;
189 const recordedExternalProcesses =
190 snapshot.externalProcesses ??
191 Option.match(input.desktopSnapshot, {
192 onNone: () => [],
193 onSome: (desktopSnapshot) => [
194 {
195 pid: desktopSnapshot.electronPid,
196 startTimeMs: desktopSnapshot.electronProcesses.find(
197 (metric) => metric.pid === desktopSnapshot.electronPid,
198 )?.creationTimeMs,
199 },
200 ],
201 });
202 const electronRootPids = new Set(recordedExternalProcesses.map((process) => process.pid));
203 const electronRootStartTimes = new Map(
204 recordedExternalProcesses.flatMap((process) =>
205 process.startTimeMs === undefined ? [] : [[process.pid, process.startTimeMs] as const],
206 ),
207 );
208 const merged = mergeProcesses({
209 serverPid: input.serverPid,
210 sidecarPid: input.sidecarPid,
211 fallbackSampledAtMs: snapshot.sampledAtUnixMs,
212 nativeSnapshot: Option.some(snapshot),
213 desktopSnapshot: Option.none(),
214 electronRootPids,
215 electronRootStartTimes,
216 previous,
217 counters,
218 updatePrevious: true,
219 });
220 previous = new Map([...previous, ...merged.previous]);
221 counters = merged.counters;
222 if (snapshot.sampledAtUnixMs < windowStartMs) {
223 continue;
224 }
225 const deltas =
226 deltaWindowFraction === 1
227 ? merged.deltas
228 : merged.deltas.map((delta) => ({
229 ...delta,
230 cpuTimeMs: Math.round(delta.cpuTimeMs * deltaWindowFraction),
231 ioReadBytes: Math.round(delta.ioReadBytes * deltaWindowFraction),
232 ioWriteBytes: Math.round(delta.ioWriteBytes * deltaWindowFraction),
233 }));
234 const deltasByIdentity = new Map(
235 deltas.map((processDelta) => [processDelta.identityKey, processDelta]),
236 );
237 aggregateSamples.push({
238 sampledAtMs: snapshot.sampledAtUnixMs,
239 cpuPercent: merged.groups.allT3.currentCpuPercent,
240 rssBytes: merged.groups.allT3.currentRssBytes,
241 processCount: merged.groups.allT3.processCount,
242 ioReadBytes: deltas.reduce((total, process) => total + process.ioReadBytes, 0),
243 ioWriteBytes: deltas.reduce((total, process) => total + process.ioWriteBytes, 0),
244 });
245 const backendDeltas = deltas.filter(
246 (processDelta) =>
247 processDelta.category === "server" ||
248 processDelta.category === "server-child" ||
249 processDelta.category === "provider-root" ||
250 processDelta.category === "terminal-root",
251 );
252 legacyBackendAggregateSamples.push({
253 sampledAtMs: snapshot.sampledAtUnixMs,
254 cpuPercent: merged.groups.backend.currentCpuPercent,
255 rssBytes: merged.groups.backend.currentRssBytes,
256 processCount: merged.groups.backend.processCount,
257 ioReadBytes: backendDeltas.reduce((total, process) => total + process.ioReadBytes, 0),
258 ioWriteBytes: backendDeltas.reduce((total, process) => total + process.ioWriteBytes, 0),
259 });
260 for (const process of merged.processes) {
261 const processDelta = deltasByIdentity.get(
262 processIdentityKey(process.identity.pid, process.identity.startTimeMs),
263 );
264 processSamples.push({
265 sampledAtMs: snapshot.sampledAtUnixMs,
266 process,
267 cpuTimeMs: processDelta?.cpuTimeMs ?? 0,
268 ioReadBytes: processDelta?.ioReadBytes ?? 0,
269 ioWriteBytes: processDelta?.ioWriteBytes ?? 0,
270 });
271 }
272 }
273​
274 return {
275 readAt: input.readAt,
276 windowMs,
277 bucketMs,
278 sampleIntervalMs: input.sampleIntervalMs,
279 retainedSampleCount: aggregateSamples.length + processSamples.length,
280 buckets: buildBuckets({ samples: aggregateSamples, nowMs: readAtMs, windowMs, bucketMs }),
281 legacyBackendBuckets: buildBuckets({
282 samples: legacyBackendAggregateSamples,
283 nowMs: readAtMs,
284 windowMs,
285 bucketMs,
286 }),
287 topProcesses: summarizeProcesses(processSamples),
288 health: input.health,
289 };