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

DesktopTelemetryPublisher.ts

425 lines16.6 KB

1import {
2 DesktopHostTelemetryMessage,
3 type DesktopHostTelemetrySnapshot,
4 type DesktopTelemetryControlMessage,
5 type DesktopTelemetryCancelDesktopUpdate,
6 type DesktopTelemetryCommitDesktopUpdate,
7 type DesktopTelemetryRequestDesktopUpdate,
8 type DesktopUpdateStatusReport,
9 type HostPowerSnapshot,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as PubSub from "effect/PubSub";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23​
24import * as ElectronApp from "../electron/ElectronApp.ts";
25import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
26​
27const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
28const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
29const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
30const DEFAULT_HOST_POWER_ACTIVE_INTERVAL = Duration.seconds(30);
31const DEFAULT_HOST_POWER_IDLE_INTERVAL = Duration.minutes(2);
32const IDLE_THRESHOLD_SECONDS = 60;
33const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
34const textEncoder = new TextEncoder();
35​
36type PowerEvent =
37 | { readonly type: "locked"; readonly value: boolean }
38 | { readonly type: "suspended"; readonly value: boolean }
39 | { readonly type: "onBattery"; readonly value: boolean }
40 | { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
41 | { readonly type: "speedLimit"; readonly value: number };
42​
43interface PowerState {
44 readonly idle: HostPowerSnapshot["idle"];
45 readonly locked: HostPowerSnapshot["locked"];
46 readonly lockedEventPending: boolean;
47 readonly suspended: boolean;
48 readonly suspendedEventPending: boolean;
49 readonly onBattery: HostPowerSnapshot["onBattery"];
50 readonly onBatteryEventPending: boolean;
51 readonly thermalState: HostPowerSnapshot["thermalState"];
52 readonly speedLimitPercent: Option.Option<number>;
54​
55interface HostPowerIntervals {
56 readonly active: Duration.Duration;
57 readonly idle: Duration.Duration;
59​
60export class DesktopTelemetryPublisher extends Context.Service<
61 DesktopTelemetryPublisher,
62 {
63 readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
64 readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
65 readonly encoded: Stream.Stream<Uint8Array>;
66 readonly handleControlForSource: (
67 sourceId: string,
68 message: DesktopTelemetryControlMessage,
69 ) => Effect.Effect<void>;
70 readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
71 /** Sends the report to the attached backend and replays the latest one
72 to backends that attach later (including the one spawned after a
73 relaunch). */
74 readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
75 /** Update requests received over the control channel. Single consumer. */
76 readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
77 readonly updateCommits: Stream.Stream<DesktopTelemetryCommitDesktopUpdate>;
78 readonly updateCancellations: Stream.Stream<DesktopTelemetryCancelDesktopUpdate>;
79 }
80>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
81​
82function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
83 return value ? "true" : "false";
85​
86function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
87 switch (value) {
88 case "active":
89 return "false";
90 case "idle":
91 case "locked":
92 return "true";
93 case "unknown":
94 return "unknown";
95 }
97​
98function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
99 switch (event.type) {
100 case "locked":
101 return {
102 ...state,
103 locked: booleanState(event.value),
104 lockedEventPending: true,
105 };
106 case "suspended":
107 return {
108 ...state,
109 suspended: event.value,
110 suspendedEventPending: event.value,
111 };
112 case "onBattery":
113 return {
114 ...state,
115 onBattery: booleanState(event.value),
116 onBatteryEventPending: true,
117 };
118 case "thermal":
119 return { ...state, thermalState: event.value };
120 case "speedLimit":
121 return { ...state, speedLimitPercent: Option.some(event.value) };
122 }
124​
125function sampleInterval(
126 power: PowerState,
127 diagnosticsDemand: boolean,
128 hostPowerIntervals: HostPowerIntervals,
129): Duration.Duration {
130 if (!diagnosticsDemand) {
131 return power.suspended || power.locked === "true" || power.idle === "true"
132 ? hostPowerIntervals.idle
133 : hostPowerIntervals.active;
134 }
135 if (
136 power.suspended ||
137 power.locked === "true" ||
138 power.thermalState === "serious" ||
139 power.thermalState === "critical"
140 ) {
141 return CONSTRAINED_SAMPLE_INTERVAL;
142 }
143 if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
144 return LIVE_SAMPLE_INTERVAL;
146​
147/** @public Service construction is part of the canonical Effect module API. */
148export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
149 const electronApp = yield* ElectronApp.ElectronApp;
150 const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
151 yield* electronApp.whenReady;
152​
153 const initialPowerState: PowerState = {
154 idle: "unknown",
155 locked: "unknown",
156 lockedEventPending: false,
157 suspended: false,
158 suspendedEventPending: false,
159 onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
160 onBatteryEventPending: false,
161 thermalState: yield* powerMonitor.getCurrentThermalState,
162 speedLimitPercent: Option.none(),
163 };
164 const powerState = yield* Ref.make(initialPowerState);
165 const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
166 active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
167 idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
168 });
169 const powerEvents = yield* Queue.unbounded<PowerEvent>();
170 const sampleTriggers = yield* Queue.sliding<void>(1);
171 const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
172 const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
173 const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
174 const sequence = yield* Ref.make(0);
175 const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
176 const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
177 const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
178 const updateCommitQueue = yield* Queue.unbounded<DesktopTelemetryCommitDesktopUpdate>();
179 const updateCancellationQueue = yield* Queue.unbounded<DesktopTelemetryCancelDesktopUpdate>();
180​
181 const offer = (event: PowerEvent): void => {
182 Queue.offerUnsafe(powerEvents, event);
183 };
184 yield* Effect.all(
185 [
186 powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
187 powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
188 powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
189 powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
190 powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
191 powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
192 powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
193 powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
194 ],
195 { concurrency: "unbounded" },
196 );
197 yield* Effect.forever(
198 Queue.take(powerEvents).pipe(
199 Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
200 Effect.andThen(Queue.offer(sampleTriggers, undefined)),
201 ),
202 ).pipe(Effect.forkScoped);
203​
204 const sampleOnce = (allowSuspendRecovery: boolean) =>
205 Effect.gen(function* () {
206 const sampledAt = yield* DateTime.now;
207 const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
208 const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
209 const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
210 [
211 Ref.get(powerState),
212 powerMonitor.getSystemIdleTime,
213 powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
214 powerMonitor.isOnBatteryPower,
215 demand ? electronApp.getAppMetrics : Effect.succeed([]),
216 ],
217 { concurrency: "unbounded" },
218 );
219 const polledLocked =
220 systemIdleState === "unknown"
221 ? currentPower.locked
222 : booleanState(systemIdleState === "locked");
223 const polledOnBattery = booleanState(onBattery);
224 const observedPower = yield* Ref.modify(powerState, (latestPower) => {
225 const preserveEventLocked =
226 latestPower.lockedEventPending ||
227 latestPower.locked !== currentPower.locked ||
228 latestPower.lockedEventPending !== currentPower.lockedEventPending;
229 const preserveEventOnBattery =
230 latestPower.onBatteryEventPending ||
231 latestPower.onBattery !== currentPower.onBattery ||
232 latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
233 const preserveEventSuspended =
234 latestPower.suspendedEventPending ||
235 latestPower.suspended !== currentPower.suspended ||
236 latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
237 const next: PowerState = {
238 ...latestPower,
239 idle: idleState(systemIdleState),
240 locked: preserveEventLocked ? latestPower.locked : polledLocked,
241 lockedEventPending:
242 latestPower.lockedEventPending &&
243 (systemIdleState === "unknown" || polledLocked !== latestPower.locked),
244 suspended:
245 allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
246 suspendedEventPending: false,
247 onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
248 onBatteryEventPending:
249 latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
250 };
251 return [next, next] as const;
252 });
253 const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
254 const snapshot: DesktopHostTelemetrySnapshot = {
255 version: 1,
256 type: "desktopTelemetry",
257 sequence: nextSequence,
258 sampledAtUnixMs,
259 electronPid: process.pid,
260 power: {
261 source: "electron-main",
262 idle: observedPower.idle,
263 idleSeconds,
264 locked: observedPower.locked,
265 suspended: observedPower.suspended,
266 onBattery: observedPower.onBattery,
267 lowPowerMode: "unknown",
268 thermalState: observedPower.thermalState,
269 stale: false,
270 updatedAt: sampledAt,
271 },
272 speedLimitPercent: observedPower.speedLimitPercent,
273 electronProcesses: metrics.map((metric) => ({
274 pid: metric.pid,
275 creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
276 type: metric.type,
277 ...(metric.name === undefined ? {} : { name: metric.name }),
278 ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
279 cpuPercent: metric.cpu.percentCPUUsage,
280 ...(metric.cpu.cumulativeCPUUsage === undefined
281 ? {}
282 : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
283 idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
284 workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
285 peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
286 })),
287 };
288​
289 yield* Ref.set(latest, Option.some(snapshot));
290 yield* PubSub.publish(changes, snapshot);
291 }).pipe(
292 Effect.catchCauseIf(
293 (cause) => !Cause.hasInterrupts(cause),
294 (cause) =>
295 Effect.logWarning("Failed to sample Electron telemetry", {
296 cause: String(cause),
297 }),
298 ),
299 );
300​
301 yield* Effect.gen(function* () {
302 yield* sampleOnce(false);
303 while (true) {
304 const [currentPower, demand, intervals] = yield* Effect.all([
305 Ref.get(powerState),
306 Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
307 Ref.get(hostPowerIntervals),
308 ]);
309 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - races a trigger queue against the interval; both arms are real outcomes, not a timeout
310 const allowSuspendRecovery = yield* Effect.raceFirst(
311 Queue.take(sampleTriggers).pipe(Effect.as(false)),
312 Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
313 );
314 yield* sampleOnce(allowSuspendRecovery);
315 }
316 }).pipe(Effect.forkScoped);
317​
318 const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
319 sourceId,
320 message,
321 ) => {
322 switch (message.type) {
323 case "setDiagnosticsDemand":
324 return Ref.modify(diagnosticsDemandSources, (sources) => {
325 const previous = sources.size > 0;
326 const next = new Set(sources);
327 if (message.enabled) {
328 next.add(sourceId);
329 } else {
330 next.delete(sourceId);
331 }
332 return [[previous, next.size > 0] as const, next] as const;
333 }).pipe(
334 Effect.flatMap(([previous, enabled]) =>
335 previous === enabled
336 ? Effect.void
337 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
338 ),
339 );
340 case "setHostPowerIntervals":
341 return Ref.set(hostPowerIntervals, {
342 active: Duration.millis(message.activeIntervalMs),
343 idle: Duration.millis(message.idleIntervalMs),
344 }).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
345 case "requestDesktopUpdate":
346 return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
347 case "commitDesktopUpdate":
348 return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid);
349 case "cancelDesktopUpdate":
350 return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid);
351 }
352 };
353 const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
354 sourceId,
355 ) =>
356 Ref.modify(diagnosticsDemandSources, (sources) => {
357 const previous = sources.size > 0;
358 const next = new Set(sources);
359 next.delete(sourceId);
360 return [[previous, next.size > 0] as const, next] as const;
361 }).pipe(
362 Effect.flatMap(([previous, enabled]) =>
363 previous === enabled
364 ? Effect.void
365 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
366 ),
367 );
368​
369 const snapshots = Stream.unwrap(
370 Effect.gen(function* () {
371 const subscription = yield* PubSub.subscribe(changes);
372 const initial = yield* Ref.get(latest);
373 return Stream.concat(
374 Option.match(initial, {
375 onNone: () => Stream.empty,
376 onSome: Stream.make,
377 }),
378 Stream.fromSubscription(subscription),
379 );
380 }),
381 );
382 const updateReports = Stream.unwrap(
383 Effect.gen(function* () {
384 const subscription = yield* PubSub.subscribe(updateReportChanges);
385 const initial = yield* Ref.get(latestUpdateReport);
386 return Stream.concat(
387 Option.match(initial, {
388 onNone: () => Stream.empty,
389 onSome: Stream.make,
390 }),
391 Stream.fromSubscription(subscription),
392 );
393 }),
394 );
395 const encoded = Stream.concat(
396 Stream.make({
397 version: 1,
398 type: "desktopTelemetryHello",
399 electronPid: process.pid,
400 } as const),
401 Stream.merge(snapshots, updateReports),
402 ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
403​
404 const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
405 report,
406 ) =>
407 Ref.set(latestUpdateReport, Option.some(report)).pipe(
408 Effect.andThen(PubSub.publish(updateReportChanges, report)),
409 Effect.asVoid,
410 );
411​
412 return DesktopTelemetryPublisher.of({
413 latest: Ref.get(latest),
414 changes: Stream.fromPubSub(changes),
415 encoded,
416 handleControlForSource,
417 removeControlSource,
418 publishUpdateReport,
419 updateRequests: Stream.fromQueue(updateRequestQueue),
420 updateCommits: Stream.fromQueue(updateCommitQueue),
421 updateCancellations: Stream.fromQueue(updateCancellationQueue),
422 });
423});
424​
425export const layer = Layer.effect(DesktopTelemetryPublisher, make());