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