Open History to see the last commit
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("keeps unknown background telemetry cheap but 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(1_000);
62 });
63});
64
65describe("canRequestNativeTelemetryRetry", () => {
66 it("only accepts retry while the supervisor is waiting without a live sidecar", () => {
67 expect(canRequestNativeTelemetryRetry("degraded", false)).toBe(true);
68 expect(canRequestNativeTelemetryRetry("unavailable", false)).toBe(true);
69 expect(canRequestNativeTelemetryRetry("degraded", true)).toBe(false);
70 expect(canRequestNativeTelemetryRetry("healthy", false)).toBe(false);
71 expect(canRequestNativeTelemetryRetry("starting", false)).toBe(false);
72 });
73});
74
75describe("canCommandNativeTelemetrySidecar", () => {
76 it("keeps on-demand recovery commands available while a live sidecar is degraded", () => {
77 expect(canCommandNativeTelemetrySidecar("healthy", true)).toBe(true);
78 expect(canCommandNativeTelemetrySidecar("degraded", true)).toBe(true);
79 expect(canCommandNativeTelemetrySidecar("unavailable", true)).toBe(false);
80 expect(canCommandNativeTelemetrySidecar("degraded", false)).toBe(false);
81 });
82});
83
84describe("NativeTelemetryRequestTimedOut", () => {
85 it("models history and sample request deadlines without a fabricated cause", () => {
86 const historyTimeout = new NativeTelemetryRequestTimedOut({
87 operation: "readHistory",
88 timeoutMs: 15_000,
89 });
90 const sampleTimeout = new NativeTelemetryRequestTimedOut({
91 operation: "sampleNow",
92 timeoutMs: 5_000,
93 });
94
95 expect(historyTimeout.message).toBe(
96 "Resource monitor 'readHistory' request timed out after 15000ms.",
97 );
98 expect(sampleTimeout.message).toBe(
99 "Resource monitor 'sampleNow' request timed out after 5000ms.",
100 );
101 expect("cause" in historyTimeout).toBe(false);
102 expect("cause" in sampleTimeout).toBe(false);
103 });
104});
105
106describe("native telemetry supervisor failures", () => {
107 it("distinguishes a closed event stream from a process exit", () => {
108 expect(new NativeTelemetryStreamClosed().message).toBe(
109 "Resource monitor event stream closed unexpectedly.",
110 );
111 });
112
113 it("keeps defect details out of the caller-visible health message", () => {
114 const secret = "credential=do-not-expose";
115 const message = nativeTelemetrySupervisorFailureMessage(Cause.die(new Error(secret)));
116
117 expect(message).toBe("Resource monitor supervisor stopped unexpectedly.");
118 expect(message).not.toContain(secret);
119 });
120});
121
122describe("retainRecentNativeTelemetryFailures", () => {
123 it("expires old failures so an isolated crash restarts from the initial backoff", () => {
124 expect(retainRecentNativeTelemetryFailures([0, 30_000], 90_001)).toEqual([]);
125 expect(retainRecentNativeTelemetryFailures([30_000, 60_000], 90_000)).toEqual([30_000, 60_000]);
126 });
127});
128
129describe("commitCollectionControlUpdate", () => {
130 it.effect("retains desired demand and retries unapplied sidecar state", () =>
131 Effect.gen(function* () {
132 const initial = {
133 hostPower: basePower,
134 liveSubscriberCount: 0,
135 sampleIntervalMs: 5_000,
136 };
137 const desired = yield* Ref.make(initial);
138 const applied = yield* Ref.make(initial);
139 const failure = new Error("sidecar write failed");
140 const receivedStates: Array<readonly [number, number]> = [];
141
142 const received = yield* commitCollectionControlUpdate(
143 desired,
144 applied,
145 (current) => ({
146 ...current,
147 liveSubscriberCount: 1,
148 sampleIntervalMs: 1_000,
149 }),
150 (previous, next) => {
151 receivedStates.push([previous.sampleIntervalMs, next.sampleIntervalMs]);
152 return Effect.fail(failure);
153 },
154 ).pipe(Effect.flip);
155
156 expect(received).toBe(failure);
157 expect(yield* Ref.get(desired)).toEqual({
158 ...initial,
159 liveSubscriberCount: 1,
160 sampleIntervalMs: 1_000,
161 });
162 expect(yield* Ref.get(applied)).toEqual(initial);
163
164 yield* commitCollectionControlUpdate(
165 desired,
166 applied,
167 (current) => current,
168 (previous, next) => {
169 receivedStates.push([previous.sampleIntervalMs, next.sampleIntervalMs]);
170 return Effect.void;
171 },
172 );
173 expect(receivedStates).toEqual([
174 [5_000, 1_000],
175 [5_000, 1_000],
176 ]);
177 expect(yield* Ref.get(applied)).toEqual(yield* Ref.get(desired));
178 }),
179 );
180
181 it.effect("serializes startup synchronization with runtime control updates", () =>
182 Effect.gen(function* () {
183 const initial = {
184 hostPower: basePower,
185 liveSubscriberCount: 0,
186 sampleIntervalMs: 5_000,
187 };
188 const desired = yield* Ref.make(initial);
189 const applied = yield* Ref.make(initial);
190 const ready = yield* Ref.make(false);
191 const mutex = yield* Semaphore.make(1);
192 const startupApplying = yield* Deferred.make<void>();
193 const releaseStartup = yield* Deferred.make<void>();
194 const appliedIntervals: Array<number> = [];
195
196 const startupFiber = yield* synchronizeCollectionControlOnStart(
197 mutex,
198 desired,
199 applied,
200 (control) =>
201 Effect.sync(() => {
202 appliedIntervals.push(control.sampleIntervalMs);
203 }).pipe(
204 Effect.andThen(Deferred.succeed(startupApplying, undefined)),
205 Effect.andThen(Deferred.await(releaseStartup)),
206 Effect.asVoid,
207 ),
208 Ref.set(ready, true),
209 ).pipe(Effect.forkChild);
210 yield* Deferred.await(startupApplying);
211
212 const updateFiber = yield* mutex
213 .withPermits(1)(
214 commitCollectionControlUpdate(
215 desired,
216 applied,
217 (current) => ({
218 ...current,
219 liveSubscriberCount: 1,
220 sampleIntervalMs: 1_000,
221 }),
222 (_previous, next) =>
223 Effect.gen(function* () {
224 expect(yield* Ref.get(ready)).toBe(true);
225 appliedIntervals.push(next.sampleIntervalMs);
226 }),
227 ),
228 )
229 .pipe(Effect.forkChild);
230 yield* Effect.yieldNow;
231 expect(yield* Ref.get(desired)).toEqual(initial);
232
233 yield* Deferred.succeed(releaseStartup, undefined);
234 yield* Fiber.join(startupFiber);
235 yield* Fiber.join(updateFiber);
236
237 expect(appliedIntervals).toEqual([5_000, 1_000]);
238 expect(yield* Ref.get(applied)).toEqual(yield* Ref.get(desired));
239 }),
240 );
241});