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

DesktopTelemetryReceiver.ts

838 lines28.9 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeNet from "node:net";
4import * as NodeTls from "node:tls";
5​
6import * as NodeStream from "@effect/platform-node/NodeStream";
7import {
8 DesktopHostTelemetryMessage,
9 type DesktopCuaDriverReport,
10 type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
11 type DesktopHostTelemetrySnapshot,
12 type DesktopShellEnvironmentSnapshot,
13 DesktopTelemetryControlMessage,
14 type DesktopUpdateChannel,
15 type DesktopUpdateStatusReport,
16 type ResourceTelemetrySourceStatus,
17} from "@t3tools/contracts";
18import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import { applyShellEnvironment } from "@t3tools/shared/shell";
21import * as Cause from "effect/Cause";
22import * as Context from "effect/Context";
23import * as DateTime from "effect/DateTime";
24import * as Duration from "effect/Duration";
25import * as Effect from "effect/Effect";
26import * as FileSystem from "effect/FileSystem";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as PubSub from "effect/PubSub";
30import * as Ref from "effect/Ref";
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";
36​
37import { eventVersion as messageVersion } from "./NativeTelemetryClient.ts";
38import * as ServerConfig from "../config.ts";
39import * as ServerSettings from "../serverSettings.ts";
40import { subscribeBeforeSnapshotWithoutMutex } from "../utils/subscribeBeforeSnapshot.ts";
41​
42const INITIAL_SAMPLE_DEADLINE_MS = 90_000;
43const MIN_SNAPSHOT_STALE_AFTER_MS = 90_000;
44const STALE_GRACE_MS = 30_000;
45const DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS = 30_000;
46const DEFAULT_HOST_POWER_IDLE_INTERVAL_MS = 120_000;
47const STALE_CHECK_INTERVAL = Duration.seconds(30);
48​
49export class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedError<DesktopTelemetryDescriptorUnavailable>()(
50 "DesktopTelemetryDescriptorUnavailable",
51 {
52 mode: Schema.String,
53 },
54) {
55 override get message(): string {
56 return `Desktop telemetry descriptor is unavailable in '${this.mode}' mode.`;
57 }
59​
60export class DesktopTelemetryProtocolMismatch extends Schema.TaggedError<DesktopTelemetryProtocolMismatch>()(
61 "DesktopTelemetryProtocolMismatch",
62 {
63 expectedVersion: Schema.Number,
64 receivedVersion: Schema.Number,
65 },
66) {
67 override get message(): string {
68 return `Desktop telemetry protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;
69 }
71​
72export class DesktopTelemetryDecodeFailed extends Schema.TaggedError<DesktopTelemetryDecodeFailed>()(
73 "DesktopTelemetryDecodeFailed",
74 {
75 cause: Schema.Defect(),
76 },
77) {
78 override get message(): string {
79 return "Failed to decode desktop telemetry.";
80 }
82​
83export class DesktopTelemetryStreamFailed extends Schema.TaggedError<DesktopTelemetryStreamFailed>()(
84 "DesktopTelemetryStreamFailed",
85 {
86 fd: Schema.Number,
87 cause: Schema.Defect(),
88 },
89) {
90 override get message(): string {
91 return `Desktop telemetry stream on fd ${this.fd} failed.`;
92 }
94​
95export class DesktopTelemetryStreamClosed extends Schema.TaggedError<DesktopTelemetryStreamClosed>()(
96 "DesktopTelemetryStreamClosed",
97 {
98 fd: Schema.Number,
99 },
100) {
101 override get message(): string {
102 return `Desktop telemetry stream on fd ${this.fd} closed.`;
103 }
105​
106export class DesktopTelemetryStale extends Schema.TaggedError<DesktopTelemetryStale>()(
107 "DesktopTelemetryStale",
108 {
109 fd: Schema.Number,
110 staleAfterMs: Schema.Number,
111 },
112) {
113 override get message(): string {
114 return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`;
115 }
117​
118export type DesktopTelemetryReceiverError =
119 | DesktopTelemetryDescriptorUnavailable
120 | DesktopTelemetryProtocolMismatch
121 | DesktopTelemetryDecodeFailed
122 | DesktopTelemetryStreamFailed
123 | DesktopTelemetryStreamClosed;
124​
125export class DesktopTelemetryControlFailed extends Schema.TaggedError<DesktopTelemetryControlFailed>()(
126 "DesktopTelemetryControlFailed",
127 {
128 fd: Schema.Number,
129 operation: Schema.String,
130 cause: Schema.Defect(),
131 },
132) {
133 override get message(): string {
134 return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`;
135 }
137​
138export class DesktopTelemetryControlStalled extends Schema.TaggedError<DesktopTelemetryControlStalled>()(
139 "DesktopTelemetryControlStalled",
140 {
141 fd: Schema.Number,
142 remainingBytes: Schema.Number,
143 },
144) {
145 override get message(): string {
146 return `Desktop telemetry control stalled on fd ${this.fd} with ${this.remainingBytes} bytes remaining.`;
147 }
149​
150export type DesktopTelemetryControlError =
151 | DesktopTelemetryControlFailed
152 | DesktopTelemetryControlStalled;
153​
154export interface DesktopTelemetryReceiverHealth {
155 readonly status: ResourceTelemetrySourceStatus;
156 readonly lastSampleAt: Option.Option<DateTime.Utc>;
157 readonly lastError: Option.Option<string>;
159​
160/** Moves the desktop app to `channel` and installs only `targetVersion`. */
161export interface DesktopTrackSwitch {
162 readonly channel: DesktopUpdateChannel;
163 readonly targetVersion: string;
165​
166export class DesktopTelemetryReceiver extends Context.Service<
167 DesktopTelemetryReceiver,
168 {
169 readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
170 readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
171 readonly subscribe: Effect.Effect<
172 {
173 readonly latest: Option.Option<DesktopHostTelemetrySnapshot>;
174 readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
175 },
176 never,
177 Scope.Scope
178 >;
179 readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>;
180 readonly subscribeHealth: Effect.Effect<
181 {
182 readonly latest: DesktopTelemetryReceiverHealth;
183 readonly changes: Stream.Stream<DesktopTelemetryReceiverHealth>;
184 },
185 never,
186 Scope.Scope
187 >;
188 readonly cuaReports: Stream.Stream<DesktopCuaDriverReport>;
189 readonly requestCuaDriver: (
190 requestId: string,
191 enabled: boolean,
192 ) => Effect.Effect<void, DesktopTelemetryControlError>;
193 readonly setDiagnosticsDemand: (
194 enabled: boolean,
195 ) => Effect.Effect<void, DesktopTelemetryControlError>;
196 /** Tells the desktop parent that the server accepts requests, so it can skip readiness polling. */
197 readonly announceServerReady: Effect.Effect<void, DesktopTelemetryControlError>;
198 readonly requestDesktopUpdate: (
199 requestId: string,
200 trackSwitch?: DesktopTrackSwitch,
201 ) => Effect.Effect<void, DesktopTelemetryControlError>;
202 readonly commitDesktopUpdate: (
203 requestId: string,
204 ) => Effect.Effect<void, DesktopTelemetryControlError>;
205 readonly cancelDesktopUpdate: (
206 requestId: string,
207 ) => Effect.Effect<void, DesktopTelemetryControlError>;
208 readonly desktopUpdates: Effect.Effect<
209 {
210 readonly latest: Option.Option<DesktopUpdateStatusReport>;
211 readonly changes: Stream.Stream<DesktopUpdateStatusReport>;
212 },
213 never,
214 Scope.Scope
215 >;
216 }
217>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
218​
219class DesktopShellCertificatesUpdateFailed extends Schema.TaggedError<DesktopShellCertificatesUpdateFailed>()(
220 "DesktopShellCertificatesUpdateFailed",
221 { cause: Schema.Defect() },
222) {
223 override get message(): string {
224 return "Failed to update desktop shell TLS certificates.";
225 }
227​
228export function makeApplyDesktopShellEnvironmentSnapshot(
229 environment: NodeJS.ProcessEnv,
230 platform: NodeJS.Platform,
231) {
232 let baseCertificates: Array<string> | undefined;
233 return Effect.fn("resourceTelemetry.desktopTelemetryReceiver.applyShellEnvironment")(function* (
234 message: DesktopShellEnvironmentSnapshot,
235 ) {
236 if (message.platform !== platform) return;
237 // Node's first default-CA enumeration consults process.env, so capture it before the patch.
238 if (message.environment.NODE_EXTRA_CA_CERTS !== undefined && baseCertificates === undefined) {
239 // Remove only the startup extras, preserving duplicates from bundled or system trust.
240 const extras = [...NodeTls.getCACertificates("extra")];
241 baseCertificates = NodeTls.getCACertificates("default").filter((certificate) => {
242 const index = extras.indexOf(certificate);
243 if (index === -1) return true;
244 extras.splice(index, 1);
245 return false;
246 });
247 }
248 applyShellEnvironment(environment, message.environment, platform);
249 if (message.environment.NODE_EXTRA_CA_CERTS !== undefined) {
250 yield* Effect.gen(function* () {
251 const certificates = baseCertificates;
252 // --use-openssl-ca roots are not enumerable; replacing the list would discard them.
253 if (certificates === undefined || certificates.length === 0) {
254 yield* Effect.logWarning(
255 "Preserving non-enumerable TLS trust. Restart to apply updated desktop shell certificates.",
256 );
257 return;
258 }
259 const fs = yield* FileSystem.FileSystem;
260 const file = message.environment.NODE_EXTRA_CA_CERTS;
261 const bundle = file ? yield* fs.readFileString(file) : undefined;
262 yield* Effect.try({
263 try: () => {
264 const extras =
265 bundle?.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? [];
266 if (bundle?.trim() && extras.length === 0) {
267 throw new Error("No PEM certificates found.");
268 }
269 NodeTls.setDefaultCACertificates([...certificates, ...extras]);
270 },
271 catch: (cause) => new DesktopShellCertificatesUpdateFailed({ cause }),
272 });
273 }).pipe(
274 Effect.catch((cause) =>
275 Effect.logWarning("Failed to update desktop shell TLS certificates.", Cause.fail(cause)),
276 ),
277 );
278 }
279 if (message.discovered) delete environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
280 });
282​
283const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);
284const encodeControlMessage = Schema.encodeEffect(
285 Schema.fromJsonString(DesktopTelemetryControlMessage),
286);
287const isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable);
288const isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch);
289const isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed);
290const isStreamFailed = Schema.is(DesktopTelemetryStreamFailed);
291​
292function isDesktopTelemetryContactStale(
293 lastContactAtMs: Option.Option<number>,
294 nowMs: number,
295): boolean {
296 return Option.exists(
297 lastContactAtMs,
298 (lastContact) => nowMs - lastContact >= INITIAL_SAMPLE_DEADLINE_MS,
299 );
301​
302function resolveDesktopTelemetrySnapshotStaleAfterMs(
303 activeIntervalMs: number,
304 idleIntervalMs: number,
305): number {
306 return Math.max(
307 MIN_SNAPSHOT_STALE_AFTER_MS,
308 Math.max(activeIntervalMs, idleIntervalMs) + STALE_GRACE_MS,
309 );
311​
312function initialDesktopTelemetryContactAt(
313 desktopTelemetryFd: number | undefined,
314 nowMs: number,
315): Option.Option<number> {
316 return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs);
318​
319const recordDesktopTelemetrySampleHealth = Effect.fn(
320 "resourceTelemetry.desktopTelemetryReceiver.recordSampleHealth",
321)(function* (
322 health: Ref.Ref<DesktopTelemetryReceiverHealth>,
323 healthChanges: PubSub.PubSub<DesktopTelemetryReceiverHealth>,
324 sampledAt: DateTime.Utc,
325) {
326 const next: DesktopTelemetryReceiverHealth = {
327 status: "healthy",
328 lastSampleAt: Option.some(sampledAt),
329 lastError: Option.none(),
330 };
331 yield* Ref.set(health, next);
332 yield* PubSub.publish(healthChanges, next);
333});
334​
335function normalizeReceiverError(error: unknown): DesktopTelemetryReceiverError {
336 if (
337 isDescriptorUnavailable(error) ||
338 isProtocolMismatch(error) ||
339 isDecodeFailed(error) ||
340 isStreamFailed(error)
341 ) {
342 return error;
343 }
344 return new DesktopTelemetryDecodeFailed({ cause: error });
346​
347export const writeAllToFileDescriptor = Effect.fn(
348 "resourceTelemetry.desktopTelemetryReceiver.writeAllToFileDescriptor",
349)(function* (fd: number, payload: Buffer) {
350 let offset = 0;
351 while (offset < payload.byteLength) {
352 const written = yield* Effect.callback<number, DesktopTelemetryControlFailed>(
353 (resume, signal) => {
354 if (signal.aborted) return;
355 try {
356 NodeFS.write(
357 fd,
358 payload,
359 offset,
360 payload.byteLength - offset,
361 null,
362 (error, bytesWritten) => {
363 if (error) {
364 resume(
365 Effect.fail(
366 new DesktopTelemetryControlFailed({
367 fd,
368 operation: "write",
369 cause: error,
370 }),
371 ),
372 );
373 return;
374 }
375 resume(Effect.succeed(bytesWritten));
376 },
377 );
378 } catch (cause) {
379 resume(
380 Effect.fail(
381 new DesktopTelemetryControlFailed({
382 fd,
383 operation: "write",
384 cause,
385 }),
386 ),
387 );
388 }
389 },
390 );
391 yield* requireDesktopTelemetryWriteProgress(fd, payload.byteLength - offset, written);
392 offset += written;
393 }
394});
395​
396export function requireDesktopTelemetryWriteProgress(
397 fd: number,
398 remainingBytes: number,
399 written: number,
400): Effect.Effect<void, DesktopTelemetryControlStalled> {
401 return written > 0
402 ? Effect.void
403 : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes }));
405​
406/** @public */
407export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () {
408 const config = yield* ServerConfig.ServerConfig;
409 const environment = yield* HostProcess.Environment;
410 const platform = yield* HostProcess.Platform;
411 const applyShellSnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, platform);
412 const serverSettings = yield* ServerSettings.ServerSettingsService;
413 const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
414 const receiverStartedAt = yield* DateTime.now;
415 const lastContactAtMs = yield* Ref.make(
416 initialDesktopTelemetryContactAt(
417 config.desktopTelemetryFd,
418 DateTime.toEpochMillis(receiverStartedAt),
419 ),
420 );
421 const snapshotStaleAfterMs = yield* Ref.make(
422 resolveDesktopTelemetrySnapshotStaleAfterMs(
423 DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS,
424 DEFAULT_HOST_POWER_IDLE_INTERVAL_MS,
425 ),
426 );
427 const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
428 const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);
429 const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
430 const cuaReports = yield* PubSub.unbounded<DesktopCuaDriverReport>();
431 const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
432 const controlMutex = yield* Semaphore.make(1);
433 const snapshotMutex = yield* Semaphore.make(1);
434 const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({
435 status: config.desktopTelemetryFd === undefined ? "unavailable" : "starting",
436 lastSampleAt: Option.none(),
437 lastError:
438 config.desktopTelemetryFd === undefined
439 ? Option.some(
440 new DesktopTelemetryDescriptorUnavailable({
441 mode: config.mode,
442 }).message,
443 )
444 : Option.none(),
445 });
446 const updateHealth = (
447 update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth,
448 ) =>
449 Ref.modify(health, (current) => {
450 const next = update(current);
451 return [next, next];
452 }).pipe(
453 Effect.flatMap((next) => PubSub.publish(healthChanges, next)),
454 Effect.asVoid,
455 );
456 const updateSampleHealth = (sampledAt: DateTime.Utc) =>
457 recordDesktopTelemetrySampleHealth(health, healthChanges, sampledAt);
458​
459 const sendControlMessage = (message: DesktopTelemetryControlMessage) =>
460 controlMutex.withPermits(1)(
461 Effect.gen(function* () {
462 const fd = config.desktopTelemetryControlFd;
463 if (fd === undefined) return;
464 const encoded = yield* encodeControlMessage(message).pipe(
465 Effect.mapError(
466 (cause) =>
467 new DesktopTelemetryControlFailed({
468 fd,
469 operation: "encode",
470 cause,
471 }),
472 ),
473 );
474 yield* writeAllToFileDescriptor(fd, Buffer.from(`${encoded}\n`)).pipe(
475 Effect.tapError((error) =>
476 updateHealth((current) => ({
477 ...current,
478 status: "degraded",
479 lastError: Option.some(error.message),
480 })),
481 ),
482 );
483 }),
484 );
485 const setDiagnosticsDemand: DesktopTelemetryReceiver["Service"]["setDiagnosticsDemand"] = (
486 enabled,
487 ) =>
488 sendControlMessage({
489 version: 1,
490 type: "setDiagnosticsDemand",
491 enabled,
492 });
493​
494 const sendHostPowerIntervals = (
495 settings: Parameters<typeof resolveServerBackgroundActivitySettings>[0],
496 ) => {
497 const resolved = resolveServerBackgroundActivitySettings(settings);
498 const activeIntervalMs = Math.max(
499 1,
500 Math.round(Duration.toMillis(resolved.hostPowerMonitorActiveInterval)),
501 );
502 const idleIntervalMs = Math.max(
503 1,
504 Math.round(Duration.toMillis(resolved.hostPowerMonitorIdleInterval)),
505 );
506 return sendControlMessage({
507 version: 1,
508 type: "setHostPowerIntervals",
509 activeIntervalMs,
510 idleIntervalMs,
511 }).pipe(
512 Effect.andThen(
513 Ref.set(
514 snapshotStaleAfterMs,
515 resolveDesktopTelemetrySnapshotStaleAfterMs(activeIntervalMs, idleIntervalMs),
516 ),
517 ),
518 );
519 };
520 if (config.desktopTelemetryControlFd !== undefined) {
521 const settingsChanges = yield* serverSettings.subscribeChanges;
522 const settings = yield* serverSettings.getSettings;
523 yield* sendHostPowerIntervals(settings).pipe(
524 Effect.catchCause((cause) =>
525 Effect.logWarning("Failed to configure desktop host-power intervals", {
526 cause: String(cause),
527 }),
528 ),
529 );
530 yield* settingsChanges.pipe(
531 Stream.runForEach((settings) =>
532 sendHostPowerIntervals(settings).pipe(
533 Effect.catchCause((cause) =>
534 Effect.logWarning("Failed to update desktop host-power intervals", {
535 cause: String(cause),
536 }),
537 ),
538 ),
539 ),
540 Effect.forkScoped,
541 );
542 }
543​
544 if (config.desktopTelemetryFd !== undefined) {
545 const fd = config.desktopTelemetryFd;
546 // The parent waits before closing; use cancellable socket reads so filesystem reads cannot block exit.
547 const readable = yield* Effect.acquireRelease(
548 Effect.try({
549 try: () => new NodeNet.Socket({ fd, readable: true, writable: false }),
550 catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
551 }),
552 (stream) =>
553 Effect.sync(() => {
554 stream.destroy();
555 }),
556 );
557​
558 const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> =
559 NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({
560 evaluate: () => readable,
561 closeOnDone: true,
562 onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
563 }).pipe(
564 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
565 Stream.mapEffect(
566 (
567 value,
568 ): Effect.Effect<
569 DesktopHostTelemetryMessageValue,
570 DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed
571 > => {
572 const version = messageVersion(value);
573 if (version !== undefined && version !== 1) {
574 return Effect.fail(
575 new DesktopTelemetryProtocolMismatch({
576 expectedVersion: 1,
577 receivedVersion: version,
578 }),
579 );
580 }
581 return decodeMessage(value).pipe(
582 Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),
583 );
584 },
585 ),
586 Stream.mapError(normalizeReceiverError),
587 );
588​
589 yield* messages.pipe(
590 Stream.runForEach((message) => {
591 const recordContact = DateTime.now.pipe(
592 Effect.flatMap((now) =>
593 Ref.set(lastContactAtMs, Option.some(DateTime.toEpochMillis(now))),
594 ),
595 );
596 if (message.type === "desktopTelemetryHello") {
597 return recordContact.pipe(
598 Effect.andThen(
599 updateHealth((current): DesktopTelemetryReceiverHealth => ({
600 ...current,
601 status: "healthy",
602 lastError: Option.none(),
603 })),
604 ),
605 );
606 }
607​
608 if (message.type === "shellEnvironment") {
609 return recordContact.pipe(Effect.andThen(applyShellSnapshot(message)));
610 }
611​
612 if (message.type === "cuaDriverReport") {
613 return recordContact.pipe(
614 Effect.andThen(PubSub.publish(cuaReports, message)),
615 Effect.asVoid,
616 );
617 }
618​
619 if (message.type === "desktopUpdateStatus") {
620 return recordContact.pipe(
621 Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))),
622 Effect.andThen(PubSub.publish(updateReportChanges, message)),
623 Effect.asVoid,
624 );
625 }
626​
627 const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);
628 return snapshotMutex.withPermits(1)(
629 recordContact.pipe(
630 Effect.andThen(Ref.set(latest, Option.some(message))),
631 Effect.andThen(updateSampleHealth(sampledAt)),
632 Effect.andThen(PubSub.publish(changes, message)),
633 Effect.asVoid,
634 ),
635 );
636 }),
637 Effect.andThen(
638 updateHealth((current): DesktopTelemetryReceiverHealth => ({
639 ...current,
640 status: "stopped",
641 lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),
642 })),
643 ),
644 Effect.catch((error) =>
645 updateHealth((current): DesktopTelemetryReceiverHealth => ({
646 ...current,
647 status: "degraded",
648 lastError: Option.some(error.message),
649 })),
650 ),
651 Effect.forkScoped,
652 );
653​
654 yield* Effect.forever(
655 Effect.sleep(STALE_CHECK_INTERVAL).pipe(
656 Effect.andThen(
657 snapshotMutex.withPermits(1)(
658 Effect.gen(function* () {
659 const now = yield* DateTime.now;
660 const nowMs = DateTime.toEpochMillis(now);
661 const staleAfterMs = yield* Ref.get(snapshotStaleAfterMs);
662 const staleSnapshot = yield* Ref.modify(latest, (current) => {
663 if (
664 Option.isNone(current) ||
665 current.value.power.stale ||
666 nowMs - current.value.sampledAtUnixMs < staleAfterMs
667 ) {
668 return [Option.none<DesktopHostTelemetrySnapshot>(), current] as const;
669 }
670 const stale: DesktopHostTelemetrySnapshot = {
671 ...current.value,
672 power: { ...current.value.power, stale: true },
673 };
674 return [Option.some(stale), Option.some(stale)] as const;
675 });
676 if (Option.isNone(staleSnapshot)) {
677 const lastContact = yield* Ref.get(lastContactAtMs);
678 if (!isDesktopTelemetryContactStale(lastContact, nowMs)) return;
679 const staleMessage = new DesktopTelemetryStale({
680 fd,
681 staleAfterMs: INITIAL_SAMPLE_DEADLINE_MS,
682 }).message;
683 const changed = yield* Ref.modify(health, (current) => {
684 if (
685 current.status === "stopped" ||
686 Option.isSome(current.lastSampleAt) ||
687 (current.status === "degraded" &&
688 Option.contains(current.lastError, staleMessage))
689 ) {
690 return [Option.none<DesktopTelemetryReceiverHealth>(), current] as const;
691 }
692 const next: DesktopTelemetryReceiverHealth = {
693 ...current,
694 status: "degraded",
695 lastError: Option.some(staleMessage),
696 };
697 return [Option.some(next), next] as const;
698 });
699 if (Option.isSome(changed)) {
700 yield* PubSub.publish(healthChanges, changed.value);
701 }
702 return;
703 }
704 yield* updateHealth((currentHealth) => ({
705 ...currentHealth,
706 status: currentHealth.status === "stopped" ? "stopped" : "degraded",
707 lastError:
708 currentHealth.status === "stopped"
709 ? currentHealth.lastError
710 : Option.some(new DesktopTelemetryStale({ fd, staleAfterMs }).message),
711 }));
712 yield* PubSub.publish(changes, staleSnapshot.value);
713 }),
714 ),
715 ),
716 ),
717 ).pipe(Effect.forkScoped);
718 }
719​
720 return DesktopTelemetryReceiver.of({
721 latest: Ref.get(latest),
722 changes: Stream.fromPubSub(changes),
723 subscribe: snapshotMutex.withPermits(1)(
724 Effect.gen(function* () {
725 const initial = yield* Ref.get(latest);
726 const subscription = yield* PubSub.subscribe(changes);
727 return {
728 latest: initial,
729 changes: Stream.fromSubscription(subscription),
730 };
731 }),
732 ),
733 health: Ref.get(health),
734 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
735 cuaReports: Stream.fromPubSub(cuaReports),
736 requestCuaDriver: Effect.fn("DesktopTelemetryReceiver.requestCuaDriver")(
737 function (requestId, enabled) {
738 return sendControlMessage({ version: 1, type: "cuaDriverRequest", requestId, enabled });
739 },
740 ),
741 setDiagnosticsDemand,
742 announceServerReady: sendControlMessage({ version: 1, type: "serverReady" }).pipe(
743 Effect.withSpan("DesktopTelemetryReceiver.announceServerReady"),
744 ),
745 requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(
746 function (requestId, trackSwitch) {
747 return sendControlMessage({
748 version: 1,
749 type: "requestDesktopUpdate",
750 requestId,
751 ...trackSwitch,
752 });
753 },
754 ),
755 commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(
756 function (requestId) {
757 return sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId });
758 },
759 ),
760 cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(
761 function (requestId) {
762 return sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId });
763 },
764 ),
765 desktopUpdates: Effect.gen(function* () {
766 const subscription = yield* PubSub.subscribe(updateReportChanges);
767 const initial = yield* Ref.get(latestUpdateReport);
768 return {
769 latest: initial,
770 changes: Stream.fromSubscription(subscription),
771 };
772 }),
773 });
774});
775​
776export const layer = Layer.effect(DesktopTelemetryReceiver, make());
777​
778export const layerTest = (
779 overrides: Partial<DesktopTelemetryReceiver["Service"]> = {},
780): Layer.Layer<DesktopTelemetryReceiver> => {
781 const latest = overrides.latest ?? Effect.succeedNone;
782 const changes = overrides.changes ?? Stream.empty;
783 const health =
784 overrides.health ??
785 Effect.succeed({
786 status: "unavailable" as const,
787 lastSampleAt: Option.none<DateTime.Utc>(),
788 lastError: Option.some("Desktop telemetry test implementation is unavailable."),
789 });
790 return Layer.succeed(
791 DesktopTelemetryReceiver,
792 DesktopTelemetryReceiver.of({
793 latest,
794 changes,
795 subscribe:
796 overrides.subscribe ??
797 latest.pipe(
798 Effect.map((initial) => ({
799 latest: initial,
800 changes,
801 })),
802 ),
803 health,
804 subscribeHealth:
805 overrides.subscribeHealth ??
806 health.pipe(
807 Effect.map((initial) => ({
808 latest: initial,
809 changes: Stream.empty,
810 })),
811 ),
812 cuaReports: Stream.empty,
813 requestCuaDriver: Effect.fn("DesktopTelemetryReceiver.requestCuaDriver")(function () {
814 return Effect.void;
815 }),
816 setDiagnosticsDemand: Effect.fn("DesktopTelemetryReceiver.setDiagnosticsDemand")(function () {
817 return Effect.void;
818 }),
819 announceServerReady: Effect.void,
820 requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(function () {
821 return Effect.void;
822 }),
823 commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(function () {
824 return Effect.void;
825 }),
826 cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(function () {
827 return Effect.void;
828 }),
829 desktopUpdates:
830 overrides.desktopUpdates ??
831 Effect.succeed({
832 latest: Option.none<DesktopUpdateStatusReport>(),
833 changes: Stream.empty,
834 }),
835 ...overrides,
836 }),
837 );
838};