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
76export class 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
134export class 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 nativeTelemetrySupervisorFailureMessage(_cause: Cause.Cause<unknown>): string {
344 return "Resource monitor supervisor stopped unexpectedly.";
345}
346
347export function canRequestNativeTelemetryRetry(
348 status: ResourceTelemetrySourceStatus,
349 hasHandle: boolean,
350): boolean {
351 return status !== "healthy" && status !== "starting" && !hasHandle;
352}
353
354export function canCommandNativeTelemetrySidecar(
355 status: ResourceTelemetrySourceStatus,
356 hasHandle: boolean,
357): boolean {
358 return hasHandle && (status === "healthy" || status === "degraded");
359}
360
361export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(function* () {
362 const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary;
363 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
364 const crypto = yield* Crypto.Crypto;
365 const config = yield* ServerConfig;
366 const initializedAt = yield* DateTime.now;
367 const state = yield* Ref.make(initialState);
368 const collectionControl = yield* Ref.make<CollectionControl>({
369 hostPower: {
370 source: "unknown",
371 idle: "unknown",
372 idleSeconds: null,
373 locked: "unknown",
374 suspended: false,
375 onBattery: "unknown",
376 lowPowerMode: "unknown",
377 thermalState: "unknown",
378 stale: true,
379 updatedAt: initializedAt,
380 },
381 liveSubscriberCount: 0,
382 sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
383 });
384 const appliedCollectionControl = yield* Ref.make(yield* Ref.get(collectionControl));
385 const externalProcesses = yield* Ref.make<ReadonlyArray<ResourceMonitorExternalProcess>>([]);
386 const pendingSamples = yield* Ref.make(
387 new Map<string, Deferred.Deferred<NativeTelemetrySnapshot, NativeTelemetryClientError>>(),
388 );
389 const pendingHistories = yield* Ref.make(new Map<string, PendingHistoryRequest>());
390 const snapshots = yield* PubSub.sliding<NativeTelemetrySnapshot>(8);
391 const healthChanges = yield* PubSub.sliding<NativeTelemetryClientHealth>(4);
392 const retryQueue = yield* Queue.sliding<void>(1);
393 const commandMutex = yield* Semaphore.make(1);
394 const controlMutex = yield* Semaphore.make(1);
395 const currentHealth = Effect.all([Ref.get(state), Ref.get(collectionControl)]).pipe(
396 Effect.map(([current, control]) => toHealth(current, control.sampleIntervalMs)),
397 );
398 const publishHealth = currentHealth.pipe(
399 Effect.flatMap((health) => PubSub.publish(healthChanges, health)),
400 Effect.asVoid,
401 );
402
403 const failPending = (error: NativeTelemetryClientError) =>
404 Effect.gen(function* () {
405 const samples = yield* Ref.getAndSet(pendingSamples, new Map());
406 const histories = yield* Ref.getAndSet(pendingHistories, new Map());
407 yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {
408 discard: true,
409 });
410 yield* Effect.forEach(
411 histories.values(),
412 (request) => Deferred.fail(request.deferred, error),
413 { discard: true },
414 );
415 });
416
417 const writeCommand = (
418 handle: ChildProcessSpawner.ChildProcessHandle,
419 command: ResourceMonitorCommand,
420 ): Effect.Effect<void, NativeTelemetryClientError> =>
421 commandMutex.withPermits(1)(
422 encodeMonitorCommand(command).pipe(
423 Effect.map((encoded) => `${encoded}\n`),
424 Effect.mapError(
425 (cause) =>
426 new NativeTelemetryCommandFailed({
427 operation: command.type,
428 cause,
429 }),
430 ),
431 Effect.flatMap((encoded) =>
432 Stream.run(Stream.encodeText(Stream.make(encoded)), handle.stdin),
433 ),
434 Effect.mapError(
435 (cause) =>
436 new NativeTelemetryCommandFailed({
437 operation: command.type,
438 cause,
439 }),
440 ),
441 ),
442 );
443
444 const processEvent = (
445 event: ResourceMonitorEvent,
446 helloDeferred: Deferred.Deferred<ResourceMonitorHelloEvent>,
447 generation: number,
448 ): Effect.Effect<void, NativeTelemetryClientError> => {
449 switch (event.type) {
450 case "hello":
451 return Ref.update(state, (current) => ({
452 ...current,
453 status: "starting" as const,
454 hello: Option.some(event),
455 lastError: Option.none(),
456 })).pipe(
457 Effect.andThen(publishHealth),
458 Effect.andThen(Deferred.succeed(helloDeferred, event)),
459 Effect.asVoid,
460 );
461 case "snapshot":
462 return Effect.gen(function* () {
463 const nativeSnapshot = { generation, snapshot: event } satisfies NativeTelemetrySnapshot;
464 const sampledAt = DateTime.makeUnsafe(event.sampledAtUnixMs);
465 const healthChanged = yield* Ref.modify(state, (current) => [
466 current.status !== "healthy" || Option.isSome(current.lastError),
467 {
468 ...current,
469 status: "healthy" as const,
470 lastSampleAt: Option.some(sampledAt),
471 lastError: Option.none(),
472 },
473 ]);
474 if (healthChanged) yield* publishHealth;
475 yield* PubSub.publish(snapshots, nativeSnapshot);
476 if (event.requestId) {
477 const deferred = yield* Ref.modify(pendingSamples, (pending) => {
478 const next = new Map(pending);
479 const current = next.get(event.requestId!);
480 next.delete(event.requestId!);
481 return [Option.fromUndefinedOr(current), next];
482 });
483 if (Option.isSome(deferred)) {
484 yield* Deferred.succeed(deferred.value, nativeSnapshot);
485 }
486 }
487 });
488 case "historyChunk":
489 return Effect.gen(function* () {
490 const latestSnapshot = event.snapshots.at(-1);
491 const healthChanged = yield* Ref.modify(state, (current) => [
492 current.status !== "healthy" || Option.isSome(current.lastError),
493 {
494 ...current,
495 status: "healthy" as const,
496 lastSampleAt: latestSnapshot
497 ? Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs))
498 : current.lastSampleAt,
499 lastError: Option.none(),
500 },
501 ]);
502 if (healthChanged) yield* publishHealth;
503 const completed = yield* Ref.modify(pendingHistories, (pending) => {
504 const request = pending.get(event.requestId);
505 if (!request) return [Option.none(), pending] as const;
506 const snapshots = [...request.snapshots, ...event.snapshots];
507 const next = new Map(pending);
508 if (event.done) {
509 next.delete(event.requestId);
510 return [Option.some({ deferred: request.deferred, snapshots }), next] as const;
511 }
512 next.set(event.requestId, { deferred: request.deferred, snapshots });
513 return [Option.none(), next] as const;
514 });
515 if (Option.isSome(completed)) {
516 yield* Deferred.succeed(completed.value.deferred, completed.value.snapshots);
517 }
518 });
519 case "error":
520 return Ref.update(state, (current) => ({
521 ...current,
522 status: "degraded" as const,
523 lastError: Option.some(event.message),
524 })).pipe(
525 Effect.andThen(publishHealth),
526 Effect.andThen(
527 event.recoverable
528 ? Effect.void
529 : Effect.fail(
530 new NativeTelemetryCommandFailed({
531 operation: event.code,
532 cause: event.message,
533 }),
534 ),
535 ),
536 );
537 }
538 };
539
540 const runAttempt: Effect.Effect<void, NativeTelemetryClientError> = Effect.scoped(
541 Effect.gen(function* () {
542 const executablePath = yield* binary.resolve;
543 const command = ChildProcess.make(executablePath, [], {
544 cwd: config.cwd,
545 stdin: {
546 stream: "pipe",
547 endOnDone: false,
548 },
549 stdout: "pipe",
550 stderr: "pipe",
551 killSignal: "SIGTERM",
552 forceKillAfter: Duration.seconds(2),
553 });
554 const handle = yield* Effect.acquireRelease(
555 spawner
556 .spawn(command)
557 .pipe(
558 Effect.mapError(
559 (cause) => new NativeTelemetrySpawnFailed({ path: executablePath, cause }),
560 ),
561 ),
562 (child) => child.kill().pipe(Effect.ignore),
563 );
564 yield* Ref.update(state, (current) => ({
565 ...current,
566 status: "starting" as const,
567 handle: Option.some(handle),
568 hello: Option.none(),
569 }));
570 yield* publishHealth;
571 const generation = (yield* Ref.get(state)).restartCount;
572
573 const helloDeferred = yield* Deferred.make<ResourceMonitorHelloEvent>();
574 const eventFiber = yield* handle.stdout.pipe(
575 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
576 Stream.mapEffect(
577 (
578 value,
579 ): Effect.Effect<
580 ResourceMonitorEvent,
581 NativeTelemetryProtocolMismatch | NativeTelemetryDecodeFailed
582 > => {
583 const version = eventVersion(value);
584 if (version !== undefined && version !== RESOURCE_MONITOR_PROTOCOL_VERSION) {
585 return Effect.fail(
586 new NativeTelemetryProtocolMismatch({
587 expectedVersion: RESOURCE_MONITOR_PROTOCOL_VERSION,
588 receivedVersion: version,
589 }),
590 );
591 }
592 return decodeMonitorEvent(value).pipe(
593 Effect.mapError((cause) => new NativeTelemetryDecodeFailed({ cause })),
594 );
595 },
596 ),
597 Stream.runForEach((event) => processEvent(event, helloDeferred, generation)),
598 Effect.mapError((cause) =>
599 isProtocolMismatch(cause) || isDecodeFailed(cause) || isCommandFailed(cause)
600 ? cause
601 : new NativeTelemetryDecodeFailed({ cause }),
602 ),
603 Effect.forkScoped,
604 );
605 yield* handle.stderr.pipe(Stream.runDrain, Effect.ignore, Effect.forkScoped);
606
607 const hello = yield* Deferred.await(helloDeferred).pipe(
608 Effect.timeoutOption(HANDSHAKE_TIMEOUT),
609 Effect.flatMap(
610 Option.match({
611 onNone: () =>
612 Effect.fail(
613 new NativeTelemetryHandshakeTimedOut({
614 timeoutMs: Duration.toMillis(HANDSHAKE_TIMEOUT),
615 }),
616 ),
617 onSome: Effect.succeed,
618 }),
619 ),
620 );
621 yield* synchronizeCollectionControlOnStart(
622 controlMutex,
623 collectionControl,
624 appliedCollectionControl,
625 (control) =>
626 Effect.gen(function* () {
627 yield* writeCommand(handle, {
628 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
629 type: "configure",
630 rootPid: process.pid,
631 sampleIntervalMs: control.sampleIntervalMs,
632 externalProcesses: [...(yield* Ref.get(externalProcesses))],
633 });
634 if (control.liveSubscriberCount > 0) {
635 yield* writeCommand(handle, {
636 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
637 type: "setStreaming",
638 enabled: true,
639 });
640 }
641 }),
642 Ref.update(state, (current) => ({
643 ...current,
644 status: "healthy" as const,
645 hello: Option.some(hello),
646 })).pipe(Effect.andThen(publishHealth)),
647 );
648
649 yield* writeCommand(handle, {
650 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
651 type: "setExternalProcesses",
652 processes: [...(yield* Ref.get(externalProcesses))],
653 });
654
655 const exitEffect = handle.exitCode.pipe(
656 Effect.mapError(
657 (cause) =>
658 new NativeTelemetryCommandFailed({
659 operation: "waitForExit",
660 cause,
661 }),
662 ),
663 Effect.flatMap((exitCode) =>
664 Effect.fail(new NativeTelemetryExited({ exitCode: Number(exitCode) })),
665 ),
666 );
667 const decoderEffect = Fiber.join(eventFiber).pipe(
668 Effect.andThen(Effect.fail(new NativeTelemetryStreamClosed())),
669 );
670 return yield* Effect.raceFirst(exitEffect, decoderEffect);
671 }),
672 ).pipe(
673 Effect.ensuring(
674 Ref.update(state, (current) => ({
675 ...current,
676 handle: Option.none(),
677 })),
678 ),
679 );
680
681 yield* Effect.gen(function* () {
682 let failures: ReadonlyArray<number> = [];
683 let restartAttempt = 0;
684
685 while (true) {
686 const result = yield* Effect.result(runAttempt);
687 if (Result.isSuccess(result)) {
688 return;
689 }
690
691 const error = result.failure;
692 const now = DateTime.toEpochMillis(yield* DateTime.now);
693 const recentFailures = retainRecentNativeTelemetryFailures(failures, now);
694 if (recentFailures.length === 0) {
695 restartAttempt = 0;
696 }
697 failures = [...recentFailures, now];
698 const exhausted = failures.length >= MAX_FAILURES_PER_WINDOW;
699 yield* Ref.update(state, (current) => ({
700 ...current,
701 status: exhausted ? ("unavailable" as const) : ("degraded" as const),
702 hello: Option.none(),
703 lastError: Option.some(errorMessage(error)),
704 restartCount: current.restartCount + 1,
705 }));
706 yield* publishHealth;
707 yield* failPending(error);
708
709 if (exhausted) {
710 yield* Queue.take(retryQueue);
711 failures = [];
712 restartAttempt = 0;
713 yield* Ref.update(state, (current) => ({
714 ...current,
715 status: "starting" as const,
716 hello: Option.none(),
717 lastError: Option.none(),
718 }));
719 yield* publishHealth;
720 continue;
721 }
722
723 const manuallyRetried = yield* Effect.raceFirst(
724 Effect.sleep(restartDelay(restartAttempt)).pipe(Effect.as(false)),
725 Queue.take(retryQueue).pipe(Effect.as(true)),
726 );
727 restartAttempt = manuallyRetried ? 0 : restartAttempt + 1;
728 }
729 }).pipe(
730 Effect.catchCause((cause) =>
731 Cause.hasInterruptsOnly(cause)
732 ? Effect.void
733 : Ref.update(state, (current) => ({
734 ...current,
735 status: "unavailable" as const,
736 hello: Option.none(),
737 lastError: Option.some(nativeTelemetrySupervisorFailureMessage(cause)),
738 })).pipe(
739 Effect.andThen(publishHealth),
740 Effect.andThen(
741 Effect.logWarning("Resource monitor supervisor failed", {
742 cause: Cause.pretty(cause),
743 }),
744 ),
745 ),
746 ),
747 Effect.forkScoped,
748 );
749
750 const applyCollectionControl = Effect.fn(
751 "resourceTelemetry.nativeTelemetryClient.applyCollectionControl",
752 )(function* (previous: CollectionControl, next: CollectionControl) {
753 const current = yield* Ref.get(state);
754 if (canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
755 const handle = Option.getOrThrow(current.handle);
756 if (previous.sampleIntervalMs !== next.sampleIntervalMs) {
757 yield* writeCommand(handle, {
758 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
759 type: "setSampleInterval",
760 sampleIntervalMs: next.sampleIntervalMs,
761 });
762 }
763 const wasStreaming = previous.liveSubscriberCount > 0;
764 const isStreaming = next.liveSubscriberCount > 0;
765 if (wasStreaming !== isStreaming) {
766 yield* writeCommand(handle, {
767 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
768 type: "setStreaming",
769 enabled: isStreaming,
770 });
771 }
772 }
773 });
774
775 const updateCollectionControl = (update: (current: CollectionControl) => CollectionControl) =>
776 controlMutex.withPermits(1)(
777 commitCollectionControlUpdate(
778 collectionControl,
779 appliedCollectionControl,
780 update,
781 applyCollectionControl,
782 ).pipe(Effect.ensuring(publishHealth), Effect.asVoid),
783 );
784
785 const setHostPowerState: NativeTelemetryClient["Service"]["setHostPowerState"] = (hostPower) =>
786 updateCollectionControl((current) => ({
787 ...current,
788 hostPower,
789 sampleIntervalMs: resolveNativeSampleIntervalMs(hostPower, current.liveSubscriberCount),
790 }));
791
792 const changeLiveSubscriberCount = Effect.fn(
793 "resourceTelemetry.nativeTelemetryClient.changeLiveSubscriberCount",
794 )(function* (delta: 1 | -1) {
795 yield* updateCollectionControl((current) => {
796 const liveSubscriberCount = Math.max(0, current.liveSubscriberCount + delta);
797 return {
798 ...current,
799 liveSubscriberCount,
800 sampleIntervalMs: resolveNativeSampleIntervalMs(current.hostPower, liveSubscriberCount),
801 };
802 });
803 });
804
805 const liveSnapshots = Stream.unwrap(
806 Effect.gen(function* () {
807 const subscription = yield* PubSub.subscribe(snapshots);
808 yield* Effect.acquireRelease(changeLiveSubscriberCount(1), () =>
809 changeLiveSubscriberCount(-1).pipe(Effect.ignore),
810 );
811 return Stream.fromSubscription(subscription);
812 }),
813 );
814
815 const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] = (
816 processes,
817 ) =>
818 Effect.gen(function* () {
819 yield* Ref.set(externalProcesses, [...processes]);
820 const current = yield* Ref.get(state);
821 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) return;
822 yield* writeCommand(Option.getOrThrow(current.handle), {
823 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
824 type: "setExternalProcesses",
825 processes: [...processes],
826 });
827 });
828
829 const readHistory: NativeTelemetryClient["Service"]["readHistory"] = (windowMs) =>
830 Effect.gen(function* () {
831 const current = yield* Ref.get(state);
832 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
833 return yield* new NativeTelemetryUnavailable({
834 reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
835 });
836 }
837 const requestId = yield* crypto.randomUUIDv4.pipe(
838 Effect.mapError(
839 (cause) =>
840 new NativeTelemetryCommandFailed({
841 operation: "createHistoryRequestId",
842 cause,
843 }),
844 ),
845 );
846 const deferred = yield* Deferred.make<
847 ReadonlyArray<ResourceMonitorSnapshotEvent>,
848 NativeTelemetryClientError
849 >();
850 yield* Ref.update(pendingHistories, (pending) => {
851 const next = new Map(pending);
852 next.set(requestId, { deferred, snapshots: [] });
853 return next;
854 });
855 return yield* writeCommand(Option.getOrThrow(current.handle), {
856 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
857 type: "readHistory",
858 requestId,
859 windowMs: Math.max(0, Math.round(windowMs)),
860 }).pipe(
861 Effect.andThen(
862 Deferred.await(deferred).pipe(
863 Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),
864 Effect.flatMap(
865 Option.match({
866 onNone: () =>
867 Effect.fail(
868 new NativeTelemetryRequestTimedOut({
869 operation: "readHistory",
870 timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),
871 }),
872 ),
873 onSome: Effect.succeed,
874 }),
875 ),
876 ),
877 ),
878 Effect.ensuring(
879 Ref.update(pendingHistories, (pending) => {
880 const next = new Map(pending);
881 next.delete(requestId);
882 return next;
883 }),
884 ),
885 );
886 });
887
888 const sampleNow: NativeTelemetryClient["Service"]["sampleNow"] = Effect.gen(function* () {
889 const current = yield* Ref.get(state);
890 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
891 return yield* new NativeTelemetryUnavailable({
892 reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
893 });
894 }
895
896 const requestId = yield* crypto.randomUUIDv4.pipe(
897 Effect.mapError(
898 (cause) =>
899 new NativeTelemetryCommandFailed({
900 operation: "createRequestId",
901 cause,
902 }),
903 ),
904 );
905 const deferred = yield* Deferred.make<NativeTelemetrySnapshot, NativeTelemetryClientError>();
906 yield* Ref.update(pendingSamples, (pending) => {
907 const next = new Map(pending);
908 next.set(requestId, deferred);
909 return next;
910 });
911 return yield* writeCommand(Option.getOrThrow(current.handle), {
912 version: RESOURCE_MONITOR_PROTOCOL_VERSION,
913 type: "sampleNow",
914 requestId,
915 }).pipe(
916 Effect.andThen(
917 Deferred.await(deferred).pipe(
918 Effect.timeoutOption(SAMPLE_REQUEST_TIMEOUT),
919 Effect.flatMap(
920 Option.match({
921 onNone: () =>
922 Effect.fail(
923 new NativeTelemetryRequestTimedOut({
924 operation: "sampleNow",
925 timeoutMs: Duration.toMillis(SAMPLE_REQUEST_TIMEOUT),
926 }),
927 ),
928 onSome: Effect.succeed,
929 }),
930 ),
931 ),
932 ),
933 Effect.ensuring(
934 Ref.update(pendingSamples, (pending) => {
935 const next = new Map(pending);
936 next.delete(requestId);
937 return next;
938 }),
939 ),
940 );
941 });
942
943 const health = currentHealth;
944
945 return NativeTelemetryClient.of({
946 capabilities: Ref.get(state).pipe(
947 Effect.flatMap((current) =>
948 Option.match(current.hello, {
949 onNone: () =>
950 Effect.fail(
951 new NativeTelemetryUnavailable({
952 reason: Option.getOrElse(current.lastError, () => "handshake is incomplete"),
953 }),
954 ),
955 onSome: (hello) => Effect.succeed(hello.capabilities),
956 }),
957 ),
958 ),
959 snapshots: liveSnapshots,
960 readHistory,
961 setExternalProcesses,
962 setHostPowerState,
963 sampleNow,
964 retry: Ref.get(state).pipe(
965 Effect.flatMap((current) =>
966 !canRequestNativeTelemetryRetry(current.status, Option.isSome(current.handle))
967 ? Effect.succeed(false)
968 : Queue.offer(retryQueue, undefined).pipe(Effect.as(true)),
969 ),
970 ),
971 health,
972 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, health),
973 });
974});
975
976export const layer = Layer.effect(NativeTelemetryClient, make());
977
978export const layerTest = (
979 overrides: Partial<NativeTelemetryClient["Service"]> = {},
980): Layer.Layer<NativeTelemetryClient> => {
981 const health =
982 overrides.health ??
983 Effect.succeed({
984 status: "unavailable" as const,
985 hello: Option.none<ResourceMonitorHelloEvent>(),
986 lastSampleAt: Option.none<DateTime.Utc>(),
987 lastError: Option.some("Resource monitor test implementation is unavailable."),
988 restartCount: 0,
989 sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,
990 });
991 return Layer.succeed(
992 NativeTelemetryClient,
993 NativeTelemetryClient.of({
994 capabilities: Effect.succeed({
995 cumulativeCpuTime: true,
996 currentCpuPercent: true,
997 residentMemory: true,
998 virtualMemory: true,
999 ioBytes: true,
1000 processStartTime: true,
1001 processTree: true,
1002 }),
1003 snapshots: Stream.empty,
1004 readHistory: () =>
1005 Effect.fail(
1006 new NativeTelemetryUnavailable({
1007 reason: "No resource monitor history was configured for this test.",
1008 }),
1009 ),
1010 setExternalProcesses: () => Effect.void,
1011 setHostPowerState: () => Effect.void,
1012 sampleNow: Effect.fail(
1013 new NativeTelemetryUnavailable({
1014 reason: "No resource monitor sample was configured for this test.",
1015 }),
1016 ),
1017 retry: Effect.succeed(false),
1018 health,
1019 subscribeHealth:
1020 overrides.subscribeHealth ??
1021 health.pipe(
1022 Effect.map((initial) => ({
1023 latest: initial,
1024 changes: Stream.empty,
1025 })),
1026 ),
1027 ...overrides,
1028 }),
1029 );
1030};