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

NativeTelemetryClient.ts

1,117 lines37.6 KB

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