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