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

DesktopTelemetryReceiver.ts

724 lines24.0 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3​
4import * as NodeStream from "@effect/platform-node/NodeStream";
5import {
6 DesktopHostTelemetryMessage,
7 type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
8 type DesktopHostTelemetrySnapshot,
9 DesktopTelemetryControlMessage,
10 type DesktopUpdateStatusReport,
11 type ResourceTelemetrySourceStatus,
12} from "@t3tools/contracts";
13import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
14import * as Context from "effect/Context";
15import * as DateTime from "effect/DateTime";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Ref from "effect/Ref";
22import * as Schema from "effect/Schema";
23import * as Semaphore from "effect/Semaphore";
24import * as Scope from "effect/Scope";
25import * as Stream from "effect/Stream";
26import * as Ndjson from "effect/unstable/encoding/Ndjson";
27​
28import { ServerConfig } from "../config.ts";
29import { ServerSettingsService } from "../serverSettings.ts";
30import { subscribeBeforeSnapshotWithoutMutex } from "../utils/subscribeBeforeSnapshot.ts";
31​
32const INITIAL_SAMPLE_DEADLINE_MS = 90_000;
33const MIN_SNAPSHOT_STALE_AFTER_MS = 90_000;
34const STALE_GRACE_MS = 30_000;
35const DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS = 30_000;
36const DEFAULT_HOST_POWER_IDLE_INTERVAL_MS = 120_000;
37const STALE_CHECK_INTERVAL = Duration.seconds(30);
38​
39export class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedErrorClass<DesktopTelemetryDescriptorUnavailable>()(
40 "DesktopTelemetryDescriptorUnavailable",
41 {
42 mode: Schema.String,
43 },
44) {
45 override get message(): string {
46 return `Desktop telemetry descriptor is unavailable in '${this.mode}' mode.`;
47 }
49​
50export class DesktopTelemetryProtocolMismatch extends Schema.TaggedErrorClass<DesktopTelemetryProtocolMismatch>()(
51 "DesktopTelemetryProtocolMismatch",
52 {
53 expectedVersion: Schema.Number,
54 receivedVersion: Schema.Number,
55 },
56) {
57 override get message(): string {
58 return `Desktop telemetry protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;
59 }
61​
62export class DesktopTelemetryDecodeFailed extends Schema.TaggedErrorClass<DesktopTelemetryDecodeFailed>()(
63 "DesktopTelemetryDecodeFailed",
64 {
65 cause: Schema.Defect(),
66 },
67) {
68 override get message(): string {
69 return "Failed to decode desktop telemetry.";
70 }
72​
73export class DesktopTelemetryStreamFailed extends Schema.TaggedErrorClass<DesktopTelemetryStreamFailed>()(
74 "DesktopTelemetryStreamFailed",
75 {
76 fd: Schema.Number,
77 cause: Schema.Defect(),
78 },
79) {
80 override get message(): string {
81 return `Desktop telemetry stream on fd ${this.fd} failed.`;
82 }
84​
85export class DesktopTelemetryStreamClosed extends Schema.TaggedErrorClass<DesktopTelemetryStreamClosed>()(
86 "DesktopTelemetryStreamClosed",
87 {
88 fd: Schema.Number,
89 },
90) {
91 override get message(): string {
92 return `Desktop telemetry stream on fd ${this.fd} closed.`;
93 }
95​
96export class DesktopTelemetryStale extends Schema.TaggedErrorClass<DesktopTelemetryStale>()(
97 "DesktopTelemetryStale",
98 {
99 fd: Schema.Number,
100 staleAfterMs: Schema.Number,
101 },
102) {
103 override get message(): string {
104 return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`;
105 }
107​
108export type DesktopTelemetryReceiverError =
109 | DesktopTelemetryDescriptorUnavailable
110 | DesktopTelemetryProtocolMismatch
111 | DesktopTelemetryDecodeFailed
112 | DesktopTelemetryStreamFailed
113 | DesktopTelemetryStreamClosed;
114​
115export class DesktopTelemetryControlFailed extends Schema.TaggedErrorClass<DesktopTelemetryControlFailed>()(
116 "DesktopTelemetryControlFailed",
117 {
118 fd: Schema.Number,
119 operation: Schema.String,
120 cause: Schema.Defect(),
121 },
122) {
123 override get message(): string {
124 return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`;
125 }
127​
128export class DesktopTelemetryControlStalled extends Schema.TaggedErrorClass<DesktopTelemetryControlStalled>()(
129 "DesktopTelemetryControlStalled",
130 {
131 fd: Schema.Number,
132 remainingBytes: Schema.Number,
133 },
134) {
135 override get message(): string {
136 return `Desktop telemetry control stalled on fd ${this.fd} with ${this.remainingBytes} bytes remaining.`;
137 }
139​
140export type DesktopTelemetryControlError =
141 | DesktopTelemetryControlFailed
142 | DesktopTelemetryControlStalled;
143​
144export interface DesktopTelemetryReceiverHealth {
145 readonly status: ResourceTelemetrySourceStatus;
146 readonly lastSampleAt: Option.Option<DateTime.Utc>;
147 readonly lastError: Option.Option<string>;
149​
150export class DesktopTelemetryReceiver extends Context.Service<
151 DesktopTelemetryReceiver,
152 {
153 readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
154 readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
155 readonly subscribe: Effect.Effect<
156 {
157 readonly latest: Option.Option<DesktopHostTelemetrySnapshot>;
158 readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
159 },
160 never,
161 Scope.Scope
162 >;
163 readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>;
164 readonly subscribeHealth: Effect.Effect<
165 {
166 readonly latest: DesktopTelemetryReceiverHealth;
167 readonly changes: Stream.Stream<DesktopTelemetryReceiverHealth>;
168 },
169 never,
170 Scope.Scope
171 >;
172 readonly setDiagnosticsDemand: (
173 enabled: boolean,
174 ) => Effect.Effect<void, DesktopTelemetryControlError>;
175 /** Asks the desktop app supervising this server to update itself. The
176 desktop answers with desktopUpdateStatus reports carrying the same
177 requestId. */
178 readonly requestDesktopUpdate: (
179 requestId: string,
180 ) => Effect.Effect<void, DesktopTelemetryControlError>;
181 readonly commitDesktopUpdate: (
182 requestId: string,
183 ) => Effect.Effect<void, DesktopTelemetryControlError>;
184 readonly cancelDesktopUpdate: (
185 requestId: string,
186 ) => Effect.Effect<void, DesktopTelemetryControlError>;
187 /** Latest desktop update state report plus subsequent reports. The
188 desktop replays its latest report when the backend attaches, so this
189 is populated shortly after startup on desktop-managed servers. */
190 readonly desktopUpdates: Effect.Effect<
191 {
192 readonly latest: Option.Option<DesktopUpdateStatusReport>;
193 readonly changes: Stream.Stream<DesktopUpdateStatusReport>;
194 },
195 never,
196 Scope.Scope
197 >;
198 }
199>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
200​
201const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);
202const encodeControlMessage = Schema.encodeEffect(
203 Schema.fromJsonString(DesktopTelemetryControlMessage),
204);
205const isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable);
206const isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch);
207const isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed);
208const isStreamFailed = Schema.is(DesktopTelemetryStreamFailed);
209​
210export function isDesktopTelemetryContactStale(
211 lastContactAtMs: Option.Option<number>,
212 nowMs: number,
213): boolean {
214 return Option.exists(
215 lastContactAtMs,
216 (lastContact) => nowMs - lastContact >= INITIAL_SAMPLE_DEADLINE_MS,
217 );
219​
220export function resolveDesktopTelemetrySnapshotStaleAfterMs(
221 activeIntervalMs: number,
222 idleIntervalMs: number,
223): number {
224 return Math.max(
225 MIN_SNAPSHOT_STALE_AFTER_MS,
226 Math.max(activeIntervalMs, idleIntervalMs) + STALE_GRACE_MS,
227 );
229​
230export function initialDesktopTelemetryContactAt(
231 desktopTelemetryFd: number | undefined,
232 nowMs: number,
233): Option.Option<number> {
234 return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs);
236​
237export const recordDesktopTelemetrySampleHealth = Effect.fn(
238 "resourceTelemetry.desktopTelemetryReceiver.recordSampleHealth",
239)(function* (
240 health: Ref.Ref<DesktopTelemetryReceiverHealth>,
241 healthChanges: PubSub.PubSub<DesktopTelemetryReceiverHealth>,
242 sampledAt: DateTime.Utc,
243) {
244 const next: DesktopTelemetryReceiverHealth = {
245 status: "healthy",
246 lastSampleAt: Option.some(sampledAt),
247 lastError: Option.none(),
248 };
249 yield* Ref.set(health, next);
250 yield* PubSub.publish(healthChanges, next);
251});
252​
253function normalizeReceiverError(error: unknown): DesktopTelemetryReceiverError {
254 if (
255 isDescriptorUnavailable(error) ||
256 isProtocolMismatch(error) ||
257 isDecodeFailed(error) ||
258 isStreamFailed(error)
259 ) {
260 return error;
261 }
262 return new DesktopTelemetryDecodeFailed({ cause: error });
264​
265function messageVersion(value: unknown): number | undefined {
266 if (typeof value !== "object" || value === null) return undefined;
267 const version = Reflect.get(value, "version");
268 return typeof version === "number" ? version : undefined;
270​
271export const writeAllToFileDescriptor = Effect.fn(
272 "resourceTelemetry.desktopTelemetryReceiver.writeAllToFileDescriptor",
273)(function* (fd: number, payload: Buffer) {
274 let offset = 0;
275 while (offset < payload.byteLength) {
276 const written = yield* Effect.callback<number, DesktopTelemetryControlFailed>(
277 (resume, signal) => {
278 if (signal.aborted) return;
279 try {
280 NodeFS.write(
281 fd,
282 payload,
283 offset,
284 payload.byteLength - offset,
285 null,
286 (error, bytesWritten) => {
287 if (error) {
288 resume(
289 Effect.fail(
290 new DesktopTelemetryControlFailed({
291 fd,
292 operation: "write",
293 cause: error,
294 }),
295 ),
296 );
297 return;
298 }
299 resume(Effect.succeed(bytesWritten));
300 },
301 );
302 } catch (cause) {
303 resume(
304 Effect.fail(
305 new DesktopTelemetryControlFailed({
306 fd,
307 operation: "write",
308 cause,
309 }),
310 ),
311 );
312 }
313 },
314 );
315 yield* requireDesktopTelemetryWriteProgress(fd, payload.byteLength - offset, written);
316 offset += written;
317 }
318});
319​
320export function requireDesktopTelemetryWriteProgress(
321 fd: number,
322 remainingBytes: number,
323 written: number,
324): Effect.Effect<void, DesktopTelemetryControlStalled> {
325 return written > 0
326 ? Effect.void
327 : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes }));
329​
330export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () {
331 const config = yield* ServerConfig;
332 const serverSettings = yield* ServerSettingsService;
333 const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
334 const receiverStartedAt = yield* DateTime.now;
335 const lastContactAtMs = yield* Ref.make(
336 initialDesktopTelemetryContactAt(
337 config.desktopTelemetryFd,
338 DateTime.toEpochMillis(receiverStartedAt),
339 ),
340 );
341 const snapshotStaleAfterMs = yield* Ref.make(
342 resolveDesktopTelemetrySnapshotStaleAfterMs(
343 DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS,
344 DEFAULT_HOST_POWER_IDLE_INTERVAL_MS,
345 ),
346 );
347 const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
348 const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);
349 const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
350 const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
351 const controlMutex = yield* Semaphore.make(1);
352 const snapshotMutex = yield* Semaphore.make(1);
353 const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({
354 status: config.desktopTelemetryFd === undefined ? "unavailable" : "starting",
355 lastSampleAt: Option.none(),
356 lastError:
357 config.desktopTelemetryFd === undefined
358 ? Option.some(
359 new DesktopTelemetryDescriptorUnavailable({
360 mode: config.mode,
361 }).message,
362 )
363 : Option.none(),
364 });
365 const updateHealth = (
366 update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth,
367 ) =>
368 Ref.modify(health, (current) => {
369 const next = update(current);
370 return [next, next];
371 }).pipe(
372 Effect.flatMap((next) => PubSub.publish(healthChanges, next)),
373 Effect.asVoid,
374 );
375 const updateSampleHealth = (sampledAt: DateTime.Utc) =>
376 recordDesktopTelemetrySampleHealth(health, healthChanges, sampledAt);
377​
378 const sendControlMessage = (message: DesktopTelemetryControlMessage) =>
379 controlMutex.withPermits(1)(
380 Effect.gen(function* () {
381 const fd = config.desktopTelemetryControlFd;
382 if (fd === undefined) return;
383 const encoded = yield* encodeControlMessage(message).pipe(
384 Effect.mapError(
385 (cause) =>
386 new DesktopTelemetryControlFailed({
387 fd,
388 operation: "encode",
389 cause,
390 }),
391 ),
392 );
393 yield* writeAllToFileDescriptor(fd, Buffer.from(`${encoded}\n`)).pipe(
394 Effect.tapError((error) =>
395 updateHealth((current) => ({
396 ...current,
397 status: "degraded",
398 lastError: Option.some(error.message),
399 })),
400 ),
401 );
402 }),
403 );
404 const setDiagnosticsDemand: DesktopTelemetryReceiver["Service"]["setDiagnosticsDemand"] = (
405 enabled,
406 ) =>
407 sendControlMessage({
408 version: 1,
409 type: "setDiagnosticsDemand",
410 enabled,
411 });
412​
413 const sendHostPowerIntervals = (
414 settings: Parameters<typeof resolveServerBackgroundActivitySettings>[0],
415 ) => {
416 const resolved = resolveServerBackgroundActivitySettings(settings);
417 const activeIntervalMs = Math.max(
418 1,
419 Math.round(Duration.toMillis(resolved.hostPowerMonitorActiveInterval)),
420 );
421 const idleIntervalMs = Math.max(
422 1,
423 Math.round(Duration.toMillis(resolved.hostPowerMonitorIdleInterval)),
424 );
425 return sendControlMessage({
426 version: 1,
427 type: "setHostPowerIntervals",
428 activeIntervalMs,
429 idleIntervalMs,
430 }).pipe(
431 Effect.andThen(
432 Ref.set(
433 snapshotStaleAfterMs,
434 resolveDesktopTelemetrySnapshotStaleAfterMs(activeIntervalMs, idleIntervalMs),
435 ),
436 ),
437 );
438 };
439 if (config.desktopTelemetryControlFd !== undefined) {
440 const settingsChanges = yield* serverSettings.subscribeChanges;
441 const settings = yield* serverSettings.getSettings;
442 yield* sendHostPowerIntervals(settings).pipe(
443 Effect.catchCause((cause) =>
444 Effect.logWarning("Failed to configure desktop host-power intervals", {
445 cause: String(cause),
446 }),
447 ),
448 );
449 yield* settingsChanges.pipe(
450 Stream.runForEach((settings) =>
451 sendHostPowerIntervals(settings).pipe(
452 Effect.catchCause((cause) =>
453 Effect.logWarning("Failed to update desktop host-power intervals", {
454 cause: String(cause),
455 }),
456 ),
457 ),
458 ),
459 Effect.forkScoped,
460 );
461 }
462​
463 if (config.desktopTelemetryFd !== undefined) {
464 const fd = config.desktopTelemetryFd;
465 const readable = yield* Effect.acquireRelease(
466 Effect.try({
467 try: () =>
468 NodeFS.createReadStream("", {
469 fd,
470 autoClose: true,
471 }),
472 catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
473 }),
474 (stream) =>
475 Effect.sync(() => {
476 stream.destroy();
477 }),
478 );
479​
480 const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> =
481 NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({
482 evaluate: () => readable,
483 closeOnDone: true,
484 onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
485 }).pipe(
486 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
487 Stream.mapEffect(
488 (
489 value,
490 ): Effect.Effect<
491 DesktopHostTelemetryMessageValue,
492 DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed
493 > => {
494 const version = messageVersion(value);
495 if (version !== undefined && version !== 1) {
496 return Effect.fail(
497 new DesktopTelemetryProtocolMismatch({
498 expectedVersion: 1,
499 receivedVersion: version,
500 }),
501 );
502 }
503 return decodeMessage(value).pipe(
504 Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),
505 );
506 },
507 ),
508 Stream.mapError(normalizeReceiverError),
509 );
510​
511 yield* messages.pipe(
512 Stream.runForEach((message) => {
513 const recordContact = DateTime.now.pipe(
514 Effect.flatMap((now) =>
515 Ref.set(lastContactAtMs, Option.some(DateTime.toEpochMillis(now))),
516 ),
517 );
518 if (message.type === "desktopTelemetryHello") {
519 return recordContact.pipe(
520 Effect.andThen(
521 updateHealth(
522 (current): DesktopTelemetryReceiverHealth => ({
523 ...current,
524 status: "healthy",
525 lastError: Option.none(),
526 }),
527 ),
528 ),
529 );
530 }
531​
532 // Not a resource sample: do not touch `latest` or sample health.
533 if (message.type === "desktopUpdateStatus") {
534 return recordContact.pipe(
535 Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))),
536 Effect.andThen(PubSub.publish(updateReportChanges, message)),
537 Effect.asVoid,
538 );
539 }
540​
541 const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);
542 return snapshotMutex.withPermits(1)(
543 recordContact.pipe(
544 Effect.andThen(Ref.set(latest, Option.some(message))),
545 Effect.andThen(updateSampleHealth(sampledAt)),
546 Effect.andThen(PubSub.publish(changes, message)),
547 Effect.asVoid,
548 ),
549 );
550 }),
551 Effect.andThen(
552 updateHealth(
553 (current): DesktopTelemetryReceiverHealth => ({
554 ...current,
555 status: "stopped",
556 lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),
557 }),
558 ),
559 ),
560 Effect.catch((error) =>
561 updateHealth(
562 (current): DesktopTelemetryReceiverHealth => ({
563 ...current,
564 status: "degraded",
565 lastError: Option.some(error.message),
566 }),
567 ),
568 ),
569 Effect.forkScoped,
570 );
571​
572 yield* Effect.forever(
573 Effect.sleep(STALE_CHECK_INTERVAL).pipe(
574 Effect.andThen(
575 snapshotMutex.withPermits(1)(
576 Effect.gen(function* () {
577 const now = yield* DateTime.now;
578 const nowMs = DateTime.toEpochMillis(now);
579 const staleAfterMs = yield* Ref.get(snapshotStaleAfterMs);
580 const staleSnapshot = yield* Ref.modify(latest, (current) => {
581 if (
582 Option.isNone(current) ||
583 current.value.power.stale ||
584 nowMs - current.value.sampledAtUnixMs < staleAfterMs
585 ) {
586 return [Option.none<DesktopHostTelemetrySnapshot>(), current] as const;
587 }
588 const stale: DesktopHostTelemetrySnapshot = {
589 ...current.value,
590 power: { ...current.value.power, stale: true },
591 };
592 return [Option.some(stale), Option.some(stale)] as const;
593 });
594 if (Option.isNone(staleSnapshot)) {
595 const lastContact = yield* Ref.get(lastContactAtMs);
596 if (!isDesktopTelemetryContactStale(lastContact, nowMs)) return;
597 const staleMessage = new DesktopTelemetryStale({
598 fd,
599 staleAfterMs: INITIAL_SAMPLE_DEADLINE_MS,
600 }).message;
601 const changed = yield* Ref.modify(health, (current) => {
602 if (
603 current.status === "stopped" ||
604 Option.isSome(current.lastSampleAt) ||
605 (current.status === "degraded" &&
606 Option.contains(current.lastError, staleMessage))
607 ) {
608 return [Option.none<DesktopTelemetryReceiverHealth>(), current] as const;
609 }
610 const next: DesktopTelemetryReceiverHealth = {
611 ...current,
612 status: "degraded",
613 lastError: Option.some(staleMessage),
614 };
615 return [Option.some(next), next] as const;
616 });
617 if (Option.isSome(changed)) {
618 yield* PubSub.publish(healthChanges, changed.value);
619 }
620 return;
621 }
622 yield* updateHealth((currentHealth) => ({
623 ...currentHealth,
624 status: currentHealth.status === "stopped" ? "stopped" : "degraded",
625 lastError:
626 currentHealth.status === "stopped"
627 ? currentHealth.lastError
628 : Option.some(new DesktopTelemetryStale({ fd, staleAfterMs }).message),
629 }));
630 yield* PubSub.publish(changes, staleSnapshot.value);
631 }),
632 ),
633 ),
634 ),
635 ).pipe(Effect.forkScoped);
636 }
637​
638 return DesktopTelemetryReceiver.of({
639 latest: Ref.get(latest),
640 changes: Stream.fromPubSub(changes),
641 subscribe: snapshotMutex.withPermits(1)(
642 Effect.gen(function* () {
643 const initial = yield* Ref.get(latest);
644 const subscription = yield* PubSub.subscribe(changes);
645 return {
646 latest: initial,
647 changes: Stream.fromSubscription(subscription),
648 };
649 }),
650 ),
651 health: Ref.get(health),
652 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
653 setDiagnosticsDemand,
654 requestDesktopUpdate: (requestId) =>
655 sendControlMessage({
656 version: 1,
657 type: "requestDesktopUpdate",
658 requestId,
659 }),
660 commitDesktopUpdate: (requestId) =>
661 sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId }),
662 cancelDesktopUpdate: (requestId) =>
663 sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId }),
664 desktopUpdates: Effect.gen(function* () {
665 const subscription = yield* PubSub.subscribe(updateReportChanges);
666 const initial = yield* Ref.get(latestUpdateReport);
667 return {
668 latest: initial,
669 changes: Stream.fromSubscription(subscription),
670 };
671 }),
672 });
673});
674​
675export const layer = Layer.effect(DesktopTelemetryReceiver, make());
676​
677export const layerTest = (
678 overrides: Partial<DesktopTelemetryReceiver["Service"]> = {},
679): Layer.Layer<DesktopTelemetryReceiver> => {
680 const latest = overrides.latest ?? Effect.succeedNone;
681 const changes = overrides.changes ?? Stream.empty;
682 const health =
683 overrides.health ??
684 Effect.succeed({
685 status: "unavailable" as const,
686 lastSampleAt: Option.none<DateTime.Utc>(),
687 lastError: Option.some("Desktop telemetry test implementation is unavailable."),
688 });
689 return Layer.succeed(
690 DesktopTelemetryReceiver,
691 DesktopTelemetryReceiver.of({
692 latest,
693 changes,
694 subscribe:
695 overrides.subscribe ??
696 latest.pipe(
697 Effect.map((initial) => ({
698 latest: initial,
699 changes,
700 })),
701 ),
702 health,
703 subscribeHealth:
704 overrides.subscribeHealth ??
705 health.pipe(
706 Effect.map((initial) => ({
707 latest: initial,
708 changes: Stream.empty,
709 })),
710 ),
711 setDiagnosticsDemand: () => Effect.void,
712 requestDesktopUpdate: () => Effect.void,
713 commitDesktopUpdate: () => Effect.void,
714 cancelDesktopUpdate: () => Effect.void,
715 desktopUpdates:
716 overrides.desktopUpdates ??
717 Effect.succeed({
718 latest: Option.none<DesktopUpdateStatusReport>(),
719 changes: Stream.empty,
720 }),
721 ...overrides,
722 }),
723 );
724};