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

ResourceTelemetry.ts

504 lines17.8 KB

1import type {
2 DesktopHostTelemetrySnapshot,
3 HostPowerSnapshot,
4 ResourceMonitorSnapshotEvent,
5 ResourceTelemetryHealth,
6 ResourceTelemetryHistoryInput,
7 ResourceTelemetryProcessIdentity,
8 ResourceTelemetryRetryResult,
9 ResourceTelemetrySnapshot,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as PubSub from "effect/PubSub";
18import * as Ref from "effect/Ref";
19import * as Result from "effect/Result";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import * as Semaphore from "effect/Semaphore";
23import * as Stream from "effect/Stream";
24​
25import * as DesktopTelemetryReceiver from "./DesktopTelemetryReceiver.ts";
26import {
27 emptyTelemetryCounters,
28 mergeProcesses,
29 type ProcessState,
30 type TelemetryCounters,
31} from "./Model.ts";
32import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
33import * as ResourceAttribution from "./ResourceAttribution.ts";
34import {
35 buildResourceTelemetryHistory,
36 normalizeResourceTelemetryHistoryInput,
37 type ResourceTelemetryHistoryWithLegacyBuckets,
38} from "./ResourceTelemetryHistory.ts";
39import { subscribeBeforeSnapshot } from "../utils/subscribeBeforeSnapshot.ts";
40​
41export class ResourceTelemetryRefreshFailed extends Schema.TaggedErrorClass<ResourceTelemetryRefreshFailed>()(
42 "ResourceTelemetryRefreshFailed",
43 {
44 operation: Schema.String,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Resource telemetry operation '${this.operation}' failed.`;
50 }
52​
53export class ResourceTelemetry extends Context.Service<
54 ResourceTelemetry,
55 {
56 readonly latest: Effect.Effect<ResourceTelemetrySnapshot>;
57 readonly changes: Stream.Stream<ResourceTelemetrySnapshot>;
58 readonly subscribe: Effect.Effect<
59 {
60 readonly latest: ResourceTelemetrySnapshot;
61 readonly changes: Stream.Stream<ResourceTelemetrySnapshot>;
62 },
63 never,
64 Scope.Scope
65 >;
66 readonly readHistory: (
67 input: ResourceTelemetryHistoryInput,
68 ) => Effect.Effect<ResourceTelemetryHistoryWithLegacyBuckets>;
69 readonly refresh: Effect.Effect<ResourceTelemetrySnapshot, ResourceTelemetryRefreshFailed>;
70 readonly validateProcessIdentity: (
71 identity: ResourceTelemetryProcessIdentity,
72 ) => Effect.Effect<boolean, ResourceTelemetryRefreshFailed>;
73 readonly retry: Effect.Effect<ResourceTelemetryRetryResult>;
74 }
75>()("t3/resourceTelemetry/ResourceTelemetry") {}
76​
77interface TelemetryState {
78 readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;
79 readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;
80 readonly previous: ReadonlyMap<string, ProcessState>;
81 readonly counters: TelemetryCounters;
82 readonly latest: ResourceTelemetrySnapshot;
83 readonly lastNativeSequence: number;
84 readonly lastNativeGeneration: number;
86​
87interface LiveTelemetryState {
88 readonly retainCount: number;
89 readonly scope: Option.Option<Scope.Closeable>;
91​
92function unknownPower(updatedAt: DateTime.Utc): HostPowerSnapshot {
93 return {
94 source: "unknown",
95 idle: "unknown",
96 idleSeconds: null,
97 locked: "unknown",
98 suspended: false,
99 onBattery: "unknown",
100 lowPowerMode: "unknown",
101 thermalState: "unknown",
102 stale: true,
103 updatedAt,
104 };
106​
107function buildHealth(input: {
108 readonly native: NativeTelemetryClient.NativeTelemetryClientHealth;
109 readonly desktop: DesktopTelemetryReceiver.DesktopTelemetryReceiverHealth;
110 readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;
111}): ResourceTelemetryHealth {
112 return {
113 native: {
114 status: input.native.status,
115 lastSampleAt: input.native.lastSampleAt,
116 lastError: input.native.lastError,
117 },
118 desktop: {
119 status: input.desktop.status,
120 lastSampleAt: input.desktop.lastSampleAt,
121 lastError: input.desktop.lastError,
122 },
123 sidecarVersion: Option.map(input.native.hello, (hello) => hello.sidecarVersion),
124 sidecarPid: Option.map(input.native.hello, (hello) => hello.sidecarPid),
125 restartCount: input.native.restartCount,
126 collectionDurationMicros: Option.match(input.nativeSnapshot, {
127 onNone: () => 0,
128 onSome: (snapshot) => snapshot.collectionDurationMicros,
129 }),
130 scannedProcessCount: Option.match(input.nativeSnapshot, {
131 onNone: () => 0,
132 onSome: (snapshot) => snapshot.scannedProcessCount,
133 }),
134 retainedProcessCount: Option.match(input.nativeSnapshot, {
135 onNone: () => 0,
136 onSome: (snapshot) => snapshot.retainedProcessCount,
137 }),
138 inaccessibleProcessCount: Option.match(input.nativeSnapshot, {
139 onNone: () => 0,
140 onSome: (snapshot) => snapshot.inaccessibleProcessCount,
141 }),
142 };
144​
145export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(function* () {
146 const nativeClient = yield* NativeTelemetryClient.NativeTelemetryClient;
147 const desktopReceiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
148 const attribution = yield* ResourceAttribution.ResourceAttribution;
149 const mutex = yield* Semaphore.make(1);
150 const changes = yield* PubSub.sliding<ResourceTelemetrySnapshot>(8);
151 const initialReadAt = yield* DateTime.now;
152 const nativeHealthSubscription = yield* nativeClient.subscribeHealth;
153 const desktopHealthSubscription = yield* desktopReceiver.subscribeHealth;
154 const desktopSubscription = yield* desktopReceiver.subscribe;
155 const initialDesktop = desktopSubscription.latest;
156 if (Option.isSome(initialDesktop)) {
157 const electronRoot = initialDesktop.value.electronProcesses.find(
158 (process) => process.pid === initialDesktop.value.electronPid,
159 );
160 yield* nativeClient
161 .setExternalProcesses([
162 {
163 pid: initialDesktop.value.electronPid,
164 ...(electronRoot === undefined ? {} : { startTimeMs: electronRoot.creationTimeMs }),
165 },
166 ])
167 .pipe(Effect.ignore);
168 yield* nativeClient.setHostPowerState(initialDesktop.value.power).pipe(Effect.ignore);
169 }
170 const initialNativeHealth = nativeHealthSubscription.latest;
171 const initialDesktopHealth = desktopHealthSubscription.latest;
172 const initialAttribution = yield* attribution.snapshot;
173 const initialMerge = mergeProcesses({
174 serverPid: process.pid,
175 sidecarPid: Option.map(initialNativeHealth.hello, (hello) => hello.sidecarPid),
176 fallbackSampledAtMs: DateTime.toEpochMillis(initialReadAt),
177 nativeSnapshot: Option.none(),
178 desktopSnapshot: initialDesktop,
179 previous: new Map(),
180 counters: emptyTelemetryCounters(),
181 updatePrevious: false,
182 });
183 const initialSnapshot: ResourceTelemetrySnapshot = {
184 readAt: initialReadAt,
185 sampleIntervalMs: initialNativeHealth.sampleIntervalMs,
186 processes: initialMerge.processes,
187 groups: initialMerge.groups,
188 power: Option.match(initialDesktop, {
189 onNone: () => unknownPower(initialReadAt),
190 onSome: (desktop) => desktop.power,
191 }),
192 speedLimitPercent: Option.flatMap(initialDesktop, (desktop) => desktop.speedLimitPercent),
193 attribution: initialAttribution,
194 health: buildHealth({
195 native: initialNativeHealth,
196 desktop: initialDesktopHealth,
197 nativeSnapshot: Option.none(),
198 }),
199 };
200 const state = yield* Ref.make<TelemetryState>({
201 nativeSnapshot: Option.none(),
202 desktopSnapshot: initialDesktop,
203 previous: new Map(),
204 counters: emptyTelemetryCounters(),
205 latest: initialSnapshot,
206 lastNativeSequence: 0,
207 lastNativeGeneration: initialNativeHealth.restartCount,
208 });
209 const liveState = yield* Ref.make<LiveTelemetryState>({
210 retainCount: 0,
211 scope: Option.none(),
212 });
213 const liveMutex = yield* Semaphore.make(1);
214 const refreshHealth = mutex.withPermits(1)(
215 Effect.gen(function* () {
216 const current = yield* Ref.get(state);
217 const [nativeHealth, desktopHealth] = yield* Effect.all([
218 nativeClient.health,
219 desktopReceiver.health,
220 ]);
221 const snapshot: ResourceTelemetrySnapshot = {
222 ...current.latest,
223 health: buildHealth({
224 native: nativeHealth,
225 desktop: desktopHealth,
226 nativeSnapshot: current.nativeSnapshot,
227 }),
228 };
229 yield* Ref.set(state, {
230 ...current,
231 latest: snapshot,
232 });
233 if ((yield* Ref.get(liveState)).retainCount > 0) {
234 yield* PubSub.publish(changes, snapshot);
235 }
236 }),
237 );
238​
239 const rebuild = (input: {
240 readonly nativeSnapshot?: NativeTelemetryClient.NativeTelemetrySnapshot;
241 readonly desktopSnapshot?: DesktopHostTelemetrySnapshot;
242 readonly updatePrevious: boolean;
243 readonly publishWhenLive?: boolean;
244 }): Effect.Effect<ResourceTelemetrySnapshot> =>
245 mutex.withPermits(1)(
246 Effect.gen(function* () {
247 const current = yield* Ref.get(state);
248 const nativeHealth = yield* nativeClient.health;
249 const incomingNativeSnapshot = input.nativeSnapshot;
250 if (
251 incomingNativeSnapshot &&
252 (incomingNativeSnapshot.generation < nativeHealth.restartCount ||
253 incomingNativeSnapshot.generation < current.lastNativeGeneration ||
254 (incomingNativeSnapshot.generation === current.lastNativeGeneration &&
255 incomingNativeSnapshot.snapshot.sequence <= current.lastNativeSequence))
256 ) {
257 return current.latest;
258 }
259 const nativeSnapshot = incomingNativeSnapshot
260 ? Option.some(incomingNativeSnapshot.snapshot)
261 : current.nativeSnapshot;
262 const desktopSnapshot = input.desktopSnapshot
263 ? Option.some(input.desktopSnapshot)
264 : current.desktopSnapshot;
265 const [desktopHealth, attributionSnapshot] = yield* Effect.all([
266 desktopReceiver.health,
267 attribution.snapshot,
268 ]);
269 const recordedElectronRoots = Option.match(nativeSnapshot, {
270 onNone: () => [],
271 onSome: (snapshot) => snapshot.externalProcesses ?? [],
272 });
273 const electronRootPids = new Set(recordedElectronRoots.map((process) => process.pid));
274 Option.match(desktopSnapshot, {
275 onNone: () => undefined,
276 onSome: (desktop) => electronRootPids.add(desktop.electronPid),
277 });
278 const electronRootStartTimes = new Map(
279 recordedElectronRoots.flatMap((process) =>
280 process.startTimeMs === undefined ? [] : [[process.pid, process.startTimeMs] as const],
281 ),
282 );
283 const merged = mergeProcesses({
284 serverPid: process.pid,
285 sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
286 fallbackSampledAtMs: DateTime.toEpochMillis(current.latest.readAt),
287 nativeSnapshot,
288 desktopSnapshot,
289 electronRootPids,
290 electronRootStartTimes,
291 previous: current.previous,
292 counters: current.counters,
293 updatePrevious: input.updatePrevious,
294 });
295 const readAt = DateTime.makeUnsafe(merged.sampledAtMs);
296 const snapshot: ResourceTelemetrySnapshot = {
297 readAt,
298 sampleIntervalMs: nativeHealth.sampleIntervalMs,
299 processes: merged.processes,
300 groups: merged.groups,
301 power: Option.match(desktopSnapshot, {
302 onNone: () => unknownPower(readAt),
303 onSome: (desktop) => desktop.power,
304 }),
305 speedLimitPercent: Option.match(desktopSnapshot, {
306 onNone: () => Option.none(),
307 onSome: (desktop) => desktop.speedLimitPercent,
308 }),
309 attribution: attributionSnapshot,
310 health: buildHealth({
311 native: nativeHealth,
312 desktop: desktopHealth,
313 nativeSnapshot,
314 }),
315 };
316 yield* Ref.set(state, {
317 nativeSnapshot,
318 desktopSnapshot,
319 previous: merged.previous,
320 counters: merged.counters,
321 latest: snapshot,
322 lastNativeSequence:
323 incomingNativeSnapshot?.snapshot.sequence ?? current.lastNativeSequence,
324 lastNativeGeneration: incomingNativeSnapshot?.generation ?? current.lastNativeGeneration,
325 });
326 if (!input.publishWhenLive || (yield* Ref.get(liveState)).retainCount > 0) {
327 yield* PubSub.publish(changes, snapshot);
328 }
329 return snapshot;
330 }),
331 );
332​
333 const ingestNative = (snapshot: NativeTelemetryClient.NativeTelemetrySnapshot) =>
334 rebuild({ nativeSnapshot: snapshot, updatePrevious: true });
335 const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) =>
336 Effect.gen(function* () {
337 const electronRoot = snapshot.electronProcesses.find(
338 (process) => process.pid === snapshot.electronPid,
339 );
340 yield* nativeClient
341 .setExternalProcesses([
342 {
343 pid: snapshot.electronPid,
344 ...(electronRoot === undefined ? {} : { startTimeMs: electronRoot.creationTimeMs }),
345 },
346 ])
347 .pipe(Effect.ignore);
348 yield* nativeClient.setHostPowerState(snapshot.power).pipe(Effect.ignore);
349 return yield* rebuild({
350 desktopSnapshot: snapshot,
351 updatePrevious: false,
352 publishWhenLive: true,
353 });
354 });
355​
356 yield* desktopSubscription.changes.pipe(
357 Stream.runForEach((snapshot) => ingestDesktop(snapshot)),
358 Effect.forkScoped,
359 );
360​
361 const acquireLive = liveMutex.withPermits(1)(
362 Effect.uninterruptible(
363 Effect.gen(function* () {
364 const current = yield* Ref.get(liveState);
365 if (current.retainCount > 0) {
366 yield* Ref.set(liveState, { ...current, retainCount: current.retainCount + 1 });
367 return;
368 }
369​
370 const scope = yield* Scope.make();
371 yield* desktopReceiver.setDiagnosticsDemand(true).pipe(Effect.ignore);
372 yield* nativeClient.snapshots.pipe(
373 Stream.runForEach(ingestNative),
374 Effect.catch((error) =>
375 Effect.logWarning("Native resource telemetry stream stopped", {
376 cause: error.message,
377 }),
378 ),
379 Effect.forkIn(scope),
380 );
381 yield* nativeClient.sampleNow.pipe(
382 Effect.flatMap(ingestNative),
383 Effect.ignore,
384 Effect.forkIn(scope),
385 );
386 yield* Ref.set(liveState, { retainCount: 1, scope: Option.some(scope) });
387 }),
388 ),
389 );
390​
391 const releaseLive = liveMutex.withPermits(1)(
392 Effect.gen(function* () {
393 const current = yield* Ref.get(liveState);
394 if (current.retainCount <= 1) {
395 yield* Ref.set(liveState, { retainCount: 0, scope: Option.none() });
396 if (Option.isSome(current.scope)) {
397 yield* Scope.close(current.scope.value, Exit.void).pipe(Effect.ignore);
398 }
399 yield* desktopReceiver.setDiagnosticsDemand(false).pipe(Effect.ignore);
400 return;
401 }
402 yield* Ref.set(liveState, { ...current, retainCount: current.retainCount - 1 });
403 }),
404 );
405​
406 const latest = Ref.get(state).pipe(Effect.map((current) => current.latest));
407 const subscribe = subscribeBeforeSnapshot(
408 changes,
409 Effect.acquireRelease(acquireLive, () => releaseLive).pipe(Effect.andThen(latest)),
410 mutex,
411 );
412 const liveChanges = Stream.unwrap(Effect.map(subscribe, ({ changes }) => changes));
413​
414 const readHistory: ResourceTelemetry["Service"]["readHistory"] = (input) =>
415 Effect.gen(function* () {
416 const readAt = yield* DateTime.now;
417 const normalizedInput = normalizeResourceTelemetryHistoryInput(input);
418 const historyResult = yield* Effect.result(
419 nativeClient.readHistory(normalizedInput.windowMs),
420 );
421 if (Result.isFailure(historyResult)) {
422 yield* Effect.logWarning("Failed to read native resource telemetry history", {
423 cause: historyResult.failure.message,
424 });
425 }
426 const [nativeHealth, desktopHealth] = yield* Effect.all([
427 nativeClient.health,
428 desktopReceiver.health,
429 ]);
430 const current = yield* Ref.get(state);
431 return buildResourceTelemetryHistory({
432 readAt,
433 windowMs: normalizedInput.windowMs,
434 bucketMs: normalizedInput.bucketMs,
435 sampleIntervalMs: nativeHealth.sampleIntervalMs,
436 serverPid: process.pid,
437 sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
438 desktopSnapshot: current.desktopSnapshot,
439 snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],
440 health: buildHealth({
441 native: nativeHealth,
442 desktop: desktopHealth,
443 nativeSnapshot: current.nativeSnapshot,
444 }),
445 });
446 });
447 yield* nativeHealthSubscription.changes.pipe(
448 Stream.runForEach(() => refreshHealth),
449 Effect.forkScoped,
450 );
451 yield* desktopHealthSubscription.changes.pipe(
452 Stream.runForEach(() => refreshHealth),
453 Effect.forkScoped,
454 );
455​
456 const refresh: ResourceTelemetry["Service"]["refresh"] = nativeClient.sampleNow.pipe(
457 Effect.flatMap(ingestNative),
458 Effect.mapError(
459 (cause) =>
460 new ResourceTelemetryRefreshFailed({
461 operation: "refresh",
462 cause,
463 }),
464 ),
465 );
466​
467 const validateProcessIdentity: ResourceTelemetry["Service"]["validateProcessIdentity"] = (
468 identity,
469 ) =>
470 nativeClient.sampleNow.pipe(
471 Effect.map(({ snapshot }) =>
472 snapshot.processes.some(
473 (process) => process.pid === identity.pid && process.startTimeMs === identity.startTimeMs,
474 ),
475 ),
476 Effect.mapError(
477 (cause) =>
478 new ResourceTelemetryRefreshFailed({
479 operation: "validateProcessIdentity",
480 cause,
481 }),
482 ),
483 );
484​
485 return ResourceTelemetry.of({
486 latest,
487 changes: liveChanges,
488 subscribe,
489 readHistory,
490 refresh,
491 validateProcessIdentity,
492 retry: nativeClient.retry.pipe(
493 Effect.zip(Ref.get(state)),
494 Effect.map(
495 ([accepted, current]): ResourceTelemetryRetryResult => ({
496 accepted,
497 snapshot: current.latest,
498 }),
499 ),
500 ),
501 });
502});
503​
504export const layer = Layer.effect(ResourceTelemetry, make());