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

NativeTelemetryClient.ts

1,024 lines34.3 KB

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