Open History to see the last commit
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>;
53}
54
55interface HostPowerIntervals {
56 readonly active: Duration.Duration;
57 readonly idle: Duration.Duration;
58}
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 handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
67 readonly handleControlForSource: (
68 sourceId: string,
69 message: DesktopTelemetryControlMessage,
70 ) => Effect.Effect<void>;
71 readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
72 /** Sends the report to the attached backend and replays the latest one
73 to backends that attach later (including the one spawned after a
74 relaunch). */
75 readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
76 /** Update requests received over the control channel. Single consumer. */
77 readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
78 readonly updateCommits: Stream.Stream<DesktopTelemetryCommitDesktopUpdate>;
79 readonly updateCancellations: Stream.Stream<DesktopTelemetryCancelDesktopUpdate>;
80 }
81>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
82
83function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
84 return value ? "true" : "false";
85}
86
87function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
88 switch (value) {
89 case "active":
90 return "false";
91 case "idle":
92 case "locked":
93 return "true";
94 case "unknown":
95 return "unknown";
96 }
97}
98
99function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
100 switch (event.type) {
101 case "locked":
102 return {
103 ...state,
104 locked: booleanState(event.value),
105 lockedEventPending: true,
106 };
107 case "suspended":
108 return {
109 ...state,
110 suspended: event.value,
111 suspendedEventPending: event.value,
112 };
113 case "onBattery":
114 return {
115 ...state,
116 onBattery: booleanState(event.value),
117 onBatteryEventPending: true,
118 };
119 case "thermal":
120 return { ...state, thermalState: event.value };
121 case "speedLimit":
122 return { ...state, speedLimitPercent: Option.some(event.value) };
123 }
124}
125
126function sampleInterval(
127 power: PowerState,
128 diagnosticsDemand: boolean,
129 hostPowerIntervals: HostPowerIntervals,
130): Duration.Duration {
131 if (!diagnosticsDemand) {
132 return power.suspended || power.locked === "true" || power.idle === "true"
133 ? hostPowerIntervals.idle
134 : hostPowerIntervals.active;
135 }
136 if (
137 power.suspended ||
138 power.locked === "true" ||
139 power.thermalState === "serious" ||
140 power.thermalState === "critical"
141 ) {
142 return CONSTRAINED_SAMPLE_INTERVAL;
143 }
144 if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
145 return LIVE_SAMPLE_INTERVAL;
146}
147
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.catchCause((cause) =>
293 Cause.hasInterrupts(cause)
294 ? Effect.failCause(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 const allowSuspendRecovery = yield* Effect.raceFirst(
310 Queue.take(sampleTriggers).pipe(Effect.as(false)),
311 Effect.sleep(sampleInterval(currentPower, demand, intervals)).pipe(Effect.as(true)),
312 );
313 yield* sampleOnce(allowSuspendRecovery);
314 }
315 }).pipe(Effect.forkScoped);
316
317 const handleControlForSource: DesktopTelemetryPublisher["Service"]["handleControlForSource"] = (
318 sourceId,
319 message,
320 ) => {
321 switch (message.type) {
322 case "setDiagnosticsDemand":
323 return Ref.modify(diagnosticsDemandSources, (sources) => {
324 const previous = sources.size > 0;
325 const next = new Set(sources);
326 if (message.enabled) {
327 next.add(sourceId);
328 } else {
329 next.delete(sourceId);
330 }
331 return [[previous, next.size > 0] as const, next] as const;
332 }).pipe(
333 Effect.flatMap(([previous, enabled]) =>
334 previous === enabled
335 ? Effect.void
336 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
337 ),
338 );
339 case "setHostPowerIntervals":
340 return Ref.set(hostPowerIntervals, {
341 active: Duration.millis(message.activeIntervalMs),
342 idle: Duration.millis(message.idleIntervalMs),
343 }).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
344 case "requestDesktopUpdate":
345 return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
346 case "commitDesktopUpdate":
347 return Queue.offer(updateCommitQueue, message).pipe(Effect.asVoid);
348 case "cancelDesktopUpdate":
349 return Queue.offer(updateCancellationQueue, message).pipe(Effect.asVoid);
350 }
351 };
352 const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
353 sourceId,
354 ) =>
355 Ref.modify(diagnosticsDemandSources, (sources) => {
356 const previous = sources.size > 0;
357 const next = new Set(sources);
358 next.delete(sourceId);
359 return [[previous, next.size > 0] as const, next] as const;
360 }).pipe(
361 Effect.flatMap(([previous, enabled]) =>
362 previous === enabled
363 ? Effect.void
364 : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
365 ),
366 );
367 const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>
368 handleControlForSource("legacy", message);
369
370 const snapshots = Stream.unwrap(
371 Effect.gen(function* () {
372 const subscription = yield* PubSub.subscribe(changes);
373 const initial = yield* Ref.get(latest);
374 return Stream.concat(
375 Option.match(initial, {
376 onNone: () => Stream.empty,
377 onSome: Stream.make,
378 }),
379 Stream.fromSubscription(subscription),
380 );
381 }),
382 );
383 const updateReports = Stream.unwrap(
384 Effect.gen(function* () {
385 const subscription = yield* PubSub.subscribe(updateReportChanges);
386 const initial = yield* Ref.get(latestUpdateReport);
387 return Stream.concat(
388 Option.match(initial, {
389 onNone: () => Stream.empty,
390 onSome: Stream.make,
391 }),
392 Stream.fromSubscription(subscription),
393 );
394 }),
395 );
396 const encoded = Stream.concat(
397 Stream.make({
398 version: 1,
399 type: "desktopTelemetryHello",
400 electronPid: process.pid,
401 } as const),
402 Stream.merge(snapshots, updateReports),
403 ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
404
405 const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
406 report,
407 ) =>
408 Ref.set(latestUpdateReport, Option.some(report)).pipe(
409 Effect.andThen(PubSub.publish(updateReportChanges, report)),
410 Effect.asVoid,
411 );
412
413 return DesktopTelemetryPublisher.of({
414 latest: Ref.get(latest),
415 changes: Stream.fromPubSub(changes),
416 encoded,
417 handleControl,
418 handleControlForSource,
419 removeControlSource,
420 publishUpdateReport,
421 updateRequests: Stream.fromQueue(updateRequestQueue),
422 updateCommits: Stream.fromQueue(updateCommitQueue),
423 updateCancellations: Stream.fromQueue(updateCancellationQueue),
424 });
425});
426
427export const layer = Layer.effect(DesktopTelemetryPublisher, make());