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