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 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";
84}
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 }
96}
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 }
123}
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;
145}
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.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
368 const snapshots = Stream.unwrap(
369 Effect.gen(function* () {
370 const subscription = yield* PubSub.subscribe(changes);
371 const initial = yield* Ref.get(latest);
372 return Stream.concat(
373 Option.match(initial, {
374 onNone: () => Stream.empty,
375 onSome: Stream.make,
376 }),
377 Stream.fromSubscription(subscription),
378 );
379 }),
380 );
381 const updateReports = Stream.unwrap(
382 Effect.gen(function* () {
383 const subscription = yield* PubSub.subscribe(updateReportChanges);
384 const initial = yield* Ref.get(latestUpdateReport);
385 return Stream.concat(
386 Option.match(initial, {
387 onNone: () => Stream.empty,
388 onSome: Stream.make,
389 }),
390 Stream.fromSubscription(subscription),
391 );
392 }),
393 );
394 const encoded = Stream.concat(
395 Stream.make({
396 version: 1,
397 type: "desktopTelemetryHello",
398 electronPid: process.pid,
399 } as const),
400 Stream.merge(snapshots, updateReports),
401 ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
402
403 const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
404 report,
405 ) =>
406 Ref.set(latestUpdateReport, Option.some(report)).pipe(
407 Effect.andThen(PubSub.publish(updateReportChanges, report)),
408 Effect.asVoid,
409 );
410
411 return DesktopTelemetryPublisher.of({
412 latest: Ref.get(latest),
413 changes: Stream.fromPubSub(changes),
414 encoded,
415 handleControlForSource,
416 removeControlSource,
417 publishUpdateReport,
418 updateRequests: Stream.fromQueue(updateRequestQueue),
419 updateCommits: Stream.fromQueue(updateCommitQueue),
420 updateCancellations: Stream.fromQueue(updateCancellationQueue),
421 });
422});
423
424export const layer = Layer.effect(DesktopTelemetryPublisher, make());