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
148/** @public Service construction is part of the canonical Effect module API. */
149export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
150 const electronApp = yield* ElectronApp.ElectronApp;
151 const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
152 yield* electronApp.whenReady;
153
154 const initialPowerState: PowerState = {
155 idle: "unknown",
156 locked: "unknown",
157 lockedEventPending: false,
158 suspended: false,
159 suspendedEventPending: false,
160 onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
161 onBatteryEventPending: false,
162 thermalState: yield* powerMonitor.getCurrentThermalState,
163 speedLimitPercent: Option.none(),
164 };
165 const powerState = yield* Ref.make(initialPowerState);
166 const hostPowerIntervals = yield* Ref.make<HostPowerIntervals>({
167 active: DEFAULT_HOST_POWER_ACTIVE_INTERVAL,
168 idle: DEFAULT_HOST_POWER_IDLE_INTERVAL,
169 });
170 const powerEvents = yield* Queue.unbounded<PowerEvent>();
171 const sampleTriggers = yield* Queue.sliding<void>(1);
172 const diagnosticsDemandSources = yield* Ref.make<ReadonlySet<string>>(new Set());
173 const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
174 const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
175 const sequence = yield* Ref.make(0);
176 const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
177 const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
178 const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
179 const updateCommitQueue = yield* Queue.unbounded<DesktopTelemetryCommitDesktopUpdate>();
180 const updateCancellationQueue = yield* Queue.unbounded<DesktopTelemetryCancelDesktopUpdate>();
181
182 const offer = (event: PowerEvent): void => {
183 Queue.offerUnsafe(powerEvents, event);
184 };
185 yield* Effect.all(
186 [
187 powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
188 powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
189 powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
190 powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
191 powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
192 powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
193 powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
194 powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
195 ],
196 { concurrency: "unbounded" },
197 );
198 yield* Effect.forever(
199 Queue.take(powerEvents).pipe(
200 Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
201 Effect.andThen(Queue.offer(sampleTriggers, undefined)),
202 ),
203 ).pipe(Effect.forkScoped);
204
205 const sampleOnce = (allowSuspendRecovery: boolean) =>
206 Effect.gen(function* () {
207 const sampledAt = yield* DateTime.now;
208 const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
209 const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
210 const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
211 [
212 Ref.get(powerState),
213 powerMonitor.getSystemIdleTime,
214 powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
215 powerMonitor.isOnBatteryPower,
216 demand ? electronApp.getAppMetrics : Effect.succeed([]),
217 ],
218 { concurrency: "unbounded" },
219 );
220 const polledLocked =
221 systemIdleState === "unknown"
222 ? currentPower.locked
223 : booleanState(systemIdleState === "locked");
224 const polledOnBattery = booleanState(onBattery);
225 const observedPower = yield* Ref.modify(powerState, (latestPower) => {
226 const preserveEventLocked =
227 latestPower.lockedEventPending ||
228 latestPower.locked !== currentPower.locked ||
229 latestPower.lockedEventPending !== currentPower.lockedEventPending;
230 const preserveEventOnBattery =
231 latestPower.onBatteryEventPending ||
232 latestPower.onBattery !== currentPower.onBattery ||
233 latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
234 const preserveEventSuspended =
235 latestPower.suspendedEventPending ||
236 latestPower.suspended !== currentPower.suspended ||
237 latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
238 const next: PowerState = {
239 ...latestPower,
240 idle: idleState(systemIdleState),
241 locked: preserveEventLocked ? latestPower.locked : polledLocked,
242 lockedEventPending:
243 latestPower.lockedEventPending &&
244 (systemIdleState === "unknown" || polledLocked !== latestPower.locked),
245 suspended:
246 allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
247 suspendedEventPending: false,
248 onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
249 onBatteryEventPending:
250 latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
251 };
252 return [next, next] as const;
253 });
254 const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
255 const snapshot: DesktopHostTelemetrySnapshot = {
256 version: 1,
257 type: "desktopTelemetry",
258 sequence: nextSequence,
259 sampledAtUnixMs,
260 electronPid: process.pid,
261 power: {
262 source: "electron-main",
263 idle: observedPower.idle,
264 idleSeconds,
265 locked: observedPower.locked,
266 suspended: observedPower.suspended,
267 onBattery: observedPower.onBattery,
268 lowPowerMode: "unknown",
269 thermalState: observedPower.thermalState,
270 stale: false,
271 updatedAt: sampledAt,
272 },
273 speedLimitPercent: observedPower.speedLimitPercent,
274 electronProcesses: metrics.map((metric) => ({
275 pid: metric.pid,
276 creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
277 type: metric.type,
278 ...(metric.name === undefined ? {} : { name: metric.name }),
279 ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
280 cpuPercent: metric.cpu.percentCPUUsage,
281 ...(metric.cpu.cumulativeCPUUsage === undefined
282 ? {}
283 : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
284 idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
285 workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
286 peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
287 })),
288 };
289
290 yield* Ref.set(latest, Option.some(snapshot));
291 yield* PubSub.publish(changes, snapshot);
292 }).pipe(
293 Effect.catchCause((cause) =>
294 Cause.hasInterrupts(cause)
295 ? Effect.failCause(cause)
296 : Effect.logWarning("Failed to sample Electron telemetry", {
297 cause: String(cause),
298 }),
299 ),
300 );
301
302 yield* Effect.gen(function* () {
303 yield* sampleOnce(false);
304 while (true) {
305 const [currentPower, demand, intervals] = yield* Effect.all([
306 Ref.get(powerState),
307 Ref.get(diagnosticsDemandSources).pipe(Effect.map((sources) => sources.size > 0)),
308 Ref.get(hostPowerIntervals),
309 ]);
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 const handleControl: DesktopTelemetryPublisher["Service"]["handleControl"] = (message) =>
369 handleControlForSource("legacy", message);
370
371 const snapshots = Stream.unwrap(
372 Effect.gen(function* () {
373 const subscription = yield* PubSub.subscribe(changes);
374 const initial = yield* Ref.get(latest);
375 return Stream.concat(
376 Option.match(initial, {
377 onNone: () => Stream.empty,
378 onSome: Stream.make,
379 }),
380 Stream.fromSubscription(subscription),
381 );
382 }),
383 );
384 const updateReports = Stream.unwrap(
385 Effect.gen(function* () {
386 const subscription = yield* PubSub.subscribe(updateReportChanges);
387 const initial = yield* Ref.get(latestUpdateReport);
388 return Stream.concat(
389 Option.match(initial, {
390 onNone: () => Stream.empty,
391 onSome: Stream.make,
392 }),
393 Stream.fromSubscription(subscription),
394 );
395 }),
396 );
397 const encoded = Stream.concat(
398 Stream.make({
399 version: 1,
400 type: "desktopTelemetryHello",
401 electronPid: process.pid,
402 } as const),
403 Stream.merge(snapshots, updateReports),
404 ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
405
406 const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
407 report,
408 ) =>
409 Ref.set(latestUpdateReport, Option.some(report)).pipe(
410 Effect.andThen(PubSub.publish(updateReportChanges, report)),
411 Effect.asVoid,
412 );
413
414 return DesktopTelemetryPublisher.of({
415 latest: Ref.get(latest),
416 changes: Stream.fromPubSub(changes),
417 encoded,
418 handleControl,
419 handleControlForSource,
420 removeControlSource,
421 publishUpdateReport,
422 updateRequests: Stream.fromQueue(updateRequestQueue),
423 updateCommits: Stream.fromQueue(updateCommitQueue),
424 updateCancellations: Stream.fromQueue(updateCancellationQueue),
425 });
426});
427
428export const layer = Layer.effect(DesktopTelemetryPublisher, make());