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

DesktopTelemetryReceiver.ts

711 lines23.6 KB

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