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

DesktopTelemetryPublisher.test.ts

389 lines15.9 KB

1import { DesktopHostTelemetryMessage } from "@t3tools/contracts";
2import { assert, describe, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Ref from "effect/Ref";
11import * as Schema from "effect/Schema";
12import * as Scope from "effect/Scope";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15​
16import type * as Electron from "electron";
17​
18import * as ElectronApp from "../electron/ElectronApp.ts";
19import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
20import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
21​
22function makeElectronAppLayer(
23 metrics: ReadonlyArray<Electron.ProcessMetric>,
24 onMetricsRead: () => void = () => undefined,
25) {
26 return Layer.succeed(ElectronApp.ElectronApp, {
27 metadata: Effect.die("unexpected metadata read"),
28 name: Effect.succeed("T3 Code"),
29 systemLocale: Effect.succeed("en-US"),
30 whenReady: Effect.void,
31 quit: Effect.void,
32 exit: () => Effect.void,
33 relaunch: () => Effect.void,
34 setPath: () => Effect.void,
35 setName: () => Effect.void,
36 setAboutPanelOptions: () => Effect.void,
37 setAppUserModelId: () => Effect.void,
38 getAppMetrics: Effect.sync(() => {
39 onMetricsRead();
40 return metrics;
41 }),
42 isDefaultProtocolClient: () => Effect.succeed(false),
43 setAsDefaultProtocolClient: () => Effect.succeed(true),
44 setDesktopName: () => Effect.void,
45 setDockIcon: () => Effect.void,
46 appendCommandLineSwitch: () => Effect.void,
47 removeCommandLineSwitch: () => Effect.void,
48 onBeforeQuitForUpdate: () => Effect.void,
49 on: () => Effect.void,
50 } satisfies ElectronApp.ElectronApp["Service"]);
52​
53describe("DesktopTelemetryPublisher", () => {
54 it.effect("stops when its scope closes during an Electron telemetry sample", () =>
55 Effect.gen(function* () {
56 const pollStarted = yield* Deferred.make<void>();
57 const blockPoll = yield* Deferred.make<void>();
58 const powerLayer = Layer.succeed(
59 ElectronPowerMonitor.ElectronPowerMonitor,
60 ElectronPowerMonitor.ElectronPowerMonitor.of({
61 isOnBatteryPower: Effect.succeed(false),
62 getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe(
63 Effect.andThen(Deferred.await(blockPoll)),
64 Effect.as(0),
65 ),
66 getSystemIdleState: () => Effect.succeed("active"),
67 getCurrentThermalState: Effect.succeed("nominal"),
68 onSimpleEvent: () => Effect.void,
69 onThermalStateChange: () => Effect.void,
70 onSpeedLimitChange: () => Effect.void,
71 }),
72 );
73 const layer = DesktopTelemetryPublisher.layer.pipe(
74 Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
75 );
76 const scope = yield* Scope.make();
77​
78 yield* Layer.buildWithScope(layer, scope);
79 yield* Deferred.await(pollStarted);
80​
81 const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach);
82 yield* Effect.yieldNow;
83 yield* Effect.yieldNow;
84​
85 assert.isDefined(closeFiber.pollUnsafe());
86 }),
87 );
88​
89 it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
90 Effect.gen(function* () {
91 const onBattery = yield* Ref.make(false);
92 const systemIdleState = yield* Ref.make<ElectronPowerMonitor.ElectronIdleState>("active");
93 let beforeSystemIdleState: Effect.Effect<void> = Effect.void;
94 let metricsReadCount = 0;
95 const simpleListeners = new Map<string, () => void>();
96 let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
97 null;
98 let speedLimitListener: ((limit: number) => void) | null = null;
99 const metrics = [
100 {
101 pid: 4_242,
102 type: "Browser",
103 creationTime: 1_000.75,
104 name: "electron",
105 cpu: {
106 percentCPUUsage: 12.5,
107 cumulativeCPUUsage: 3.25,
108 idleWakeupsPerSecond: 7,
109 },
110 memory: {
111 workingSetSize: 2_048,
112 peakWorkingSetSize: 4_096,
113 },
114 } as Electron.ProcessMetric,
115 ];
116 const powerLayer = Layer.succeed(
117 ElectronPowerMonitor.ElectronPowerMonitor,
118 ElectronPowerMonitor.ElectronPowerMonitor.of({
119 isOnBatteryPower: Ref.get(onBattery),
120 getSystemIdleTime: Effect.succeed(5),
121 getSystemIdleState: () =>
122 beforeSystemIdleState.pipe(Effect.andThen(Ref.get(systemIdleState))),
123 getCurrentThermalState: Effect.succeed("nominal"),
124 onSimpleEvent: (eventName, listener) =>
125 Effect.sync(() => {
126 simpleListeners.set(eventName, listener);
127 }),
128 onThermalStateChange: (listener) =>
129 Effect.sync(() => {
130 thermalListener = listener;
131 }),
132 onSpeedLimitChange: (listener) =>
133 Effect.sync(() => {
134 speedLimitListener = listener;
135 }),
136 }),
137 );
138 const layer = DesktopTelemetryPublisher.layer.pipe(
139 Layer.provide(
140 Layer.mergeAll(
141 makeElectronAppLayer(metrics, () => {
142 metricsReadCount += 1;
143 }),
144 powerLayer,
145 ),
146 ),
147 );
148​
149 yield* Effect.gen(function* () {
150 const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
151 const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
152 const decoder = new TextDecoder();
153 const decodeMessage = Schema.decodeUnknownEffect(
154 Schema.fromJsonString(DesktopHostTelemetryMessage),
155 );
156 const messages = yield* Effect.forEach(encoded, (bytes) =>
157 decodeMessage(decoder.decode(bytes).trim()),
158 );
159​
160 assert.equal(messages[0]?.type, "desktopTelemetryHello");
161 assert.equal(messages[0]?.electronPid, process.pid);
162 const initialSnapshot = messages[1];
163 if (initialSnapshot?.type !== "desktopTelemetry") {
164 return assert.fail("Expected the second telemetry message to be a snapshot.");
165 }
166 assert.deepEqual(initialSnapshot.electronProcesses, []);
167 assert.equal(initialSnapshot.electronPid, process.pid);
168 assert.equal(metricsReadCount, 0);
169​
170 const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
171 yield* Effect.yieldNow;
172 yield* publisher.handleControl({
173 version: 1,
174 type: "setDiagnosticsDemand",
175 enabled: true,
176 });
177 const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
178 assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
179 assert.equal(demandedSnapshot.electronProcesses[0]?.creationTimeMs, 1_001);
180 assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
181 assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
182 assert.equal(metricsReadCount, 1);
183 yield* publisher.handleControlForSource("secondary-backend", {
184 version: 1,
185 type: "setDiagnosticsDemand",
186 enabled: true,
187 });
188 yield* publisher.handleControl({
189 version: 1,
190 type: "setDiagnosticsDemand",
191 enabled: false,
192 });
193 yield* publisher.handleControlForSource("old-backend", {
194 version: 1,
195 type: "setDiagnosticsDemand",
196 enabled: true,
197 });
198 yield* publisher.handleControlForSource("secondary-backend", {
199 version: 1,
200 type: "setDiagnosticsDemand",
201 enabled: false,
202 });
203 yield* Effect.all(
204 [
205 publisher.removeControlSource("old-backend"),
206 publisher.handleControlForSource("replacement-backend", {
207 version: 1,
208 type: "setDiagnosticsDemand",
209 enabled: true,
210 }),
211 ],
212 { concurrency: "unbounded", discard: true },
213 );
214​
215 const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
216 Effect.forkChild,
217 );
218 yield* Effect.yieldNow;
219 simpleListeners.get("on-battery")?.();
220 const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
221 assert.equal(batterySnapshot.power.onBattery, "true");
222 yield* Ref.set(onBattery, true);
223​
224 const metricsAfterBatteryEvent = metricsReadCount;
225 yield* TestClock.adjust(Duration.millis(4_999));
226 assert.equal(metricsReadCount, metricsAfterBatteryEvent);
227 yield* TestClock.adjust(Duration.millis(1));
228 assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
229 assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "true");
230​
231 yield* Ref.set(onBattery, false);
232 const metricsBeforePolledAc = metricsReadCount;
233 yield* TestClock.adjust(Duration.seconds(5));
234 assert.equal(metricsReadCount, metricsBeforePolledAc + 1);
235 assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "false");
236 yield* TestClock.adjust(Duration.seconds(1));
237 assert.equal(metricsReadCount, metricsBeforePolledAc + 2);
238​
239 const suspendedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
240 Effect.forkChild,
241 );
242 yield* Effect.yieldNow;
243 simpleListeners.get("suspend")?.();
244 const suspendedSnapshot = Option.getOrThrow(yield* Fiber.join(suspendedSnapshotFiber));
245 assert.isTrue(suspendedSnapshot.power.suspended);
246​
247 const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
248 Effect.forkChild,
249 );
250 yield* Effect.yieldNow;
251 thermalListener?.("serious");
252 const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
253 assert.equal(constrainedSnapshot.power.thermalState, "serious");
254 assert.isTrue(constrainedSnapshot.power.suspended);
255​
256 const metricsAfterThermalEvent = metricsReadCount;
257 const recoveredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
258 Effect.forkChild,
259 );
260 yield* TestClock.adjust(Duration.millis(14_999));
261 assert.equal(metricsReadCount, metricsAfterThermalEvent);
262 yield* TestClock.adjust(Duration.millis(1));
263 assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
264 const recoveredSnapshot = Option.getOrThrow(yield* Fiber.join(recoveredSnapshotFiber));
265 assert.isFalse(recoveredSnapshot.power.suspended);
266​
267 const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
268 Effect.forkChild,
269 );
270 yield* Effect.yieldNow;
271 speedLimitListener?.(65);
272 const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
273 assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
274​
275 const encodedSpeedLimit = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
276 const decodedSpeedLimit = yield* decodeMessage(decoder.decode(encodedSpeedLimit[1]).trim());
277 if (decodedSpeedLimit.type !== "desktopTelemetry") {
278 return assert.fail("Expected the encoded telemetry message to be a snapshot.");
279 }
280 assert.equal(Option.getOrNull(decodedSpeedLimit.speedLimitPercent), 65);
281 assert.equal(decodedSpeedLimit.electronProcesses[0]?.pid, 4_242);
282 assert.equal(decodedSpeedLimit.electronProcesses[0]?.creationTimeMs, 1_001);
283​
284 const metricsBeforeSecondaryOnlySample = metricsReadCount;
285 yield* TestClock.adjust(Duration.seconds(15));
286 assert.equal(metricsReadCount, metricsBeforeSecondaryOnlySample + 1);
287 assert.equal(
288 (yield* publisher.latest).pipe(Option.getOrThrow).electronProcesses[0]?.pid,
289 4_242,
290 );
291​
292 const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
293 Effect.forkChild,
294 );
295 yield* Effect.yieldNow;
296 yield* publisher.handleControlForSource("replacement-backend", {
297 version: 1,
298 type: "setDiagnosticsDemand",
299 enabled: false,
300 });
301 const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
302 assert.deepEqual(stoppedSnapshot.electronProcesses, []);
303 const metricsAfterStopping = metricsReadCount;
304 const configuredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
305 Effect.forkChild,
306 );
307 yield* Effect.yieldNow;
308 yield* publisher.handleControl({
309 version: 1,
310 type: "setHostPowerIntervals",
311 activeIntervalMs: 7_000,
312 idleIntervalMs: 11_000,
313 });
314 const configuredSequence = Option.getOrThrow(
315 yield* Fiber.join(configuredSnapshotFiber),
316 ).sequence;
317​
318 yield* TestClock.adjust(Duration.millis(6_999));
319 assert.equal(
320 (yield* publisher.latest).pipe(Option.getOrThrow).sequence,
321 configuredSequence,
322 );
323 assert.equal(metricsReadCount, metricsAfterStopping);
324 yield* TestClock.adjust(Duration.millis(1));
325 assert.equal(
326 (yield* publisher.latest).pipe(Option.getOrThrow).sequence,
327 configuredSequence + 1,
328 );
329 assert.equal(metricsReadCount, metricsAfterStopping);
330​
331 yield* Ref.set(systemIdleState, "locked");
332 yield* TestClock.adjust(Duration.seconds(7));
333 const lockedSequence = (yield* publisher.latest).pipe(Option.getOrThrow).sequence;
334 assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.locked, "true");
335 yield* TestClock.adjust(Duration.millis(10_999));
336 assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).sequence, lockedSequence);
337 yield* TestClock.adjust(Duration.millis(1));
338 assert.equal(
339 (yield* publisher.latest).pipe(Option.getOrThrow).sequence,
340 lockedSequence + 1,
341 );
342​
343 yield* Ref.set(systemIdleState, "active");
344 yield* TestClock.adjust(Duration.seconds(11));
345 const unlockedSnapshot = (yield* publisher.latest).pipe(Option.getOrThrow);
346 assert.equal(unlockedSnapshot.power.locked, "false");
347 assert.equal(unlockedSnapshot.power.idle, "false");
348​
349 yield* TestClock.adjust(Duration.millis(6_999));
350 assert.equal(
351 (yield* publisher.latest).pipe(Option.getOrThrow).sequence,
352 unlockedSnapshot.sequence,
353 );
354 yield* TestClock.adjust(Duration.millis(1));
355 assert.equal(
356 (yield* publisher.latest).pipe(Option.getOrThrow).sequence,
357 unlockedSnapshot.sequence + 1,
358 );
359​
360 const pollStarted = yield* Deferred.make<void>();
361 const releasePoll = yield* Deferred.make<void>();
362 beforeSystemIdleState = Deferred.succeed(pollStarted, undefined).pipe(
363 Effect.andThen(Deferred.await(releasePoll)),
364 );
365 const concurrentEventSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
366 Effect.forkChild,
367 );
368 yield* Effect.yieldNow;
369 yield* publisher.handleControl({
370 version: 1,
371 type: "setDiagnosticsDemand",
372 enabled: true,
373 });
374 yield* Deferred.await(pollStarted);
375 simpleListeners.get("lock-screen")?.();
376 thermalListener?.("critical");
377 yield* Effect.yieldNow;
378 yield* Effect.yieldNow;
379 yield* Deferred.succeed(releasePoll, undefined);
380​
381 const concurrentEventSnapshot = Option.getOrThrow(
382 yield* Fiber.join(concurrentEventSnapshotFiber),
383 );
384 assert.equal(concurrentEventSnapshot.power.locked, "true");
385 assert.equal(concurrentEventSnapshot.power.thermalState, "critical");
386 }).pipe(Effect.provide(layer));
387 }),
388 );
389});