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