Open History to see the last commit
1import {
2 ClientCapabilities,
3 PlatformConnectionSource,
4 Persistence,
5} from "@t3tools/client-runtime/platform";
6import {
7 BearerConnectionCredential,
8 BearerConnectionProfile,
9 BearerConnectionRegistration,
10 BearerConnectionTarget,
11 ConnectionBlockedError,
12 type ConnectionAttemptError,
13 ConnectionTransientError,
14 Connectivity,
15 mapRemoteEnvironmentError,
16 type PlatformConnectionRegistration,
17 PrimaryConnectionRegistration,
18 PrimaryConnectionTarget,
19 Wakeups,
20} from "@t3tools/client-runtime/connection";
21import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
22import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
23import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
24import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
25import {
26 AuthStandardClientScopes,
27 type DesktopBridge,
28 type DesktopEnvironmentBootstrap,
29 type DesktopSshEnvironmentTarget,
30 type EnvironmentId,
31 PRIMARY_LOCAL_ENVIRONMENT_ID,
32} from "@t3tools/contracts";
33import * as Clock from "effect/Clock";
34import * as Context from "effect/Context";
35import * as Effect from "effect/Effect";
36import * as Layer from "effect/Layer";
37import * as Option from "effect/Option";
38import * as Queue from "effect/Queue";
39import * as Ref from "effect/Ref";
40import * as Stream from "effect/Stream";
41import { FetchHttpClient } from "effect/http";
42
43import { APP_VERSION } from "../branding";
44import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
45import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";
46import {
47 readPrimaryEnvironmentTarget,
48 type PrimaryEnvironmentTarget,
49} from "../environments/primary/target";
50import { clearComposerDraftsEnvironment } from "../composerDraftStore";
51import { isHostedStaticApp } from "../hostedPairing";
52import { isLocalEnvironmentDisabled } from "../localEnvironment";
53import { appAtomRegistry } from "../rpc/atomRegistry";
54import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
55import {
56 desktopLocalConnectionId,
57 readDesktopSecondaryBootstrapsResult,
58 type DesktopSecondaryBootstrapsRead,
59} from "./desktopLocal";
60import * as ConnectionStorage from "./storage";
61import { clientPresentationMetadata } from "./clientMetadata";
62
63let nextObservedRpcRequestId = 0;
64
65function currentNetworkStatus(): "unknown" | "offline" | "online" {
66 if (typeof navigator === "undefined") {
67 return "unknown";
68 }
69 return navigator.onLine ? "online" : "offline";
70}
71
72const layerConnectivity = Connectivity.layer({
73 status: Effect.sync(currentNetworkStatus),
74 changes: Stream.callback((queue) =>
75 Effect.acquireRelease(
76 Effect.sync(() => {
77 const online = () => Queue.offerUnsafe(queue, "online");
78 const offline = () => Queue.offerUnsafe(queue, "offline");
79 window.addEventListener("online", online);
80 window.addEventListener("offline", offline);
81 return { online, offline };
82 }),
83 ({ online, offline }) =>
84 Effect.sync(() => {
85 window.removeEventListener("online", online);
86 window.removeEventListener("offline", offline);
87 }),
88 ).pipe(Effect.asVoid),
89 ),
90});
91
92interface NetworkInformationLike extends EventTarget {
93 readonly type?: string;
94}
95
96/**
97 * `change` also fires for bandwidth and latency estimates on the same network,
98 * so only a type change counts.
99 */
100const networkPathChanges = Stream.callback<"network-changed">((queue) =>
101 Effect.acquireRelease(
102 Effect.sync(() => {
103 const connection =
104 typeof navigator === "undefined"
105 ? undefined
106 : (navigator as Navigator & { readonly connection?: NetworkInformationLike }).connection;
107 if (connection?.type === undefined) return undefined;
108 let previous = connection.type;
109 const listener = () => {
110 const type = connection.type;
111 if (type === undefined || type === previous) return;
112 previous = type;
113 Queue.offerUnsafe(queue, "network-changed");
114 };
115 connection.addEventListener("change", listener);
116 return { connection, listener };
117 }),
118 (subscription) =>
119 Effect.sync(() =>
120 subscription?.connection.removeEventListener("change", subscription.listener),
121 ),
122 ).pipe(Effect.asVoid),
123);
124
125const layerWakeups = Wakeups.layer({
126 changes: Stream.mergeAll(
127 [
128 Stream.callback<"application-active">((queue) =>
129 Effect.acquireRelease(
130 Effect.sync(() => {
131 const listener = () => {
132 if (document.visibilityState === "visible") {
133 Queue.offerUnsafe(queue, "application-active");
134 }
135 };
136 document.addEventListener("visibilitychange", listener);
137 return listener;
138 }),
139 (listener) =>
140 Effect.sync(() => {
141 document.removeEventListener("visibilitychange", listener);
142 }),
143 ).pipe(Effect.asVoid),
144 ),
145 managedRelayAccountChanges(appAtomRegistry).pipe(
146 Stream.map(() => "credentials-changed" as const),
147 ),
148 networkPathChanges,
149 ],
150 { concurrency: "unbounded" },
151 ),
152});
153
154function clientMetadata() {
155 return clientPresentationMetadata({
156 appVersion: APP_VERSION,
157 hosted: isHostedStaticApp(),
158 identity: {
159 userAgent: navigator.userAgent,
160 platform: navigator.platform,
161 maxTouchPoints: navigator.maxTouchPoints,
162 },
163 desktopBridge: window.desktopBridge,
164 });
165}
166
167function sshPreparationError(cause: unknown) {
168 const message = cause instanceof Error ? cause.message : String(cause);
169 if (message.toLowerCase().includes("cancel")) {
170 return new ConnectionBlockedError({
171 reason: "authentication",
172 detail: message,
173 });
174 }
175 return new ConnectionTransientError({
176 reason: "remote-unavailable",
177 detail: `Could not prepare the SSH environment: ${message}`,
178 });
179}
180
181export const provisionDesktopSshEnvironment = Effect.fn(
182 "web.connectionPlatform.ssh.provisionDesktop",
183)(function* (
184 bridge: DesktopBridge,
185 target: DesktopSshEnvironmentTarget,
186 expectedEnvironmentId?: EnvironmentId,
187) {
188 const bootstrap = yield* Effect.tryPromise({
189 try: () =>
190 bridge.ensureSshEnvironment(target, {
191 issuePairingToken: true,
192 }),
193 catch: sshPreparationError,
194 });
195 const pairingToken = bootstrap.pairingToken;
196 if (pairingToken === null) {
197 return yield* new ConnectionBlockedError({
198 reason: "authentication",
199 detail: "The SSH environment did not issue a pairing credential.",
200 });
201 }
202 const descriptor = yield* Effect.tryPromise({
203 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
204 catch: sshPreparationError,
205 });
206 if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) {
207 return yield* new ConnectionBlockedError({
208 reason: "configuration",
209 detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
210 });
211 }
212 const access = yield* Effect.tryPromise({
213 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
214 catch: sshPreparationError,
215 });
216 return {
217 environmentId: descriptor.environmentId,
218 label: descriptor.label,
219 bootstrap,
220 bearerToken: access.access_token,
221 };
222});
223
224const layerCapabilities = Layer.effectContext(
225 Effect.sync(() => {
226 const presentation = ClientCapabilities.ClientPresentation.of({
227 metadata: clientMetadata(),
228 });
229 const cloudSession = ClientCapabilities.CloudSession.of({
230 identity: Effect.sync(() =>
231 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
232 ),
233 clerkToken: Effect.gen(function* () {
234 const session = appAtomRegistry.get(managedRelaySessionAtom);
235 if (session === null) {
236 return yield* new ConnectionBlockedError({
237 reason: "authentication",
238 detail: "Sign in to T3 Connect to connect this environment.",
239 });
240 }
241 const token = yield* session.readClerkToken().pipe(
242 Effect.mapError(
243 (error) =>
244 new ConnectionTransientError({
245 reason: "network",
246 detail: error.message,
247 }),
248 ),
249 );
250 if (token === null) {
251 return yield* new ConnectionBlockedError({
252 reason: "authentication",
253 detail: "The T3 Connect session is unavailable.",
254 });
255 }
256 return token;
257 }),
258 });
259 const identity = ClientCapabilities.RelayDeviceIdentity.of({
260 deviceId: Effect.succeedNone,
261 });
262 const primaryAuth = ClientCapabilities.PrimaryEnvironmentAuth.of({
263 bearerToken: Effect.tryPromise({
264 try: readDesktopPrimaryBearerToken,
265 catch: (cause) =>
266 new ConnectionTransientError({
267 reason: "remote-unavailable",
268 detail: `Could not load the desktop primary credential: ${String(cause)}`,
269 }),
270 }).pipe(Effect.map(Option.fromNullishOr)),
271 });
272 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
273 provision: Effect.fn("web.connectionPlatform.ssh.provision")(
274 function* (target, expectedEnvironmentId) {
275 const bridge = window.desktopBridge;
276 if (bridge === undefined) {
277 return yield* new ConnectionBlockedError({
278 reason: "unsupported",
279 detail: "SSH environments are only available in the desktop app.",
280 });
281 }
282 return yield* provisionDesktopSshEnvironment(bridge, target, expectedEnvironmentId);
283 },
284 ),
285 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
286 const bridge = window.desktopBridge;
287 if (bridge === undefined) {
288 return yield* new ConnectionBlockedError({
289 reason: "unsupported",
290 detail: "SSH environments are only available in the desktop app.",
291 });
292 }
293 const bootstrap = yield* Effect.tryPromise({
294 try: () =>
295 bridge.ensureSshEnvironment(input.target, {
296 issuePairingToken: true,
297 }),
298 catch: sshPreparationError,
299 });
300 if (bootstrap.pairingToken === null) {
301 return yield* new ConnectionBlockedError({
302 reason: "authentication",
303 detail: "The SSH environment did not issue a pairing credential.",
304 });
305 }
306 const access = yield* Effect.tryPromise({
307 try: () =>
308 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
309 catch: sshPreparationError,
310 });
311 return {
312 bootstrap,
313 bearerToken: access.access_token,
314 };
315 }),
316 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
317 const bridge = window.desktopBridge;
318 if (bridge === undefined) {
319 return;
320 }
321 yield* Effect.tryPromise({
322 try: () => bridge.disconnectSshEnvironment(target),
323 catch: (cause) =>
324 new ConnectionTransientError({
325 reason: "remote-unavailable",
326 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
327 }),
328 });
329 }),
330 });
331
332 return Context.make(ClientCapabilities.CloudSession, cloudSession).pipe(
333 Context.add(ClientCapabilities.PrimaryEnvironmentAuth, primaryAuth),
334 Context.add(ClientCapabilities.RelayDeviceIdentity, identity),
335 Context.add(ClientCapabilities.ClientPresentation, presentation),
336 Context.add(ClientCapabilities.SshEnvironmentGateway, ssh),
337 );
338 }),
339);
340
341const loadPrimaryConnectionRegistration = Effect.fn(
342 "web.connectionPlatform.loadPrimaryConnectionRegistration",
343)(function* (resolved: PrimaryEnvironmentTarget) {
344 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
345 httpBaseUrl: resolved.target.httpBaseUrl,
346 }).pipe(
347 Effect.provide(PrimaryEnvironmentHttpLayer.layer),
348 Effect.mapError(mapRemoteEnvironmentError),
349 );
350 return new PrimaryConnectionRegistration({
351 target: new PrimaryConnectionTarget({
352 environmentId: descriptor.environmentId,
353 label: descriptor.label,
354 httpBaseUrl: resolved.target.httpBaseUrl,
355 wsBaseUrl: resolved.target.wsBaseUrl,
356 }),
357 });
358});
359
360const loadSecondaryConnectionRegistration = Effect.fn(
361 "web.connectionPlatform.loadSecondaryConnectionRegistration",
362)(function* (entry: DesktopEnvironmentBootstrap) {
363 if (
364 entry.httpBaseUrl === null ||
365 entry.wsBaseUrl === null ||
366 entry.bootstrapToken === undefined
367 ) {
368 return yield* new ConnectionTransientError({
369 reason: "endpoint-unavailable",
370 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
371 });
372 }
373 const httpBaseUrl = entry.httpBaseUrl;
374 const wsBaseUrl = entry.wsBaseUrl;
375 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
376 Effect.mapError(mapRemoteEnvironmentError),
377 );
378 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
379 const access = yield* bootstrapRemoteBearerSession({
380 httpBaseUrl,
381 credential: entry.bootstrapToken,
382 scopes: AuthStandardClientScopes,
383 clientMetadata: clientMetadata(),
384 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
385 // Keep the desktop pool's stable backend id in the connection id. The
386 // descriptor environment id still scopes projects and RPC state, while the
387 // backend id lets desktop-only operations (notably the WSL folder picker)
388 // route back to the instance that owns the environment.
389 const connectionId = desktopLocalConnectionId(entry.id);
390 const label = entry.label || descriptor.label;
391 return {
392 registration: new BearerConnectionRegistration({
393 target: new BearerConnectionTarget({
394 environmentId: descriptor.environmentId,
395 label,
396 connectionId,
397 }),
398 profile: new BearerConnectionProfile({
399 connectionId,
400 environmentId: descriptor.environmentId,
401 label,
402 httpBaseUrl,
403 wsBaseUrl,
404 }),
405 credential: new BearerConnectionCredential({ token: access.access_token }),
406 }),
407 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
408 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
409 };
410});
411
412// Poll cadence for the desktop bootstrap topology. There is no change event on
413// the bridge, so the renderer polls; successful registrations are cached by a
414// signature of their endpoint until bearer credentials approach expiry.
415const PLATFORM_POLL_INTERVAL = "3 seconds";
416const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
417
418export function secondaryBearerExpiresAtEpochMs(
419 issuedAtEpochMs: number,
420 expiresInSeconds: number,
421): number {
422 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
423}
424
425export function secondaryBearerRefreshAtEpochMs(
426 issuedAtEpochMs: number,
427 expiresInSeconds: number,
428): number {
429 return Math.max(
430 issuedAtEpochMs,
431 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
432 SECONDARY_BEARER_REFRESH_SKEW_MS,
433 );
434}
435
436interface CachedPlatformRegistration {
437 readonly signature: string;
438 readonly registration: PlatformConnectionRegistration;
439 readonly expiresAtEpochMs?: number;
440 readonly refreshAtEpochMs?: number;
441 readonly bootstrapToken?: string;
442}
443
444export type PrimaryEnvironmentTargetRead =
445 | {
446 readonly _tag: "Success";
447 readonly target: PrimaryEnvironmentTarget | null;
448 }
449 | {
450 readonly _tag: "Failure";
451 readonly cause: unknown;
452 };
453
454export function readPrimaryEnvironmentTargetResult(
455 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
456): PrimaryEnvironmentTargetRead {
457 try {
458 return { _tag: "Success", target: readTarget() };
459 } catch (cause) {
460 return { _tag: "Failure", cause };
461 }
462}
463
464export function primaryRegistrationToRetainAfterTopologyRead(
465 previous: ReadonlyMap<string, CachedPlatformRegistration>,
466 topologyRead: PrimaryEnvironmentTargetRead,
467): CachedPlatformRegistration | undefined {
468 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
469}
470
471export function canReuseCachedPlatformRegistration(
472 cached: CachedPlatformRegistration,
473 signature: string,
474 nowEpochMs: number,
475): boolean {
476 return (
477 cached.signature === signature &&
478 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
479 );
480}
481
482export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
483 cached: CachedPlatformRegistration,
484 signature: string,
485 nowEpochMs: number,
486): boolean {
487 return (
488 cached.signature === signature &&
489 cached.expiresAtEpochMs !== undefined &&
490 nowEpochMs < cached.expiresAtEpochMs
491 );
492}
493
494const REJECTED_BOOTSTRAP_RETRY_INITIAL_MS = 60_000;
495const REJECTED_BOOTSTRAP_RETRY_MAX_MS = 30 * 60_000;
496
497export interface RejectedSecondaryBootstrap {
498 readonly signature: string;
499 readonly retryAtEpochMs: number;
500 readonly delayMs: number;
501}
502
503/**
504 * A backend that rejected a bootstrap token will usually keep rejecting it, so
505 * the poll backs off on that exact signature instead of re-presenting a dead
506 * credential every few seconds. It still retries on a capped backoff: a backend
507 * that restarts on the same port seeds a fresh grant for the same token, and
508 * nothing in the topology says it restarted.
509 */
510export function isRejectedSecondaryBootstrap(
511 rejected: RejectedSecondaryBootstrap | undefined,
512 signature: string,
513 nowEpochMs: number,
514): rejected is RejectedSecondaryBootstrap {
515 return (
516 rejected !== undefined &&
517 rejected.signature === signature &&
518 nowEpochMs < rejected.retryAtEpochMs
519 );
520}
521
522export function nextRejectedSecondaryBootstrap(
523 previous: RejectedSecondaryBootstrap | undefined,
524 signature: string,
525 nowEpochMs: number,
526): RejectedSecondaryBootstrap {
527 const delayMs =
528 previous?.signature === signature
529 ? Math.min(previous.delayMs * 2, REJECTED_BOOTSTRAP_RETRY_MAX_MS)
530 : REJECTED_BOOTSTRAP_RETRY_INITIAL_MS;
531 return { signature, retryAtEpochMs: nowEpochMs + delayMs, delayMs };
532}
533
534export function isRejectedBootstrapCredentialError(error: ConnectionAttemptError): boolean {
535 return error._tag === "ConnectionBlockedError" && error.reason === "authentication";
536}
537
538export function secondaryRegistrationsToRetainAfterTopologyRead(
539 previous: ReadonlyMap<string, CachedPlatformRegistration>,
540 topologyRead: DesktopSecondaryBootstrapsRead,
541 nowEpochMs: number,
542): ReadonlyMap<string, CachedPlatformRegistration> {
543 if (topologyRead._tag === "Success") {
544 return new Map();
545 }
546 return new Map(
547 [...previous].filter(
548 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
549 ),
550 );
551}
552
553const layerPlatformConnectionSource = Layer.effect(
554 PlatformConnectionSource.PlatformConnectionSource,
555 Effect.gen(function* () {
556 if (isHostedStaticApp() || isLocalEnvironmentDisabled()) {
557 return PlatformConnectionSource.PlatformConnectionSource.of({
558 registrations: Stream.empty,
559 });
560 }
561 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
562 const rejectedRef = yield* Ref.make(new Map<string, RejectedSecondaryBootstrap>());
563
564 const buildPlatformRegistrations = Effect.gen(function* () {
565 const previous = yield* Ref.get(cacheRef);
566 const nowEpochMs = yield* Clock.currentTimeMillis;
567 const next = new Map<string, CachedPlatformRegistration>();
568 const registrations: Array<PlatformConnectionRegistration> = [];
569
570 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
571 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
572 previous,
573 primaryTopologyRead,
574 );
575 if (retainedPrimary !== undefined) {
576 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
577 registrations.push(retainedPrimary.registration);
578 }
579
580 if (primaryTopologyRead._tag === "Failure") {
581 yield* Effect.logWarning("Could not read the primary environment topology.", {
582 cause: primaryTopologyRead.cause,
583 });
584 } else if (primaryTopologyRead.target !== null) {
585 const primaryTarget = primaryTopologyRead.target;
586 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
587 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
588 if (
589 cached !== undefined &&
590 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
591 ) {
592 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
593 registrations.push(cached.registration);
594 } else {
595 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
596 Effect.tapError((error) =>
597 Effect.logWarning("Could not discover the primary environment.", { error }),
598 ),
599 Effect.option,
600 );
601 if (Option.isSome(built)) {
602 const cacheEntry = { signature, registration: built.value };
603 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
604 registrations.push(built.value);
605 }
606 }
607 }
608
609 const topologyRead = readDesktopSecondaryBootstrapsResult();
610 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
611 previous,
612 topologyRead,
613 nowEpochMs,
614 )) {
615 next.set(id, cached);
616 registrations.push(cached.registration);
617 }
618
619 if (topologyRead._tag === "Failure") {
620 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
621 cause: topologyRead.cause,
622 });
623 } else {
624 const rejected = yield* Ref.get(rejectedRef);
625 const nextRejected = new Map<string, RejectedSecondaryBootstrap>();
626 for (const bootstrap of topologyRead.bootstraps) {
627 // The cached bearer belongs to the endpoint, not to the bootstrap
628 // token it was exchanged for: a new token must not drop a live
629 // session (its removal also clears the environment's drafts). The
630 // token only decides whether a rejected exchange is retried.
631 const endpointSignature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}`;
632 const signature = `${endpointSignature}|${bootstrap.bootstrapToken ?? ""}`;
633 const cached = previous.get(bootstrap.id);
634 // A new token from the desktop means something changed (rotation, a
635 // restarted backend): exchange it rather than reusing a bearer that
636 // may be dead. The old bearer stays registered if that exchange fails.
637 if (
638 cached !== undefined &&
639 cached.bootstrapToken === bootstrap.bootstrapToken &&
640 canReuseCachedPlatformRegistration(cached, endpointSignature, nowEpochMs)
641 ) {
642 next.set(bootstrap.id, cached);
643 registrations.push(cached.registration);
644 continue;
645 }
646 const previouslyRejected = rejected.get(bootstrap.id);
647 if (isRejectedSecondaryBootstrap(previouslyRejected, signature, nowEpochMs)) {
648 nextRejected.set(bootstrap.id, previouslyRejected);
649 if (
650 cached !== undefined &&
651 canRetainCachedPlatformRegistrationAfterRefreshFailure(
652 cached,
653 endpointSignature,
654 nowEpochMs,
655 )
656 ) {
657 next.set(bootstrap.id, cached);
658 registrations.push(cached.registration);
659 }
660 continue;
661 }
662 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
663 Effect.tapError((error) =>
664 Effect.logWarning("Could not connect a desktop-local backend.", {
665 id: bootstrap.id,
666 error,
667 }),
668 ),
669 Effect.tapError((error) =>
670 isRejectedBootstrapCredentialError(error)
671 ? // Back off from when the rejection arrived; the exchanges in
672 // this poll can take longer than the first backoff step.
673 Clock.currentTimeMillis.pipe(
674 Effect.map((rejectedAtEpochMs) =>
675 nextRejected.set(
676 bootstrap.id,
677 nextRejectedSecondaryBootstrap(
678 previouslyRejected,
679 signature,
680 rejectedAtEpochMs,
681 ),
682 ),
683 ),
684 )
685 : Effect.void,
686 ),
687 Effect.option,
688 );
689 if (Option.isSome(built)) {
690 const cacheEntry = {
691 signature: endpointSignature,
692 ...(bootstrap.bootstrapToken === undefined
693 ? {}
694 : { bootstrapToken: bootstrap.bootstrapToken }),
695 ...built.value,
696 };
697 next.set(bootstrap.id, cacheEntry);
698 registrations.push(built.value.registration);
699 } else if (
700 cached !== undefined &&
701 canRetainCachedPlatformRegistrationAfterRefreshFailure(
702 cached,
703 endpointSignature,
704 nowEpochMs,
705 )
706 ) {
707 next.set(bootstrap.id, cached);
708 registrations.push(cached.registration);
709 }
710 }
711 yield* Ref.set(rejectedRef, nextRejected);
712 }
713
714 yield* Ref.set(cacheRef, next);
715 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
716 }).pipe(Effect.provide(FetchHttpClient.layer));
717
718 return PlatformConnectionSource.PlatformConnectionSource.of({
719 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
720 Stream.mapEffect(() => buildPlatformRegistrations),
721 ),
722 });
723 }),
724);
725
726const layerEnvironmentOwnedDataCleanup = Layer.succeed(
727 Persistence.EnvironmentOwnedDataCleanup,
728 Persistence.EnvironmentOwnedDataCleanup.of({
729 clear: (environmentId) =>
730 Effect.sync(() => {
731 clearComposerDraftsEnvironment(environmentId);
732 }),
733 }),
734);
735
736const layerRpcRequestObserver = Layer.succeed(
737 EnvironmentRpcRequestObserver,
738 EnvironmentRpcRequestObserver.of({
739 observe: ({ environmentId, method }) =>
740 Effect.sync(() => {
741 nextObservedRpcRequestId += 1;
742 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
743 trackRpcRequestSent(requestId, method, `${method} · ${environmentId}`);
744 return Effect.sync(() => {
745 acknowledgeRpcRequest(requestId);
746 });
747 }),
748 }),
749);
750
751type ConnectionPlatformLayerSource =
752 | typeof ConnectionStorage.layer
753 | typeof layerConnectivity
754 | typeof layerWakeups
755 | typeof layerCapabilities
756 | typeof layerPlatformConnectionSource
757 | typeof layerEnvironmentOwnedDataCleanup
758 | typeof layerRpcRequestObserver;
759
760export const layer: Layer.Layer<
761 Layer.Success<ConnectionPlatformLayerSource>,
762 Layer.Error<ConnectionPlatformLayerSource>,
763 Layer.Services<ConnectionPlatformLayerSource>
764> = Layer.mergeAll(
765 ConnectionStorage.layer,
766 layerConnectivity,
767 layerWakeups,
768 layerCapabilities,
769 layerPlatformConnectionSource,
770 layerEnvironmentOwnedDataCleanup,
771 layerRpcRequestObserver,
772);