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