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

NativeTelemetryClient.ts

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