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

NativeTelemetryClient.test.ts

242 lines8.5 KB

1import type { HostPowerSnapshot } from "@t3tools/contracts";
2import { describe, expect, it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as DateTime from "effect/DateTime";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Ref from "effect/Ref";
9import * as Semaphore from "effect/Semaphore";
10​
11import {
12 NativeTelemetryRequestTimedOut,
13 NativeTelemetryStreamClosed,
14 canCommandNativeTelemetrySidecar,
15 canRequestNativeTelemetryRetry,
16 commitCollectionControlUpdate,
17 nativeTelemetrySupervisorFailureMessage,
18 retainRecentNativeTelemetryFailures,
19 resolveNativeSampleIntervalMs,
20 synchronizeCollectionControlOnStart,
21} from "./NativeTelemetryClient.ts";
22​
23const basePower: HostPowerSnapshot = {
24 source: "electron-main",
25 idle: "false",
26 idleSeconds: 0,
27 locked: "false",
28 suspended: false,
29 onBattery: "false",
30 lowPowerMode: "false",
31 thermalState: "nominal",
32 stale: false,
33 updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
34};
35​
36describe("resolveNativeSampleIntervalMs", () => {
37 it("keeps a recovery cadence while suspended and backs off under host constraints", () => {
38 expect(resolveNativeSampleIntervalMs({ ...basePower, suspended: true }, 1)).toBe(15_000);
39 expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 1)).toBe(15_000);
40 expect(resolveNativeSampleIntervalMs({ ...basePower, lowPowerMode: "true" }, 1)).toBe(15_000);
41 expect(resolveNativeSampleIntervalMs({ ...basePower, thermalState: "critical" }, 1)).toBe(
42 15_000,
43 );
44 expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 1)).toBe(5_000);
45 });
46​
47 it("slows background telemetry and serves live diagnostics at 1Hz", () => {
48 const unknown: HostPowerSnapshot = {
49 ...basePower,
50 source: "unknown",
51 stale: true,
52 };
53 expect(resolveNativeSampleIntervalMs(unknown, 0)).toBe(5_000);
54 expect(resolveNativeSampleIntervalMs(unknown, 1)).toBe(1_000);
55 expect(
56 resolveNativeSampleIntervalMs(
57 { ...basePower, stale: true, locked: "true", suspended: true },
58 0,
59 ),
60 ).toBe(5_000);
61 expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(5_000);
62 expect(resolveNativeSampleIntervalMs(basePower, 1)).toBe(1_000);
63 });
64});
65​
66describe("canRequestNativeTelemetryRetry", () => {
67 it("only accepts retry while the supervisor is waiting without a live sidecar", () => {
68 expect(canRequestNativeTelemetryRetry("degraded", false)).toBe(true);
69 expect(canRequestNativeTelemetryRetry("unavailable", false)).toBe(true);
70 expect(canRequestNativeTelemetryRetry("degraded", true)).toBe(false);
71 expect(canRequestNativeTelemetryRetry("healthy", false)).toBe(false);
72 expect(canRequestNativeTelemetryRetry("starting", false)).toBe(false);
73 });
74});
75​
76describe("canCommandNativeTelemetrySidecar", () => {
77 it("keeps on-demand recovery commands available while a live sidecar is degraded", () => {
78 expect(canCommandNativeTelemetrySidecar("healthy", true)).toBe(true);
79 expect(canCommandNativeTelemetrySidecar("degraded", true)).toBe(true);
80 expect(canCommandNativeTelemetrySidecar("unavailable", true)).toBe(false);
81 expect(canCommandNativeTelemetrySidecar("degraded", false)).toBe(false);
82 });
83});
84​
85describe("NativeTelemetryRequestTimedOut", () => {
86 it("models history and sample request deadlines without a fabricated cause", () => {
87 const historyTimeout = new NativeTelemetryRequestTimedOut({
88 operation: "readHistory",
89 timeoutMs: 15_000,
90 });
91 const sampleTimeout = new NativeTelemetryRequestTimedOut({
92 operation: "sampleNow",
93 timeoutMs: 5_000,
94 });
95​
96 expect(historyTimeout.message).toBe(
97 "Resource monitor 'readHistory' request timed out after 15000ms.",
98 );
99 expect(sampleTimeout.message).toBe(
100 "Resource monitor 'sampleNow' request timed out after 5000ms.",
101 );
102 expect("cause" in historyTimeout).toBe(false);
103 expect("cause" in sampleTimeout).toBe(false);
104 });
105});
106​
107describe("native telemetry supervisor failures", () => {
108 it("distinguishes a closed event stream from a process exit", () => {
109 expect(new NativeTelemetryStreamClosed().message).toBe(
110 "Resource monitor event stream closed unexpectedly.",
111 );
112 });
113​
114 it("keeps defect details out of the caller-visible health message", () => {
115 const secret = "credential=do-not-expose";
116 const message = nativeTelemetrySupervisorFailureMessage(Cause.die(new Error(secret)));
117​
118 expect(message).toBe("Resource monitor supervisor stopped unexpectedly.");
119 expect(message).not.toContain(secret);
120 });
121});
122​
123describe("retainRecentNativeTelemetryFailures", () => {
124 it("expires old failures so an isolated crash restarts from the initial backoff", () => {
125 expect(retainRecentNativeTelemetryFailures([0, 30_000], 90_001)).toEqual([]);
126 expect(retainRecentNativeTelemetryFailures([30_000, 60_000], 90_000)).toEqual([30_000, 60_000]);
127 });
128});
129​
130describe("commitCollectionControlUpdate", () => {
131 it.effect("retains desired demand and retries unapplied sidecar state", () =>
132 Effect.gen(function* () {
133 const initial = {
134 hostPower: basePower,
135 liveSubscriberCount: 0,
136 sampleIntervalMs: 5_000,
137 };
138 const desired = yield* Ref.make(initial);
139 const applied = yield* Ref.make(initial);
140 const failure = new Error("sidecar write failed");
141 const receivedStates: Array<readonly [number, number]> = [];
142​
143 const received = yield* commitCollectionControlUpdate(
144 desired,
145 applied,
146 (current) => ({
147 ...current,
148 liveSubscriberCount: 1,
149 sampleIntervalMs: 1_000,
150 }),
151 (previous, next) => {
152 receivedStates.push([previous.sampleIntervalMs, next.sampleIntervalMs]);
153 return Effect.fail(failure);
154 },
155 ).pipe(Effect.flip);
156​
157 expect(received).toBe(failure);
158 expect(yield* Ref.get(desired)).toEqual({
159 ...initial,
160 liveSubscriberCount: 1,
161 sampleIntervalMs: 1_000,
162 });
163 expect(yield* Ref.get(applied)).toEqual(initial);
164​
165 yield* commitCollectionControlUpdate(
166 desired,
167 applied,
168 (current) => current,
169 (previous, next) => {
170 receivedStates.push([previous.sampleIntervalMs, next.sampleIntervalMs]);
171 return Effect.void;
172 },
173 );
174 expect(receivedStates).toEqual([
175 [5_000, 1_000],
176 [5_000, 1_000],
177 ]);
178 expect(yield* Ref.get(applied)).toEqual(yield* Ref.get(desired));
179 }),
180 );
181​
182 it.effect("serializes startup synchronization with runtime control updates", () =>
183 Effect.gen(function* () {
184 const initial = {
185 hostPower: basePower,
186 liveSubscriberCount: 0,
187 sampleIntervalMs: 5_000,
188 };
189 const desired = yield* Ref.make(initial);
190 const applied = yield* Ref.make(initial);
191 const ready = yield* Ref.make(false);
192 const mutex = yield* Semaphore.make(1);
193 const startupApplying = yield* Deferred.make<void>();
194 const releaseStartup = yield* Deferred.make<void>();
195 const appliedIntervals: Array<number> = [];
196​
197 const startupFiber = yield* synchronizeCollectionControlOnStart(
198 mutex,
199 desired,
200 applied,
201 (control) =>
202 Effect.sync(() => {
203 appliedIntervals.push(control.sampleIntervalMs);
204 }).pipe(
205 Effect.andThen(Deferred.succeed(startupApplying, undefined)),
206 Effect.andThen(Deferred.await(releaseStartup)),
207 Effect.asVoid,
208 ),
209 Ref.set(ready, true),
210 ).pipe(Effect.forkChild);
211 yield* Deferred.await(startupApplying);
212​
213 const updateFiber = yield* mutex
214 .withPermits(1)(
215 commitCollectionControlUpdate(
216 desired,
217 applied,
218 (current) => ({
219 ...current,
220 liveSubscriberCount: 1,
221 sampleIntervalMs: 1_000,
222 }),
223 (_previous, next) =>
224 Effect.gen(function* () {
225 expect(yield* Ref.get(ready)).toBe(true);
226 appliedIntervals.push(next.sampleIntervalMs);
227 }),
228 ),
229 )
230 .pipe(Effect.forkChild);
231 yield* Effect.yieldNow;
232 expect(yield* Ref.get(desired)).toEqual(initial);
233​
234 yield* Deferred.succeed(releaseStartup, undefined);
235 yield* Fiber.join(startupFiber);
236 yield* Fiber.join(updateFiber);
237​
238 expect(appliedIntervals).toEqual([5_000, 1_000]);
239 expect(yield* Ref.get(applied)).toEqual(yield* Ref.get(desired));
240 }),
241 );
242});