Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { HostPowerSnapshot } from "@t3tools/contracts";
4import {
5 RESOURCE_MONITOR_PROTOCOL_VERSION,
6 ResourceMonitorCommand,
7 type ResourceMonitorHelloEvent,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "@effect/vitest";
10import * as DateTime from "effect/DateTime";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Sink from "effect/Sink";
22import * as Stream from "effect/Stream";
23import { ChildProcessSpawner } from "effect/process";
24
25import * as ServerConfig from "../config.ts";
26import * as NativeTelemetryClient from "./NativeTelemetryClient.ts";
27import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
28import {
29 canCommandNativeTelemetrySidecar,
30 canRequestNativeTelemetryRetry,
31 commitCollectionControlUpdate,
32 retainRecentNativeTelemetryFailures,
33 resolveNativeSampleIntervalMs,
34 synchronizeCollectionControlOnStart,
35} from "./NativeTelemetryClient.ts";
36
37const basePower: HostPowerSnapshot = {
38 source: "electron-main",
39 idle: "false",
40 idleSeconds: 0,
41 locked: "false",
42 suspended: false,
43 onBattery: "false",
44 lowPowerMode: "false",
45 thermalState: "nominal",
46 stale: false,
47 updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
48};
49
50describe("resolveNativeSampleIntervalMs", () => {
51 it("keeps a recovery cadence while suspended and backs off under host constraints", () => {
52 expect(resolveNativeSampleIntervalMs({ ...basePower, suspended: true }, 1)).toBe(15_000);
53 expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 1)).toBe(15_000);
54 expect(resolveNativeSampleIntervalMs({ ...basePower, lowPowerMode: "true" }, 1)).toBe(15_000);
55 expect(resolveNativeSampleIntervalMs({ ...basePower, thermalState: "critical" }, 1)).toBe(
56 15_000,
57 );
58 expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 1)).toBe(5_000);
59 });
60
61 it("stops timed sampling without a live subscriber and serves live diagnostics at 1Hz", () => {
62 const unknown: HostPowerSnapshot = {
63 ...basePower,
64 source: "unknown",
65 stale: true,
66 };
67 expect(resolveNativeSampleIntervalMs(unknown, 0)).toBe(0);
68 expect(resolveNativeSampleIntervalMs(unknown, 1)).toBe(1_000);
69 expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 0)).toBe(0);
70 expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 0)).toBe(0);
71 expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(0);
72 expect(resolveNativeSampleIntervalMs(basePower, 1)).toBe(1_000);
73 });
74});
75
76const decodeCommandLine = Schema.decodeUnknownSync(Schema.fromJsonString(ResourceMonitorCommand));
77
78const hello: ResourceMonitorHelloEvent = {
79 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
80 type: "hello",
81 sidecarVersion: "test",
82 sidecarPid: 4242,
83 platform: "linux",
84 arch: "x64",
85 capabilities: {
86 cumulativeCpuTime: true,
87 currentCpuPercent: true,
88 residentMemory: true,
89 virtualMemory: true,
90 ioBytes: true,
91 processStartTime: true,
92 processTree: true,
93 },
94};
95
96describe("NativeTelemetryClient", () => {
97 it.effect("asks the sidecar for timed samples only while a live subscriber exists", () =>
98 Effect.gen(function* () {
99 const commands = yield* Queue.unbounded<ResourceMonitorCommand>();
100 const spawner = ChildProcessSpawner.make(() =>
101 Effect.succeed(
102 ChildProcessSpawner.makeHandle({
103 pid: ChildProcessSpawner.ProcessId(hello.sidecarPid),
104 exitCode: Effect.never,
105 isRunning: Effect.succeed(true),
106 kill: () => Effect.void,
107 unref: Effect.succeed(Effect.void),
108 stdin: Sink.forEach((chunk: Uint8Array) =>
109 Effect.forEach(new TextDecoder().decode(chunk).split("\n").filter(Boolean), (line) =>
110 Queue.offer(commands, decodeCommandLine(line)),
111 ),
112 ),
113 stdout: Stream.encodeText(Stream.make(`${JSON.stringify(hello)}\n`)).pipe(
114 Stream.concat(Stream.never),
115 ),
116 stderr: Stream.empty,
117 all: Stream.empty,
118 getInputFd: () => Sink.drain,
119 getOutputFd: () => Stream.empty,
120 }),
121 ),
122 );
123 const client = yield* NativeTelemetryClient.make().pipe(
124 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
125 Effect.provideService(ResourceMonitorBinary.ResourceMonitorBinary, {
126 resolve: Effect.succeed("/test/t3-resource-monitor"),
127 }),
128 );
129
130 const configure = yield* Queue.take(commands);
131 expect(configure).toMatchObject({ type: "configure", sampleIntervalMs: 0 });
132 expect(yield* Queue.take(commands)).toMatchObject({ type: "setExternalProcesses" });
133
134 const live = yield* Scope.make();
135 yield* client.snapshots.pipe(Stream.runDrain, Effect.forkIn(live));
136 expect(yield* Queue.take(commands)).toMatchObject({
137 type: "setSampleInterval",
138 sampleIntervalMs: 1_000,
139 });
140 expect(yield* Queue.take(commands)).toMatchObject({ type: "setStreaming", enabled: true });
141
142 yield* Scope.close(live, Exit.void);
143 expect(yield* Queue.take(commands)).toMatchObject({
144 type: "setSampleInterval",
145 sampleIntervalMs: 0,
146 });
147 expect(yield* Queue.take(commands)).toMatchObject({ type: "setStreaming", enabled: false });
148 expect((yield* client.health).sampleIntervalMs).toBe(0);
149 }).pipe(
150 Effect.provide(
151 Layer.mergeAll(
152 ServerConfig.layerTest(process.cwd(), { prefix: "t3-native-telemetry-test-" }),
153 NodeCrypto.layer,
154 ).pipe(Layer.provideMerge(NodeServices.layer)),
155 ),
156 ),
157 );
158});
159
160describe("canRequestNativeTelemetryRetry", () => {
161 it("only accepts retry while the supervisor is waiting without a live sidecar", () => {
162 expect(canRequestNativeTelemetryRetry("degraded", false)).toBe(true);
163 expect(canRequestNativeTelemetryRetry("unavailable", false)).toBe(true);
164 expect(canRequestNativeTelemetryRetry("degraded", true)).toBe(false);
165 expect(canRequestNativeTelemetryRetry("healthy", false)).toBe(false);
166 expect(canRequestNativeTelemetryRetry("starting", false)).toBe(false);
167 });
168});
169
170describe("canCommandNativeTelemetrySidecar", () => {
171 it("keeps on-demand recovery commands available while a live sidecar is degraded", () => {
172 expect(canCommandNativeTelemetrySidecar("healthy", true)).toBe(true);
173 expect(canCommandNativeTelemetrySidecar("degraded", true)).toBe(true);
174 expect(canCommandNativeTelemetrySidecar("unavailable", true)).toBe(false);
175 expect(canCommandNativeTelemetrySidecar("degraded", false)).toBe(false);
176 });
177});
178
179describe("retainRecentNativeTelemetryFailures", () => {
180 it("expires old failures so an isolated crash restarts from the initial backoff", () => {
181 expect(retainRecentNativeTelemetryFailures([0, 30_000], 90_001)).toEqual([]);
182 expect(retainRecentNativeTelemetryFailures([30_000, 60_000], 90_000)).toEqual([30_000, 60_000]);
183 });
184});
185
186describe("commitCollectionControlUpdate", () => {
187 it.effect("retains desired demand and retries unapplied sidecar state", () =>
188 Effect.gen(function* () {
189 const initial = {
190 hostPower: basePower,
191 liveSubscriberCount: 0,
192 sampleIntervalMs: 5_000,
193 };
194 const desired = yield* Ref.make(initial);
195 const applied = yield* Ref.make(initial);
196 const failure = new Error("sidecar write failed");
197 const receivedStates: Array<readonly [number, number]> = [];
198
199 const received = yield* commitCollectionControlUpdate(
200 desired,
201 applied,
202 (current) => ({
203 ...current,
204 liveSubscriberCount: 1,
205 sampleIntervalMs: 1_000,
206 }),
207 (previous, next) => {
208 receivedStates.push([previous.sampleIntervalMs, next.sampleIntervalMs]);
209 return Effect.fail(failure);
210 },
211 ).pipe(Effect.flip);
212
213 expect(received).toBe(failure);
214 expect(yield* Ref.get(desired)).toEqual({
215 ...initial,
216 liveSubscriberCount: 1,
217 sampleIntervalMs: 1_000,
218 });
219 expect(yield* Ref.get(applied)).toEqual(initial);
220
221 yield* commitCollectionControlUpdate(
222 desired,
223 applied,
224 (current) => current,
225 (previous, next) => {
226 receivedStates.push([previous.sampleIntervalMs, next.sampleIntervalMs]);
227 return Effect.void;
228 },
229 );
230 expect(receivedStates).toEqual([
231 [5_000, 1_000],
232 [5_000, 1_000],
233 ]);
234 expect(yield* Ref.get(applied)).toEqual(yield* Ref.get(desired));
235 }),
236 );
237
238 it.effect("serializes startup synchronization with runtime control updates", () =>
239 Effect.gen(function* () {
240 const initial = {
241 hostPower: basePower,
242 liveSubscriberCount: 0,
243 sampleIntervalMs: 5_000,
244 };
245 const desired = yield* Ref.make(initial);
246 const applied = yield* Ref.make(initial);
247 const ready = yield* Ref.make(false);
248 const mutex = yield* Semaphore.make(1);
249 const startupApplying = yield* Deferred.make<void>();
250 const releaseStartup = yield* Deferred.make<void>();
251 const appliedIntervals: Array<number> = [];
252
253 const startupFiber = yield* synchronizeCollectionControlOnStart(
254 mutex,
255 desired,
256 applied,
257 (control) =>
258 Effect.sync(() => {
259 appliedIntervals.push(control.sampleIntervalMs);
260 }).pipe(
261 Effect.andThen(Deferred.succeed(startupApplying, undefined)),
262 Effect.andThen(Deferred.await(releaseStartup)),
263 Effect.asVoid,
264 ),
265 Ref.set(ready, true),
266 ).pipe(Effect.forkChild);
267 yield* Deferred.await(startupApplying);
268
269 const updateFiber = yield* mutex
270 .withPermits(1)(
271 commitCollectionControlUpdate(
272 desired,
273 applied,
274 (current) => ({
275 ...current,
276 liveSubscriberCount: 1,
277 sampleIntervalMs: 1_000,
278 }),
279 (_previous, next) =>
280 Effect.gen(function* () {
281 expect(yield* Ref.get(ready)).toBe(true);
282 appliedIntervals.push(next.sampleIntervalMs);
283 }),
284 ),
285 )
286 .pipe(Effect.forkChild);
287 yield* Effect.yieldNow;
288 expect(yield* Ref.get(desired)).toEqual(initial);
289
290 yield* Deferred.succeed(releaseStartup, undefined);
291 yield* Fiber.join(startupFiber);
292 yield* Fiber.join(updateFiber);
293
294 expect(appliedIntervals).toEqual([5_000, 1_000]);
295 expect(yield* Ref.get(applied)).toEqual(yield* Ref.get(desired));
296 }),
297 );
298});