Open History to see the last commit
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 * as ServerConfig from "../config.ts";
29import * as ServerSettings 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.TaggedError<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 }
48}
49
50export class DesktopTelemetryProtocolMismatch extends Schema.TaggedError<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 }
60}
61
62export class DesktopTelemetryDecodeFailed extends Schema.TaggedError<DesktopTelemetryDecodeFailed>()(
63 "DesktopTelemetryDecodeFailed",
64 {
65 cause: Schema.Defect(),
66 },
67) {
68 override get message(): string {
69 return "Failed to decode desktop telemetry.";
70 }
71}
72
73export class DesktopTelemetryStreamFailed extends Schema.TaggedError<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 }
83}
84
85export class DesktopTelemetryStreamClosed extends Schema.TaggedError<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 }
94}
95
96export class DesktopTelemetryStale extends Schema.TaggedError<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 }
106}
107
108export type DesktopTelemetryReceiverError =
109 | DesktopTelemetryDescriptorUnavailable
110 | DesktopTelemetryProtocolMismatch
111 | DesktopTelemetryDecodeFailed
112 | DesktopTelemetryStreamFailed
113 | DesktopTelemetryStreamClosed;
114
115export class DesktopTelemetryControlFailed extends Schema.TaggedError<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 }
126}
127
128export class DesktopTelemetryControlStalled extends Schema.TaggedError<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 }
138}
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>;
148}
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 );
218}
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 );
228}
229
230export function initialDesktopTelemetryContactAt(
231 desktopTelemetryFd: number | undefined,
232 nowMs: number,
233): Option.Option<number> {
234 return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs);
235}
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 });
263}
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;
269}
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 }));
328}
329
330/** @public Service construction is part of the canonical Effect module API. */
331export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () {
332 const config = yield* ServerConfig.ServerConfig;
333 const serverSettings = yield* ServerSettings.ServerSettingsService;
334 const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
335 const receiverStartedAt = yield* DateTime.now;
336 const lastContactAtMs = yield* Ref.make(
337 initialDesktopTelemetryContactAt(
338 config.desktopTelemetryFd,
339 DateTime.toEpochMillis(receiverStartedAt),
340 ),
341 );
342 const snapshotStaleAfterMs = yield* Ref.make(
343 resolveDesktopTelemetrySnapshotStaleAfterMs(
344 DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS,
345 DEFAULT_HOST_POWER_IDLE_INTERVAL_MS,
346 ),
347 );
348 const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
349 const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);
350 const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
351 const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
352 const controlMutex = yield* Semaphore.make(1);
353 const snapshotMutex = yield* Semaphore.make(1);
354 const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({
355 status: config.desktopTelemetryFd === undefined ? "unavailable" : "starting",
356 lastSampleAt: Option.none(),
357 lastError:
358 config.desktopTelemetryFd === undefined
359 ? Option.some(
360 new DesktopTelemetryDescriptorUnavailable({
361 mode: config.mode,
362 }).message,
363 )
364 : Option.none(),
365 });
366 const updateHealth = (
367 update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth,
368 ) =>
369 Ref.modify(health, (current) => {
370 const next = update(current);
371 return [next, next];
372 }).pipe(
373 Effect.flatMap((next) => PubSub.publish(healthChanges, next)),
374 Effect.asVoid,
375 );
376 const updateSampleHealth = (sampledAt: DateTime.Utc) =>
377 recordDesktopTelemetrySampleHealth(health, healthChanges, sampledAt);
378
379 const sendControlMessage = (message: DesktopTelemetryControlMessage) =>
380 controlMutex.withPermits(1)(
381 Effect.gen(function* () {
382 const fd = config.desktopTelemetryControlFd;
383 if (fd === undefined) return;
384 const encoded = yield* encodeControlMessage(message).pipe(
385 Effect.mapError(
386 (cause) =>
387 new DesktopTelemetryControlFailed({
388 fd,
389 operation: "encode",
390 cause,
391 }),
392 ),
393 );
394 yield* writeAllToFileDescriptor(fd, Buffer.from(`${encoded}\n`)).pipe(
395 Effect.tapError((error) =>
396 updateHealth((current) => ({
397 ...current,
398 status: "degraded",
399 lastError: Option.some(error.message),
400 })),
401 ),
402 );
403 }),
404 );
405 const setDiagnosticsDemand: DesktopTelemetryReceiver["Service"]["setDiagnosticsDemand"] = (
406 enabled,
407 ) =>
408 sendControlMessage({
409 version: 1,
410 type: "setDiagnosticsDemand",
411 enabled,
412 });
413
414 const sendHostPowerIntervals = (
415 settings: Parameters<typeof resolveServerBackgroundActivitySettings>[0],
416 ) => {
417 const resolved = resolveServerBackgroundActivitySettings(settings);
418 const activeIntervalMs = Math.max(
419 1,
420 Math.round(Duration.toMillis(resolved.hostPowerMonitorActiveInterval)),
421 );
422 const idleIntervalMs = Math.max(
423 1,
424 Math.round(Duration.toMillis(resolved.hostPowerMonitorIdleInterval)),
425 );
426 return sendControlMessage({
427 version: 1,
428 type: "setHostPowerIntervals",
429 activeIntervalMs,
430 idleIntervalMs,
431 }).pipe(
432 Effect.andThen(
433 Ref.set(
434 snapshotStaleAfterMs,
435 resolveDesktopTelemetrySnapshotStaleAfterMs(activeIntervalMs, idleIntervalMs),
436 ),
437 ),
438 );
439 };
440 if (config.desktopTelemetryControlFd !== undefined) {
441 const settingsChanges = yield* serverSettings.subscribeChanges;
442 const settings = yield* serverSettings.getSettings;
443 yield* sendHostPowerIntervals(settings).pipe(
444 Effect.catchCause((cause) =>
445 Effect.logWarning("Failed to configure desktop host-power intervals", {
446 cause: String(cause),
447 }),
448 ),
449 );
450 yield* settingsChanges.pipe(
451 Stream.runForEach((settings) =>
452 sendHostPowerIntervals(settings).pipe(
453 Effect.catchCause((cause) =>
454 Effect.logWarning("Failed to update desktop host-power intervals", {
455 cause: String(cause),
456 }),
457 ),
458 ),
459 ),
460 Effect.forkScoped,
461 );
462 }
463
464 if (config.desktopTelemetryFd !== undefined) {
465 const fd = config.desktopTelemetryFd;
466 const readable = yield* Effect.acquireRelease(
467 Effect.try({
468 try: () =>
469 NodeFS.createReadStream("", {
470 fd,
471 autoClose: true,
472 }),
473 catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
474 }),
475 (stream) =>
476 Effect.sync(() => {
477 stream.destroy();
478 }),
479 );
480
481 const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> =
482 NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({
483 evaluate: () => readable,
484 closeOnDone: true,
485 onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),
486 }).pipe(
487 Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
488 Stream.mapEffect(
489 (
490 value,
491 ): Effect.Effect<
492 DesktopHostTelemetryMessageValue,
493 DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed
494 > => {
495 const version = messageVersion(value);
496 if (version !== undefined && version !== 1) {
497 return Effect.fail(
498 new DesktopTelemetryProtocolMismatch({
499 expectedVersion: 1,
500 receivedVersion: version,
501 }),
502 );
503 }
504 return decodeMessage(value).pipe(
505 Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),
506 );
507 },
508 ),
509 Stream.mapError(normalizeReceiverError),
510 );
511
512 yield* messages.pipe(
513 Stream.runForEach((message) => {
514 const recordContact = DateTime.now.pipe(
515 Effect.flatMap((now) =>
516 Ref.set(lastContactAtMs, Option.some(DateTime.toEpochMillis(now))),
517 ),
518 );
519 if (message.type === "desktopTelemetryHello") {
520 return recordContact.pipe(
521 Effect.andThen(
522 updateHealth((current): DesktopTelemetryReceiverHealth => ({
523 ...current,
524 status: "healthy",
525 lastError: Option.none(),
526 })),
527 ),
528 );
529 }
530
531 // Not a resource sample: do not touch `latest` or sample health.
532 if (message.type === "desktopUpdateStatus") {
533 return recordContact.pipe(
534 Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))),
535 Effect.andThen(PubSub.publish(updateReportChanges, message)),
536 Effect.asVoid,
537 );
538 }
539
540 const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);
541 return snapshotMutex.withPermits(1)(
542 recordContact.pipe(
543 Effect.andThen(Ref.set(latest, Option.some(message))),
544 Effect.andThen(updateSampleHealth(sampledAt)),
545 Effect.andThen(PubSub.publish(changes, message)),
546 Effect.asVoid,
547 ),
548 );
549 }),
550 Effect.andThen(
551 updateHealth((current): DesktopTelemetryReceiverHealth => ({
552 ...current,
553 status: "stopped",
554 lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),
555 })),
556 ),
557 Effect.catch((error) =>
558 updateHealth((current): DesktopTelemetryReceiverHealth => ({
559 ...current,
560 status: "degraded",
561 lastError: Option.some(error.message),
562 })),
563 ),
564 Effect.forkScoped,
565 );
566
567 yield* Effect.forever(
568 Effect.sleep(STALE_CHECK_INTERVAL).pipe(
569 Effect.andThen(
570 snapshotMutex.withPermits(1)(
571 Effect.gen(function* () {
572 const now = yield* DateTime.now;
573 const nowMs = DateTime.toEpochMillis(now);
574 const staleAfterMs = yield* Ref.get(snapshotStaleAfterMs);
575 const staleSnapshot = yield* Ref.modify(latest, (current) => {
576 if (
577 Option.isNone(current) ||
578 current.value.power.stale ||
579 nowMs - current.value.sampledAtUnixMs < staleAfterMs
580 ) {
581 return [Option.none<DesktopHostTelemetrySnapshot>(), current] as const;
582 }
583 const stale: DesktopHostTelemetrySnapshot = {
584 ...current.value,
585 power: { ...current.value.power, stale: true },
586 };
587 return [Option.some(stale), Option.some(stale)] as const;
588 });
589 if (Option.isNone(staleSnapshot)) {
590 const lastContact = yield* Ref.get(lastContactAtMs);
591 if (!isDesktopTelemetryContactStale(lastContact, nowMs)) return;
592 const staleMessage = new DesktopTelemetryStale({
593 fd,
594 staleAfterMs: INITIAL_SAMPLE_DEADLINE_MS,
595 }).message;
596 const changed = yield* Ref.modify(health, (current) => {
597 if (
598 current.status === "stopped" ||
599 Option.isSome(current.lastSampleAt) ||
600 (current.status === "degraded" &&
601 Option.contains(current.lastError, staleMessage))
602 ) {
603 return [Option.none<DesktopTelemetryReceiverHealth>(), current] as const;
604 }
605 const next: DesktopTelemetryReceiverHealth = {
606 ...current,
607 status: "degraded",
608 lastError: Option.some(staleMessage),
609 };
610 return [Option.some(next), next] as const;
611 });
612 if (Option.isSome(changed)) {
613 yield* PubSub.publish(healthChanges, changed.value);
614 }
615 return;
616 }
617 yield* updateHealth((currentHealth) => ({
618 ...currentHealth,
619 status: currentHealth.status === "stopped" ? "stopped" : "degraded",
620 lastError:
621 currentHealth.status === "stopped"
622 ? currentHealth.lastError
623 : Option.some(new DesktopTelemetryStale({ fd, staleAfterMs }).message),
624 }));
625 yield* PubSub.publish(changes, staleSnapshot.value);
626 }),
627 ),
628 ),
629 ),
630 ).pipe(Effect.forkScoped);
631 }
632
633 return DesktopTelemetryReceiver.of({
634 latest: Ref.get(latest),
635 changes: Stream.fromPubSub(changes),
636 subscribe: snapshotMutex.withPermits(1)(
637 Effect.gen(function* () {
638 const initial = yield* Ref.get(latest);
639 const subscription = yield* PubSub.subscribe(changes);
640 return {
641 latest: initial,
642 changes: Stream.fromSubscription(subscription),
643 };
644 }),
645 ),
646 health: Ref.get(health),
647 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
648 setDiagnosticsDemand,
649 requestDesktopUpdate: (requestId) =>
650 sendControlMessage({
651 version: 1,
652 type: "requestDesktopUpdate",
653 requestId,
654 }),
655 commitDesktopUpdate: (requestId) =>
656 sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId }),
657 cancelDesktopUpdate: (requestId) =>
658 sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId }),
659 desktopUpdates: Effect.gen(function* () {
660 const subscription = yield* PubSub.subscribe(updateReportChanges);
661 const initial = yield* Ref.get(latestUpdateReport);
662 return {
663 latest: initial,
664 changes: Stream.fromSubscription(subscription),
665 };
666 }),
667 });
668});
669
670export const layer = Layer.effect(DesktopTelemetryReceiver, make());
671
672export const layerTest = (
673 overrides: Partial<DesktopTelemetryReceiver["Service"]> = {},
674): Layer.Layer<DesktopTelemetryReceiver> => {
675 const latest = overrides.latest ?? Effect.succeedNone;
676 const changes = overrides.changes ?? Stream.empty;
677 const health =
678 overrides.health ??
679 Effect.succeed({
680 status: "unavailable" as const,
681 lastSampleAt: Option.none<DateTime.Utc>(),
682 lastError: Option.some("Desktop telemetry test implementation is unavailable."),
683 });
684 return Layer.succeed(
685 DesktopTelemetryReceiver,
686 DesktopTelemetryReceiver.of({
687 latest,
688 changes,
689 subscribe:
690 overrides.subscribe ??
691 latest.pipe(
692 Effect.map((initial) => ({
693 latest: initial,
694 changes,
695 })),
696 ),
697 health,
698 subscribeHealth:
699 overrides.subscribeHealth ??
700 health.pipe(
701 Effect.map((initial) => ({
702 latest: initial,
703 changes: Stream.empty,
704 })),
705 ),
706 setDiagnosticsDemand: () => Effect.void,
707 requestDesktopUpdate: () => Effect.void,
708 commitDesktopUpdate: () => Effect.void,
709 cancelDesktopUpdate: () => Effect.void,
710 desktopUpdates:
711 overrides.desktopUpdates ??
712 Effect.succeed({
713 latest: Option.none<DesktopUpdateStatusReport>(),
714 changes: Stream.empty,
715 }),
716 ...overrides,
717 }),
718 );
719};