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

ResourceTelemetryHistory.ts

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