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

DesktopTelemetryReceiver.ts

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