Open History to see the last commit
1import type {
2 HostPowerSnapshot,
3 ResourceMonitorCapabilities,
4 ResourceMonitorCommand,
5 ResourceMonitorEvent,
6 ResourceMonitorExternalProcess,
7 ResourceMonitorHelloEvent,
8 ResourceMonitorSnapshotEvent,
9 ResourceTelemetrySourceStatus,
10} from "@t3tools/contracts";
11import {
12 RESOURCE_MONITOR_PROTOCOL_VERSION,
13 ResourceMonitorCommand as ResourceMonitorCommandSchema,
14 ResourceMonitorEvent as ResourceMonitorEventSchema,
15} from "@t3tools/contracts";
16import * as Cause from "effect/Cause";
17import * as Context from "effect/Context";
18import * as Crypto from "effect/Crypto";
19import * as DateTime from "effect/DateTime";
20import * as Deferred from "effect/Deferred";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Fiber from "effect/Fiber";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as PubSub from "effect/PubSub";
27import * as Queue from "effect/Queue";
28import * as Ref from "effect/Ref";
29import * as Result from "effect/Result";
30import * as Schema from "effect/Schema";
31import * as Semaphore from "effect/Semaphore";
32import * as Scope from "effect/Scope";
33import * as Stream from "effect/Stream";
34import * as Ndjson from "effect/unstable/encoding/Ndjson";
35import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
36
37import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts";
38import { ServerConfig } from "../config.ts";
39import { subscribeBeforeSnapshotWithoutMutex } from "../utils/subscribeBeforeSnapshot.ts";
40
41const SAMPLE_INTERVAL_MS = 1_000;
42const UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS = 5_000;
43const BATTERY_SAMPLE_INTERVAL_MS = 5_000;
44const CONSTRAINED_SAMPLE_INTERVAL_MS = 15_000;
45const HANDSHAKE_TIMEOUT = Duration.seconds(5);
46const SAMPLE_REQUEST_TIMEOUT = Duration.seconds(5);
47const HISTORY_REQUEST_TIMEOUT = Duration.seconds(15);
48const INITIAL_RESTART_DELAY = Duration.millis(500);
49const MAX_RESTART_DELAY = Duration.seconds(10);
50const FAILURE_WINDOW_MS = 60_000;
51const MAX_FAILURES_PER_WINDOW = 5;
52
53export class NativeTelemetrySpawnFailed extends Schema.TaggedErrorClass<NativeTelemetrySpawnFailed>()(
54 "NativeTelemetrySpawnFailed",
55 {
56 path: Schema.String,
57 cause: Schema.Defect(),
58 },
59) {
60 override get message(): string {
61 return `Failed to start resource monitor '${this.path}'.`;
62 }
63}
64
65export class NativeTelemetryHandshakeTimedOut extends Schema.TaggedErrorClass<NativeTelemetryHandshakeTimedOut>()(
66 "NativeTelemetryHandshakeTimedOut",
67 {
68 timeoutMs: Schema.Number,
69 },
70) {
71 override get message(): string {
72 return `Resource monitor handshake timed out after ${this.timeoutMs}ms.`;
73 }
74}
75
76class NativeTelemetryRequestTimedOut extends Schema.TaggedErrorClass<NativeTelemetryRequestTimedOut>()(
77 "NativeTelemetryRequestTimedOut",
78 {
79 operation: Schema.Literals(["readHistory", "sampleNow"]),
80 timeoutMs: Schema.Number,
81 },
82) {
83 override get message(): string {
84 return `Resource monitor '${this.operation}' request timed out after ${this.timeoutMs}ms.`;
85 }
86}
87
88export class NativeTelemetryProtocolMismatch extends Schema.TaggedErrorClass<NativeTelemetryProtocolMismatch>()(
89 "NativeTelemetryProtocolMismatch",
90 {
91 expectedVersion: Schema.Number,
92 receivedVersion: Schema.Number,
93 },
94) {
95 override get message(): string {
96 return `Resource monitor protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;
97 }
98}
99
100export class NativeTelemetryDecodeFailed extends Schema.TaggedErrorClass<NativeTelemetryDecodeFailed>()(
101 "NativeTelemetryDecodeFailed",
102 {
103 cause: Schema.Defect(),
104 },
105) {
106 override get message(): string {
107 return "Failed to decode resource monitor output.";
108 }
109}
110
111export class NativeTelemetryCommandFailed extends Schema.TaggedErrorClass<NativeTelemetryCommandFailed>()(
112 "NativeTelemetryCommandFailed",
113 {
114 operation: Schema.String,
115 cause: Schema.Defect(),
116 },
117) {
118 override get message(): string {
119 return `Resource monitor command '${this.operation}' failed.`;
120 }
121}
122
123export class NativeTelemetryExited extends Schema.TaggedErrorClass<NativeTelemetryExited>()(
124 "NativeTelemetryExited",
125 {
126 exitCode: Schema.Number,
127 },
128) {
129 override get message(): string {
130 return `Resource monitor exited with code ${this.exitCode}.`;
131 }
132}
133
134class NativeTelemetryStreamClosed extends Schema.TaggedErrorClass<NativeTelemetryStreamClosed>()(
135 "NativeTelemetryStreamClosed",
136 {},
137) {
138 override get message(): string {
139 return "Resource monitor event stream closed unexpectedly.";
140 }
141}
142
143export class NativeTelemetryUnavailable extends Schema.TaggedErrorClass<NativeTelemetryUnavailable>()(
144 "NativeTelemetryUnavailable",
145 {
146 reason: Schema.String,
147 },
148) {
149 override get message(): string {
150 return `Resource monitor is unavailable: ${this.reason}`;
151 }
152}
153
154export type NativeTelemetryClientError =
155 | ResourceMonitorBinary.ResourceMonitorBinaryError
156 | NativeTelemetrySpawnFailed
157 | NativeTelemetryHandshakeTimedOut
158 | NativeTelemetryRequestTimedOut
159 | NativeTelemetryProtocolMismatch
160 | NativeTelemetryDecodeFailed
161 | NativeTelemetryCommandFailed
162 | NativeTelemetryExited
163 | NativeTelemetryStreamClosed
164 | NativeTelemetryUnavailable;
165
166export interface NativeTelemetryClientHealth {
167 readonly status: ResourceTelemetrySourceStatus;
168 readonly hello: Option.Option<ResourceMonitorHelloEvent>;
169 readonly lastSampleAt: Option.Option<DateTime.Utc>;
170 readonly lastError: Option.Option<string>;
171 readonly restartCount: number;
172 readonly sampleIntervalMs: number;
173}
174
175export interface NativeTelemetrySnapshot {
176 readonly generation: number;
177 readonly snapshot: ResourceMonitorSnapshotEvent;
178}
179
180export class NativeTelemetryClient extends Context.Service<
181 NativeTelemetryClient,
182 {
183 readonly capabilities: Effect.Effect<ResourceMonitorCapabilities, NativeTelemetryClientError>;
184 readonly snapshots: Stream.Stream<NativeTelemetrySnapshot, NativeTelemetryClientError>;
185 readonly readHistory: (
186 windowMs: number,
187 ) => Effect.Effect<ReadonlyArray<ResourceMonitorSnapshotEvent>, NativeTelemetryClientError>;
188 readonly setExternalProcesses: (
189 processes: ReadonlyArray<ResourceMonitorExternalProcess>,
190 ) => Effect.Effect<void, NativeTelemetryClientError>;
191 readonly setHostPowerState: (
192 snapshot: HostPowerSnapshot,
193 ) => Effect.Effect<void, NativeTelemetryClientError>;
194 readonly sampleNow: Effect.Effect<NativeTelemetrySnapshot, NativeTelemetryClientError>;
195 readonly retry: Effect.Effect<boolean>;
196 readonly health: Effect.Effect<NativeTelemetryClientHealth>;
197 readonly subscribeHealth: Effect.Effect<
198 {
199 readonly latest: NativeTelemetryClientHealth;
200 readonly changes: Stream.Stream<NativeTelemetryClientHealth>;
201 },
202 never,
203 Scope.Scope
204 >;
205 }
206>()("t3/resourceTelemetry/NativeTelemetryClient") {}
207
208interface ClientState {
209 readonly status: ResourceTelemetrySourceStatus;
210 readonly handle: Option.Option<ChildProcessSpawner.ChildProcessHandle>;
211 readonly hello: Option.Option<ResourceMonitorHelloEvent>;
212 readonly lastSampleAt: Option.Option<DateTime.Utc>;
213 readonly lastError: Option.Option<string>;
214 readonly restartCount: number;
215}
216
217export interface CollectionControl {
218 readonly hostPower: HostPowerSnapshot;
219 readonly liveSubscriberCount: number;
220 readonly sampleIntervalMs: number;
221}
222
223interface PendingHistoryRequest {
224 readonly deferred: Deferred.Deferred<
225 ReadonlyArray<ResourceMonitorSnapshotEvent>,
226 NativeTelemetryClientError
227 >;
228 readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;
229}
230
231const initialState: ClientState = {
232 status: "starting",
233 handle: Option.none(),
234 hello: Option.none(),
235 lastSampleAt: Option.none(),
236 lastError: Option.none(),
237 restartCount: 0,
238};
239
240function toHealth(state: ClientState, sampleIntervalMs: number): NativeTelemetryClientHealth {
241 return {
242 status: state.status,
243 hello: state.hello,
244 lastSampleAt: state.lastSampleAt,
245 lastError: state.lastError,
246 restartCount: state.restartCount,
247 sampleIntervalMs,
248 };
249}
250
251function isThermallyConstrained(snapshot: HostPowerSnapshot): boolean {
252 return snapshot.thermalState === "serious" || snapshot.thermalState === "critical";
253}
254
255export function resolveNativeSampleIntervalMs(
256 snapshot: HostPowerSnapshot,
257 liveSubscriberCount: number,
258): number {
259 if (snapshot.stale || snapshot.source === "unknown") {
260 return liveSubscriberCount > 0 ? SAMPLE_INTERVAL_MS : UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS;
261 }
262 if (
263 snapshot.suspended ||
264 snapshot.locked === "true" ||
265 snapshot.lowPowerMode === "true" ||
266 isThermallyConstrained(snapshot)
267 ) {
268 return CONSTRAINED_SAMPLE_INTERVAL_MS;
269 }
270 if (snapshot.onBattery === "true") return BATTERY_SAMPLE_INTERVAL_MS;
271 return liveSubscriberCount > 0 ? SAMPLE_INTERVAL_MS : UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS;
272}
273
274export function commitCollectionControlUpdate<E, R>(
275 desiredState: Ref.Ref<CollectionControl>,
276 appliedState: Ref.Ref<CollectionControl>,
277 update: (current: CollectionControl) => CollectionControl,
278 apply: (previous: CollectionControl, next: CollectionControl) => Effect.Effect<void, E, R>,
279): Effect.Effect<readonly [CollectionControl, CollectionControl], E, R> {
280 return Effect.gen(function* () {
281 const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => {
282 const next = update(previous);
283 return [[previous, next] as const, next];
284 });
285 const previousApplied = yield* Ref.get(appliedState);
286 yield* apply(previousApplied, next);
287 yield* Ref.set(appliedState, next);
288 return [previousDesired, next] as const;
289 });
290}
291
292export function synchronizeCollectionControlOnStart<E1, R1, E2, R2>(
293 mutex: Semaphore.Semaphore,
294 desiredState: Ref.Ref<CollectionControl>,
295 appliedState: Ref.Ref<CollectionControl>,
296 apply: (control: CollectionControl) => Effect.Effect<void, E1, R1>,
297 markReady: Effect.Effect<void, E2, R2>,
298) {
299 return mutex.withPermits(1)(
300 Effect.gen(function* () {
301 const control = yield* Ref.get(desiredState);
302 yield* apply(control);
303 yield* Ref.set(appliedState, control);
304 yield* markReady;
305 return control;
306 }),
307 );
308}
309
310const decodeMonitorEvent: (
311 value: unknown,
312) => Effect.Effect<ResourceMonitorEvent, Schema.SchemaError> = Schema.decodeUnknownEffect(
313 ResourceMonitorEventSchema,
314);
315const encodeMonitorCommand = Schema.encodeEffect(
316 Schema.fromJsonString(ResourceMonitorCommandSchema),
317);
318const isProtocolMismatch = Schema.is(NativeTelemetryProtocolMismatch);
319const isDecodeFailed = Schema.is(NativeTelemetryDecodeFailed);
320const isCommandFailed = Schema.is(NativeTelemetryCommandFailed);
321
322function eventVersion(value: unknown): number | undefined {
323 if (typeof value !== "object" || value === null) return undefined;
324 const version = Reflect.get(value, "version");
325 return typeof version === "number" ? version : undefined;
326}
327
328function restartDelay(attempt: number): Duration.Duration {
329 return Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);
330}
331
332export function retainRecentNativeTelemetryFailures(
333 failures: ReadonlyArray<number>,
334 now: number,
335): ReadonlyArray<number> {
336 return failures.filter((failedAt) => now - failedAt <= FAILURE_WINDOW_MS);
337}
338
339function errorMessage(error: NativeTelemetryClientError): string {
340 return error.message;
341}
342
343export function canRequestNativeTelemetryRetry(
344 status: ResourceTelemetrySourceStatus,
345 hasHandle: boolean,
346): boolean {
347 return status !== "healthy" && status !== "starting" && !hasHandle;
348}
349
350export function canCommandNativeTelemetrySidecar(
351 status: ResourceTelemetrySourceStatus,
352 hasHandle: boolean,
353): boolean {
354 return hasHandle && (status === "healthy" || status === "degraded");
355}
356
357export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(function* () {
358 const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary;
359 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
360 const crypto = yield* Crypto.Crypto;
361 const config = yield* ServerConfig;
362 const initializedAt = yield* DateTime.now;
363 const state = yield* Ref.make(initialState);
364 const collectionControl = yield* Ref.make<CollectionControl>({
365 hostPower: {
366 source: "unknown",
367 idle: "unknown",
368 idleSeconds: null,
369 locked: "unknown",
370 suspended: false,
371 onBattery: "unknown",
372 lowPowerMode: "unknown",
373 thermalState: "unknown",
374 stale: true,
375 updatedAt: initializedAt,
376 },
377 liveSubscriberCount: 0,
378 sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
379 });
380 const appliedCollectionControl = yield* Ref.make(yield* Ref.get(collectionControl));
381 const externalProcesses = yield* Ref.make<ReadonlyArray<ResourceMonitorExternalProcess>>([]);
382 const pendingSamples = yield* Ref.make(
383 new Map<string, Deferred.Deferred<NativeTelemetrySnapshot, NativeTelemetryClientError>>(),
384 );
385 const pendingHistories = yield* Ref.make(new Map<string, PendingHistoryRequest>());
386 const snapshots = yield* PubSub.sliding<NativeTelemetrySnapshot>(8);
387 const healthChanges = yield* PubSub.sliding<NativeTelemetryClientHealth>(4);
388 const retryQueue = yield* Queue.sliding<void>(1);
389 const commandMutex = yield* Semaphore.make(1);
390 const controlMutex = yield* Semaphore.make(1);
391 const currentHealth = Effect.all([Ref.get(state), Ref.get(collectionControl)]).pipe(
392 Effect.map(([current, control]) => toHealth(current, control.sampleIntervalMs)),
393 );
394 const publishHealth = currentHealth.pipe(
395 Effect.flatMap((health) => PubSub.publish(healthChanges, health)),
396 Effect.asVoid,
397 );
398
399 const failPending = (error: NativeTelemetryClientError) =>
400 Effect.gen(function* () {
401 const samples = yield* Ref.getAndSet(pendingSamples, new Map());
402 const histories = yield* Ref.getAndSet(pendingHistories, new Map());
403 yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {
404 discard: true,
405 });
406 yield* Effect.forEach(
407 histories.values(),
408 (request) => Deferred.fail(request.deferred, error),
409 { discard: true },
410 );
411 });
412
413 const writeCommand = (
414 handle: ChildProcessSpawner.ChildProcessHandle,
415 command: ResourceMonitorCommand,
416 ): Effect.Effect<void, NativeTelemetryClientError> =>
417 commandMutex.withPermits(1)(
418 encodeMonitorCommand(command).pipe(
419 Effect.map((encoded) => `${encoded}\n`),
420 Effect.mapError(
421 (cause) =>
422 new NativeTelemetryCommandFailed({
423 operation: command.type,
424 cause,
425 }),
426 ),
427 Effect.flatMap((encoded) =>
428 Stream.run(Stream.encodeText(Stream.make(encoded)), handle.stdin),
429 ),
430 Effect.mapError(
431 (cause) =>
432 new NativeTelemetryCommandFailed({
433 operation: command.type,
434 cause,
435 }),
436 ),
437 ),
438 );
439
440 const processEvent = (
441 event: ResourceMonitorEvent,
442 helloDeferred: Deferred.Deferred<ResourceMonitorHelloEvent>,
443 generation: number,
444 ): Effect.Effect<void, NativeTelemetryClientError> => {
445 switch (event.type) {
446 case "hello":
447 return Ref.update(state, (current) => ({
448 ...current,
449 status: "starting" as const,
450 hello: Option.some(event),
451 lastError: Option.none(),
452 })).pipe(
453 Effect.andThen(publishHealth),
454 Effect.andThen(Deferred.succeed(helloDeferred, event)),
455 Effect.asVoid,
456 );
457 case "snapshot":
458 return Effect.gen(function* () {
459 const nativeSnapshot = { generation, snapshot: event } satisfies NativeTelemetrySnapshot;
460 const sampledAt = DateTime.makeUnsafe(event.sampledAtUnixMs);
461 const healthChanged = yield* Ref.modify(state, (current) => [
462 current.status !== "healthy" || Option.isSome(current.lastError),
463 {
464 ...current,
465 status: "healthy" as const,
466 lastSampleAt: Option.some(sampledAt),
467 lastError: Option.none(),
468 },
469 ]);
470 if (healthChanged) yield* publishHealth;
471 yield* PubSub.publish(snapshots, nativeSnapshot);
472 if (event.requestId) {
473 const deferred = yield* Ref.modify(pendingSamples, (pending) => {
474 const next = new Map(pending);
475 const current = next.get(event.requestId!);
476 next.delete(event.requestId!);
477 return [Option.fromUndefinedOr(current), next];
478 });
479 if (Option.isSome(deferred)) {
480 yield* Deferred.succeed(deferred.value, nativeSnapshot);
481 }
482 }
483 });
484 case "historyChunk":
485 return Effect.gen(function* () {
486 const latestSnapshot = event.snapshots.at(-1);
487 const healthChanged = yield* Ref.modify(state, (current) => [
488 current.status !== "healthy" || Option.isSome(current.lastError),
489 {
490 ...current,
491 status: "healthy" as const,
492 lastSampleAt: latestSnapshot
493 ? Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs))
494 : current.lastSampleAt,
495 lastError: Option.none(),
496 },
497 ]);
498 if (healthChanged) yield* publishHealth;
499 const completed = yield* Ref.modify(pendingHistories, (pending) => {
500 const request = pending.get(event.requestId);
501 if (!request) return [Option.none(), pending] as const;
502 const snapshots = [...request.snapshots, ...event.snapshots];
503 const next = new Map(pending);
504 if (event.done) {
505 next.delete(event.requestId);
506 return [Option.some({ deferred: request.deferred, snapshots }), next] as const;
507 }
508 next.set(event.requestId, { deferred: request.deferred, snapshots });
509 return [Option.none(), next] as const;
510 });
511 if (Option.isSome(completed)) {
512 yield* Deferred.succeed(completed.value.deferred, completed.value.snapshots);
513 }
514 });
515 case "error":
516 return Ref.update(state, (current) => ({
517 ...current,
518 status: "degraded" as const,
519 lastError: Option.some(event.message),
520 })).pipe(
521 Effect.andThen(publishHealth),
522 Effect.andThen(
523 event.recoverable
524 ? Effect.void
525 : Effect.fail(
526 new NativeTelemetryCommandFailed({
527 operation: event.code,
528 cause: event.message,
529 }),
530 ),
531 ),
532 );
533 }
534 };
535
536 const runAttempt: Effect.Effect<void, NativeTelemetryClientError> = Effect.scoped(
537 Effect.gen(function* () {
538 const executablePath = yield* binary.resolve;
539 const command = ChildProcess.make(executablePath, [], {
540 cwd: config.cwd,
541 stdin: {
542 stream: "pipe",
543 endOnDone: false,
544 },
545 stdout: "pipe",
546 stderr: "pipe",
547 killSignal: "SIGTERM",
548 forceKillAfter: Duration.seconds(2),
549 });
550 const handle = yield* Effect.acquireRelease(
551 spawner
552 .spawn(command)
553 .pipe(
554 Effect.mapError(
555 (cause) => new NativeTelemetrySpawnFailed({ path: executablePath, cause }),
556 ),
557 ),
558 (child) => child.kill().pipe(Effect.ignore),
559 );
560 yield* Ref.update(state, (current) => ({
561 ...current,
562 status: "starting" as const,
563 handle: Option.some(handle),
564 hello: Option.none(),
565 }));
566 yield* publishHealth;
567 const generation = (yield* Ref.get(state)).restartCount;
568
569 const helloDeferred = yield* Deferred.make<ResourceMonitorHelloEvent>();
570 const eventFiber = yield* handle.stdout.pipe(
571 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
572 Stream.mapEffect(
573 (
574 value,
575 ): Effect.Effect<
576 ResourceMonitorEvent,
577 NativeTelemetryProtocolMismatch | NativeTelemetryDecodeFailed
578 > => {
579 const version = eventVersion(value);
580 if (version !== undefined && version !== RESOURCE_MONITOR_PROTOCOL_VERSION) {
581 return Effect.fail(
582 new NativeTelemetryProtocolMismatch({
583 expectedVersion: RESOURCE_MONITOR_PROTOCOL_VERSION,
584 receivedVersion: version,
585 }),
586 );
587 }
588 return decodeMonitorEvent(value).pipe(
589 Effect.mapError((cause) => new NativeTelemetryDecodeFailed({ cause })),
590 );
591 },
592 ),
593 Stream.runForEach((event) => processEvent(event, helloDeferred, generation)),
594 Effect.mapError((cause) =>
595 isProtocolMismatch(cause) || isDecodeFailed(cause) || isCommandFailed(cause)
596 ? cause
597 : new NativeTelemetryDecodeFailed({ cause }),
598 ),
599 Effect.forkScoped,
600 );
601 yield* handle.stderr.pipe(Stream.runDrain, Effect.ignore, Effect.forkScoped);
602
603 const hello = yield* Deferred.await(helloDeferred).pipe(
604 Effect.timeoutOption(HANDSHAKE_TIMEOUT),
605 Effect.flatMap(
606 Option.match({
607 onNone: () =>
608 Effect.fail(
609 new NativeTelemetryHandshakeTimedOut({
610 timeoutMs: Duration.toMillis(HANDSHAKE_TIMEOUT),
611 }),
612 ),
613 onSome: Effect.succeed,
614 }),
615 ),
616 );
617 yield* synchronizeCollectionControlOnStart(
618 controlMutex,
619 collectionControl,
620 appliedCollectionControl,
621 (control) =>
622 Effect.gen(function* () {
623 yield* writeCommand(handle, {
624 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
625 type: "configure",
626 rootPid: process.pid,
627 sampleIntervalMs: control.sampleIntervalMs,
628 externalProcesses: [...(yield* Ref.get(externalProcesses))],
629 });
630 if (control.liveSubscriberCount > 0) {
631 yield* writeCommand(handle, {
632 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
633 type: "setStreaming",
634 enabled: true,
635 });
636 }
637 }),
638 Ref.update(state, (current) => ({
639 ...current,
640 status: "healthy" as const,
641 hello: Option.some(hello),
642 })).pipe(Effect.andThen(publishHealth)),
643 );
644
645 yield* writeCommand(handle, {
646 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
647 type: "setExternalProcesses",
648 processes: [...(yield* Ref.get(externalProcesses))],
649 });
650
651 const exitEffect = handle.exitCode.pipe(
652 Effect.mapError(
653 (cause) =>
654 new NativeTelemetryCommandFailed({
655 operation: "waitForExit",
656 cause,
657 }),
658 ),
659 Effect.flatMap((exitCode) =>
660 Effect.fail(new NativeTelemetryExited({ exitCode: Number(exitCode) })),
661 ),
662 );
663 const decoderEffect = Fiber.join(eventFiber).pipe(
664 Effect.andThen(Effect.fail(new NativeTelemetryStreamClosed())),
665 );
666 return yield* Effect.raceFirst(exitEffect, decoderEffect);
667 }),
668 ).pipe(
669 Effect.ensuring(
670 Ref.update(state, (current) => ({
671 ...current,
672 handle: Option.none(),
673 })),
674 ),
675 );
676
677 yield* Effect.gen(function* () {
678 let failures: ReadonlyArray<number> = [];
679 let restartAttempt = 0;
680
681 while (true) {
682 const result = yield* Effect.result(runAttempt);
683 if (Result.isSuccess(result)) {
684 return;
685 }
686
687 const error = result.failure;
688 const now = DateTime.toEpochMillis(yield* DateTime.now);
689 const recentFailures = retainRecentNativeTelemetryFailures(failures, now);
690 if (recentFailures.length === 0) {
691 restartAttempt = 0;
692 }
693 failures = [...recentFailures, now];
694 const exhausted = failures.length >= MAX_FAILURES_PER_WINDOW;
695 yield* Ref.update(state, (current) => ({
696 ...current,
697 status: exhausted ? ("unavailable" as const) : ("degraded" as const),
698 hello: Option.none(),
699 lastError: Option.some(errorMessage(error)),
700 restartCount: current.restartCount + 1,
701 }));
702 yield* publishHealth;
703 yield* failPending(error);
704
705 if (exhausted) {
706 yield* Queue.take(retryQueue);
707 failures = [];
708 restartAttempt = 0;
709 yield* Ref.update(state, (current) => ({
710 ...current,
711 status: "starting" as const,
712 hello: Option.none(),
713 lastError: Option.none(),
714 }));
715 yield* publishHealth;
716 continue;
717 }
718
719 const manuallyRetried = yield* Effect.raceFirst(
720 Effect.sleep(restartDelay(restartAttempt)).pipe(Effect.as(false)),
721 Queue.take(retryQueue).pipe(Effect.as(true)),
722 );
723 restartAttempt = manuallyRetried ? 0 : restartAttempt + 1;
724 }
725 }).pipe(
726 Effect.catchCause((cause) =>
727 Cause.hasInterruptsOnly(cause)
728 ? Effect.void
729 : Ref.update(state, (current) => ({
730 ...current,
731 status: "unavailable" as const,
732 hello: Option.none(),
733 lastError: Option.some("Resource monitor supervisor stopped unexpectedly."),
734 })).pipe(
735 Effect.andThen(publishHealth),
736 Effect.andThen(
737 Effect.logWarning("Resource monitor supervisor failed", {
738 cause: Cause.pretty(cause),
739 }),
740 ),
741 ),
742 ),
743 Effect.forkScoped,
744 );
745
746 const applyCollectionControl = Effect.fn(
747 "resourceTelemetry.nativeTelemetryClient.applyCollectionControl",
748 )(function* (previous: CollectionControl, next: CollectionControl) {
749 const current = yield* Ref.get(state);
750 if (canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
751 const handle = Option.getOrThrow(current.handle);
752 if (previous.sampleIntervalMs !== next.sampleIntervalMs) {
753 yield* writeCommand(handle, {
754 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
755 type: "setSampleInterval",
756 sampleIntervalMs: next.sampleIntervalMs,
757 });
758 }
759 const wasStreaming = previous.liveSubscriberCount > 0;
760 const isStreaming = next.liveSubscriberCount > 0;
761 if (wasStreaming !== isStreaming) {
762 yield* writeCommand(handle, {
763 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
764 type: "setStreaming",
765 enabled: isStreaming,
766 });
767 }
768 }
769 });
770
771 const updateCollectionControl = (update: (current: CollectionControl) => CollectionControl) =>
772 controlMutex.withPermits(1)(
773 commitCollectionControlUpdate(
774 collectionControl,
775 appliedCollectionControl,
776 update,
777 applyCollectionControl,
778 ).pipe(Effect.ensuring(publishHealth), Effect.asVoid),
779 );
780
781 const setHostPowerState: NativeTelemetryClient["Service"]["setHostPowerState"] = (hostPower) =>
782 updateCollectionControl((current) => ({
783 ...current,
784 hostPower,
785 sampleIntervalMs: resolveNativeSampleIntervalMs(hostPower, current.liveSubscriberCount),
786 }));
787
788 const changeLiveSubscriberCount = Effect.fn(
789 "resourceTelemetry.nativeTelemetryClient.changeLiveSubscriberCount",
790 )(function* (delta: 1 | -1) {
791 yield* updateCollectionControl((current) => {
792 const liveSubscriberCount = Math.max(0, current.liveSubscriberCount + delta);
793 return {
794 ...current,
795 liveSubscriberCount,
796 sampleIntervalMs: resolveNativeSampleIntervalMs(current.hostPower, liveSubscriberCount),
797 };
798 });
799 });
800
801 const liveSnapshots = Stream.unwrap(
802 Effect.gen(function* () {
803 const subscription = yield* PubSub.subscribe(snapshots);
804 yield* Effect.acquireRelease(changeLiveSubscriberCount(1), () =>
805 changeLiveSubscriberCount(-1).pipe(Effect.ignore),
806 );
807 return Stream.fromSubscription(subscription);
808 }),
809 );
810
811 const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] = (
812 processes,
813 ) =>
814 Effect.gen(function* () {
815 yield* Ref.set(externalProcesses, [...processes]);
816 const current = yield* Ref.get(state);
817 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) return;
818 yield* writeCommand(Option.getOrThrow(current.handle), {
819 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
820 type: "setExternalProcesses",
821 processes: [...processes],
822 });
823 });
824
825 const readHistory: NativeTelemetryClient["Service"]["readHistory"] = (windowMs) =>
826 Effect.gen(function* () {
827 const current = yield* Ref.get(state);
828 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
829 return yield* new NativeTelemetryUnavailable({
830 reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
831 });
832 }
833 const requestId = yield* crypto.randomUUIDv4.pipe(
834 Effect.mapError(
835 (cause) =>
836 new NativeTelemetryCommandFailed({
837 operation: "createHistoryRequestId",
838 cause,
839 }),
840 ),
841 );
842 const deferred = yield* Deferred.make<
843 ReadonlyArray<ResourceMonitorSnapshotEvent>,
844 NativeTelemetryClientError
845 >();
846 yield* Ref.update(pendingHistories, (pending) => {
847 const next = new Map(pending);
848 next.set(requestId, { deferred, snapshots: [] });
849 return next;
850 });
851 return yield* writeCommand(Option.getOrThrow(current.handle), {
852 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
853 type: "readHistory",
854 requestId,
855 windowMs: Math.max(0, Math.round(windowMs)),
856 }).pipe(
857 Effect.andThen(
858 Deferred.await(deferred).pipe(
859 Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),
860 Effect.flatMap(
861 Option.match({
862 onNone: () =>
863 Effect.fail(
864 new NativeTelemetryRequestTimedOut({
865 operation: "readHistory",
866 timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),
867 }),
868 ),
869 onSome: Effect.succeed,
870 }),
871 ),
872 ),
873 ),
874 Effect.ensuring(
875 Ref.update(pendingHistories, (pending) => {
876 const next = new Map(pending);
877 next.delete(requestId);
878 return next;
879 }),
880 ),
881 );
882 });
883
884 const sampleNow: NativeTelemetryClient["Service"]["sampleNow"] = Effect.gen(function* () {
885 const current = yield* Ref.get(state);
886 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
887 return yield* new NativeTelemetryUnavailable({
888 reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
889 });
890 }
891
892 const requestId = yield* crypto.randomUUIDv4.pipe(
893 Effect.mapError(
894 (cause) =>
895 new NativeTelemetryCommandFailed({
896 operation: "createRequestId",
897 cause,
898 }),
899 ),
900 );
901 const deferred = yield* Deferred.make<NativeTelemetrySnapshot, NativeTelemetryClientError>();
902 yield* Ref.update(pendingSamples, (pending) => {
903 const next = new Map(pending);
904 next.set(requestId, deferred);
905 return next;
906 });
907 return yield* writeCommand(Option.getOrThrow(current.handle), {
908 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
909 type: "sampleNow",
910 requestId,
911 }).pipe(
912 Effect.andThen(
913 Deferred.await(deferred).pipe(
914 Effect.timeoutOption(SAMPLE_REQUEST_TIMEOUT),
915 Effect.flatMap(
916 Option.match({
917 onNone: () =>
918 Effect.fail(
919 new NativeTelemetryRequestTimedOut({
920 operation: "sampleNow",
921 timeoutMs: Duration.toMillis(SAMPLE_REQUEST_TIMEOUT),
922 }),
923 ),
924 onSome: Effect.succeed,
925 }),
926 ),
927 ),
928 ),
929 Effect.ensuring(
930 Ref.update(pendingSamples, (pending) => {
931 const next = new Map(pending);
932 next.delete(requestId);
933 return next;
934 }),
935 ),
936 );
937 });
938
939 const health = currentHealth;
940
941 return NativeTelemetryClient.of({
942 capabilities: Ref.get(state).pipe(
943 Effect.flatMap((current) =>
944 Option.match(current.hello, {
945 onNone: () =>
946 Effect.fail(
947 new NativeTelemetryUnavailable({
948 reason: Option.getOrElse(current.lastError, () => "handshake is incomplete"),
949 }),
950 ),
951 onSome: (hello) => Effect.succeed(hello.capabilities),
952 }),
953 ),
954 ),
955 snapshots: liveSnapshots,
956 readHistory,
957 setExternalProcesses,
958 setHostPowerState,
959 sampleNow,
960 retry: Ref.get(state).pipe(
961 Effect.flatMap((current) =>
962 !canRequestNativeTelemetryRetry(current.status, Option.isSome(current.handle))
963 ? Effect.succeed(false)
964 : Queue.offer(retryQueue, undefined).pipe(Effect.as(true)),
965 ),
966 ),
967 health,
968 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, health),
969 });
970});
971
972export const layer = Layer.effect(NativeTelemetryClient, make());
973
974export const layerTest = (
975 overrides: Partial<NativeTelemetryClient["Service"]> = {},
976): Layer.Layer<NativeTelemetryClient> => {
977 const health =
978 overrides.health ??
979 Effect.succeed({
980 status: "unavailable" as const,
981 hello: Option.none<ResourceMonitorHelloEvent>(),
982 lastSampleAt: Option.none<DateTime.Utc>(),
983 lastError: Option.some("Resource monitor test implementation is unavailable."),
984 restartCount: 0,
985 sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
986 });
987 return Layer.succeed(
988 NativeTelemetryClient,
989 NativeTelemetryClient.of({
990 capabilities: Effect.succeed({
991 cumulativeCpuTime: true,
992 currentCpuPercent: true,
993 residentMemory: true,
994 virtualMemory: true,
995 ioBytes: true,
996 processStartTime: true,
997 processTree: true,
998 }),
999 snapshots: Stream.empty,
1000 readHistory: () =>
1001 Effect.fail(
1002 new NativeTelemetryUnavailable({
1003 reason: "No resource monitor history was configured for this test.",
1004 }),
1005 ),
1006 setExternalProcesses: () => Effect.void,
1007 setHostPowerState: () => Effect.void,
1008 sampleNow: Effect.fail(
1009 new NativeTelemetryUnavailable({
1010 reason: "No resource monitor sample was configured for this test.",
1011 }),
1012 ),
1013 retry: Effect.succeed(false),
1014 health,
1015 subscribeHealth:
1016 overrides.subscribeHealth ??
1017 health.pipe(
1018 Effect.map((initial) => ({
1019 latest: initial,
1020 changes: Stream.empty,
1021 })),
1022 ),
1023 ...overrides,
1024 }),
1025 );
1026};