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 * Wakes connections when the browser reports a different network type, such
98 * as a laptop moving from Wi-Fi to a phone hotspot. `change` also fires for
99 * bandwidth and latency estimates on the same network, so only a type change
100 * counts. Browsers without `navigator.connection.type` rely on the periodic
101 * route check instead.
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
184export const provisionDesktopSshEnvironment = Effect.fn(
185 "web.connectionPlatform.ssh.provisionDesktop",
186)(function* (
187 bridge: DesktopBridge,
188 target: DesktopSshEnvironmentTarget,
189 expectedEnvironmentId?: EnvironmentId,
190) {
191 const bootstrap = yield* Effect.tryPromise({
192 try: () =>
193 bridge.ensureSshEnvironment(target, {
194 issuePairingToken: true,
195 }),
196 catch: sshPreparationError,
197 });
198 const pairingToken = bootstrap.pairingToken;
199 if (pairingToken === null) {
200 return yield* new ConnectionBlockedError({
201 reason: "authentication",
202 detail: "The SSH environment did not issue a pairing credential.",
203 });
204 }
205 const descriptor = yield* Effect.tryPromise({
206 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
207 catch: sshPreparationError,
208 });
209 if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) {
210 return yield* new ConnectionBlockedError({
211 reason: "configuration",
212 detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
213 });
214 }
215 const access = yield* Effect.tryPromise({
216 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
217 catch: sshPreparationError,
218 });
219 return {
220 environmentId: descriptor.environmentId,
221 label: descriptor.label,
222 bootstrap,
223 bearerToken: access.access_token,
224 };
225});
226
227const layerCapabilities = Layer.effectContext(
228 Effect.sync(() => {
229 const presentation = ClientCapabilities.ClientPresentation.of({
230 metadata: clientMetadata(),
231 scopes: AuthStandardClientScopes,
232 });
233 const cloudSession = ClientCapabilities.CloudSession.of({
234 identity: Effect.sync(() =>
235 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
236 ),
237 clerkToken: Effect.gen(function* () {
238 const session = appAtomRegistry.get(managedRelaySessionAtom);
239 if (session === null) {
240 return yield* new ConnectionBlockedError({
241 reason: "authentication",
242 detail: "Sign in to T3 Connect to connect this environment.",
243 });
244 }
245 const token = yield* session.readClerkToken().pipe(
246 Effect.mapError(
247 (error) =>
248 new ConnectionTransientError({
249 reason: "network",
250 detail: error.message,
251 }),
252 ),
253 );
254 if (token === null) {
255 return yield* new ConnectionBlockedError({
256 reason: "authentication",
257 detail: "The T3 Connect session is unavailable.",
258 });
259 }
260 return token;
261 }),
262 });
263 const identity = ClientCapabilities.RelayDeviceIdentity.of({
264 deviceId: Effect.succeedNone,
265 });
266 const primaryAuth = ClientCapabilities.PrimaryEnvironmentAuth.of({
267 bearerToken: Effect.tryPromise({
268 try: readDesktopPrimaryBearerToken,
269 catch: (cause) =>
270 new ConnectionTransientError({
271 reason: "remote-unavailable",
272 detail: `Could not load the desktop primary credential: ${String(cause)}`,
273 }),
274 }).pipe(Effect.map(Option.fromNullishOr)),
275 });
276 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
277 provision: Effect.fn("web.connectionPlatform.ssh.provision")(
278 function* (target, expectedEnvironmentId) {
279 const bridge = window.desktopBridge;
280 if (bridge === undefined) {
281 return yield* new ConnectionBlockedError({
282 reason: "unsupported",
283 detail: "SSH environments are only available in the desktop app.",
284 });
285 }
286 return yield* provisionDesktopSshEnvironment(bridge, target, expectedEnvironmentId);
287 },
288 ),
289 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
290 const bridge = window.desktopBridge;
291 if (bridge === undefined) {
292 return yield* new ConnectionBlockedError({
293 reason: "unsupported",
294 detail: "SSH environments are only available in the desktop app.",
295 });
296 }
297 const bootstrap = yield* Effect.tryPromise({
298 try: () =>
299 bridge.ensureSshEnvironment(input.target, {
300 issuePairingToken: true,
301 }),
302 catch: sshPreparationError,
303 });
304 if (bootstrap.pairingToken === null) {
305 return yield* new ConnectionBlockedError({
306 reason: "authentication",
307 detail: "The SSH environment did not issue a pairing credential.",
308 });
309 }
310 const access = yield* Effect.tryPromise({
311 try: () =>
312 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
313 catch: sshPreparationError,
314 });
315 return {
316 bootstrap,
317 bearerToken: access.access_token,
318 };
319 }),
320 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
321 const bridge = window.desktopBridge;
322 if (bridge === undefined) {
323 return;
324 }
325 yield* Effect.tryPromise({
326 try: () => bridge.disconnectSshEnvironment(target),
327 catch: (cause) =>
328 new ConnectionTransientError({
329 reason: "remote-unavailable",
330 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
331 }),
332 });
333 }),
334 });
335
336 return Context.make(ClientCapabilities.CloudSession, cloudSession).pipe(
337 Context.add(ClientCapabilities.PrimaryEnvironmentAuth, primaryAuth),
338 Context.add(ClientCapabilities.RelayDeviceIdentity, identity),
339 Context.add(ClientCapabilities.ClientPresentation, presentation),
340 Context.add(ClientCapabilities.SshEnvironmentGateway, ssh),
341 );
342 }),
343);
344
345const loadPrimaryConnectionRegistration = Effect.fn(
346 "web.connectionPlatform.loadPrimaryConnectionRegistration",
347)(function* (resolved: PrimaryEnvironmentTarget) {
348 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
349 httpBaseUrl: resolved.target.httpBaseUrl,
350 }).pipe(
351 Effect.provide(PrimaryEnvironmentHttpLayer.layer),
352 Effect.mapError(mapRemoteEnvironmentError),
353 );
354 return new PrimaryConnectionRegistration({
355 target: new PrimaryConnectionTarget({
356 environmentId: descriptor.environmentId,
357 label: descriptor.label,
358 httpBaseUrl: resolved.target.httpBaseUrl,
359 wsBaseUrl: resolved.target.wsBaseUrl,
360 }),
361 });
362});
363
364// A desktop-local secondary backend (e.g. a parallel WSL backend) lives on its
365// own loopback origin, so — unlike the same-origin primary — it authenticates
366// with a bearer token minted from the bootstrap credential the desktop issues.
367const loadSecondaryConnectionRegistration = Effect.fn(
368 "web.connectionPlatform.loadSecondaryConnectionRegistration",
369)(function* (entry: DesktopEnvironmentBootstrap) {
370 if (
371 entry.httpBaseUrl === null ||
372 entry.wsBaseUrl === null ||
373 entry.bootstrapToken === undefined
374 ) {
375 return yield* new ConnectionTransientError({
376 reason: "endpoint-unavailable",
377 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
378 });
379 }
380 const httpBaseUrl = entry.httpBaseUrl;
381 const wsBaseUrl = entry.wsBaseUrl;
382 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
383 Effect.mapError(mapRemoteEnvironmentError),
384 );
385 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
386 const access = yield* bootstrapRemoteBearerSession({
387 httpBaseUrl,
388 credential: entry.bootstrapToken,
389 scopes: AuthStandardClientScopes,
390 clientMetadata: clientMetadata(),
391 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
392 // Keep the desktop pool's stable backend id in the connection id. The
393 // descriptor environment id still scopes projects and RPC state, while the
394 // backend id lets desktop-only operations (notably the WSL folder picker)
395 // route back to the instance that owns the environment.
396 const connectionId = desktopLocalConnectionId(entry.id);
397 // Prefer the desktop's bootstrap label (it identifies the backend and distro,
398 // e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
399 // a meaningful name without recovering it from the bootstrap list later.
400 const label = entry.label || descriptor.label;
401 return {
402 registration: new BearerConnectionRegistration({
403 target: new BearerConnectionTarget({
404 environmentId: descriptor.environmentId,
405 label,
406 connectionId,
407 }),
408 profile: new BearerConnectionProfile({
409 connectionId,
410 environmentId: descriptor.environmentId,
411 label,
412 httpBaseUrl,
413 wsBaseUrl,
414 }),
415 credential: new BearerConnectionCredential({ token: access.access_token }),
416 }),
417 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
418 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
419 };
420});
421
422// Poll cadence for the desktop bootstrap topology. There is no change event on
423// the bridge, so the renderer polls; successful registrations are cached by a
424// signature of their endpoint until bearer credentials approach expiry.
425const PLATFORM_POLL_INTERVAL = "3 seconds";
426const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
427
428export function secondaryBearerExpiresAtEpochMs(
429 issuedAtEpochMs: number,
430 expiresInSeconds: number,
431): number {
432 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
433}
434
435export function secondaryBearerRefreshAtEpochMs(
436 issuedAtEpochMs: number,
437 expiresInSeconds: number,
438): number {
439 return Math.max(
440 issuedAtEpochMs,
441 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
442 SECONDARY_BEARER_REFRESH_SKEW_MS,
443 );
444}
445
446interface CachedPlatformRegistration {
447 readonly signature: string;
448 readonly registration: PlatformConnectionRegistration;
449 readonly expiresAtEpochMs?: number;
450 readonly refreshAtEpochMs?: number;
451 /** The bootstrap token a desktop-local bearer was exchanged for. */
452 readonly bootstrapToken?: string;
453}
454
455export type PrimaryEnvironmentTargetRead =
456 | {
457 readonly _tag: "Success";
458 readonly target: PrimaryEnvironmentTarget | null;
459 }
460 | {
461 readonly _tag: "Failure";
462 readonly cause: unknown;
463 };
464
465export function readPrimaryEnvironmentTargetResult(
466 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
467): PrimaryEnvironmentTargetRead {
468 try {
469 return { _tag: "Success", target: readTarget() };
470 } catch (cause) {
471 return { _tag: "Failure", cause };
472 }
473}
474
475export function primaryRegistrationToRetainAfterTopologyRead(
476 previous: ReadonlyMap<string, CachedPlatformRegistration>,
477 topologyRead: PrimaryEnvironmentTargetRead,
478): CachedPlatformRegistration | undefined {
479 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
480}
481
482export function canReuseCachedPlatformRegistration(
483 cached: CachedPlatformRegistration,
484 signature: string,
485 nowEpochMs: number,
486): boolean {
487 return (
488 cached.signature === signature &&
489 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
490 );
491}
492
493export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
494 cached: CachedPlatformRegistration,
495 signature: string,
496 nowEpochMs: number,
497): boolean {
498 return (
499 cached.signature === signature &&
500 cached.expiresAtEpochMs !== undefined &&
501 nowEpochMs < cached.expiresAtEpochMs
502 );
503}
504
505const REJECTED_BOOTSTRAP_RETRY_INITIAL_MS = 60_000;
506const REJECTED_BOOTSTRAP_RETRY_MAX_MS = 30 * 60_000;
507
508/** A bootstrap token a backend rejected, and when the poll may try it again. */
509export interface RejectedSecondaryBootstrap {
510 readonly signature: string;
511 readonly retryAtEpochMs: number;
512 readonly delayMs: number;
513}
514
515/**
516 * A backend that rejected a bootstrap token will usually keep rejecting it, so
517 * the poll backs off on that exact signature instead of re-presenting a dead
518 * credential every few seconds. It still retries on a capped backoff: a
519 * backend that restarts on the same port seeds a fresh grant for the same
520 * token, and nothing in the topology says it restarted. A new token or
521 * endpoint retries at once.
522 */
523export function isRejectedSecondaryBootstrap(
524 rejected: RejectedSecondaryBootstrap | undefined,
525 signature: string,
526 nowEpochMs: number,
527): rejected is RejectedSecondaryBootstrap {
528 return (
529 rejected !== undefined &&
530 rejected.signature === signature &&
531 nowEpochMs < rejected.retryAtEpochMs
532 );
533}
534
535export function nextRejectedSecondaryBootstrap(
536 previous: RejectedSecondaryBootstrap | undefined,
537 signature: string,
538 nowEpochMs: number,
539): RejectedSecondaryBootstrap {
540 const delayMs =
541 previous?.signature === signature
542 ? Math.min(previous.delayMs * 2, REJECTED_BOOTSTRAP_RETRY_MAX_MS)
543 : REJECTED_BOOTSTRAP_RETRY_INITIAL_MS;
544 return { signature, retryAtEpochMs: nowEpochMs + delayMs, delayMs };
545}
546
547export function isRejectedBootstrapCredentialError(error: ConnectionAttemptError): boolean {
548 return error._tag === "ConnectionBlockedError" && error.reason === "authentication";
549}
550
551export function secondaryRegistrationsToRetainAfterTopologyRead(
552 previous: ReadonlyMap<string, CachedPlatformRegistration>,
553 topologyRead: DesktopSecondaryBootstrapsRead,
554 nowEpochMs: number,
555): ReadonlyMap<string, CachedPlatformRegistration> {
556 if (topologyRead._tag === "Success") {
557 return new Map();
558 }
559 return new Map(
560 [...previous].filter(
561 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
562 ),
563 );
564}
565
566const layerPlatformConnectionSource = Layer.effect(
567 PlatformConnectionSource.PlatformConnectionSource,
568 Effect.gen(function* () {
569 if (isHostedStaticApp() || isLocalEnvironmentDisabled()) {
570 return PlatformConnectionSource.PlatformConnectionSource.of({
571 registrations: Stream.empty,
572 });
573 }
574 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
575 const rejectedRef = yield* Ref.make(new Map<string, RejectedSecondaryBootstrap>());
576
577 // Resolve the full set of platform-managed environments the host currently
578 // reports: the primary (same-origin cookie auth) plus any desktop-local
579 // backends running alongside it (bearer auth). Reused registrations come
580 // from the cache; a failed entry is skipped and retried on the next poll.
581 const buildPlatformRegistrations = Effect.gen(function* () {
582 const previous = yield* Ref.get(cacheRef);
583 const nowEpochMs = yield* Clock.currentTimeMillis;
584 const next = new Map<string, CachedPlatformRegistration>();
585 const registrations: Array<PlatformConnectionRegistration> = [];
586
587 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
588 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
589 previous,
590 primaryTopologyRead,
591 );
592 if (retainedPrimary !== undefined) {
593 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
594 registrations.push(retainedPrimary.registration);
595 }
596
597 if (primaryTopologyRead._tag === "Failure") {
598 yield* Effect.logWarning("Could not read the primary environment topology.", {
599 cause: primaryTopologyRead.cause,
600 });
601 } else if (primaryTopologyRead.target !== null) {
602 const primaryTarget = primaryTopologyRead.target;
603 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
604 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
605 if (
606 cached !== undefined &&
607 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
608 ) {
609 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
610 registrations.push(cached.registration);
611 } else {
612 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
613 Effect.tapError((error) =>
614 Effect.logWarning("Could not discover the primary environment.", { error }),
615 ),
616 Effect.option,
617 );
618 if (Option.isSome(built)) {
619 const cacheEntry = { signature, registration: built.value };
620 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
621 registrations.push(built.value);
622 }
623 }
624 }
625
626 const topologyRead = readDesktopSecondaryBootstrapsResult();
627 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
628 previous,
629 topologyRead,
630 nowEpochMs,
631 )) {
632 next.set(id, cached);
633 registrations.push(cached.registration);
634 }
635
636 if (topologyRead._tag === "Failure") {
637 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
638 cause: topologyRead.cause,
639 });
640 } else {
641 const rejected = yield* Ref.get(rejectedRef);
642 const nextRejected = new Map<string, RejectedSecondaryBootstrap>();
643 for (const bootstrap of topologyRead.bootstraps) {
644 // The cached bearer belongs to the endpoint, not to the bootstrap
645 // token it was exchanged for: a new token must not drop a live
646 // session (its removal also clears the environment's drafts). The
647 // token only decides whether a rejected exchange is retried.
648 const endpointSignature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}`;
649 const signature = `${endpointSignature}|${bootstrap.bootstrapToken ?? ""}`;
650 const cached = previous.get(bootstrap.id);
651 // A new token from the desktop means something changed (rotation, a
652 // restarted backend): exchange it rather than reusing a bearer that
653 // may be dead. The old bearer stays registered if that exchange fails.
654 if (
655 cached !== undefined &&
656 cached.bootstrapToken === bootstrap.bootstrapToken &&
657 canReuseCachedPlatformRegistration(cached, endpointSignature, nowEpochMs)
658 ) {
659 next.set(bootstrap.id, cached);
660 registrations.push(cached.registration);
661 continue;
662 }
663 const previouslyRejected = rejected.get(bootstrap.id);
664 if (isRejectedSecondaryBootstrap(previouslyRejected, signature, nowEpochMs)) {
665 nextRejected.set(bootstrap.id, previouslyRejected);
666 // The bearer minted before the token died is still good until it expires.
667 if (
668 cached !== undefined &&
669 canRetainCachedPlatformRegistrationAfterRefreshFailure(
670 cached,
671 endpointSignature,
672 nowEpochMs,
673 )
674 ) {
675 next.set(bootstrap.id, cached);
676 registrations.push(cached.registration);
677 }
678 continue;
679 }
680 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
681 Effect.tapError((error) =>
682 Effect.logWarning("Could not connect a desktop-local backend.", {
683 id: bootstrap.id,
684 error,
685 }),
686 ),
687 Effect.tapError((error) =>
688 isRejectedBootstrapCredentialError(error)
689 ? // Back off from when the rejection arrived; the exchanges in
690 // this poll can take longer than the first backoff step.
691 Clock.currentTimeMillis.pipe(
692 Effect.map((rejectedAtEpochMs) =>
693 nextRejected.set(
694 bootstrap.id,
695 nextRejectedSecondaryBootstrap(
696 previouslyRejected,
697 signature,
698 rejectedAtEpochMs,
699 ),
700 ),
701 ),
702 )
703 : Effect.void,
704 ),
705 Effect.option,
706 );
707 if (Option.isSome(built)) {
708 const cacheEntry = {
709 signature: endpointSignature,
710 ...(bootstrap.bootstrapToken === undefined
711 ? {}
712 : { bootstrapToken: bootstrap.bootstrapToken }),
713 ...built.value,
714 };
715 next.set(bootstrap.id, cacheEntry);
716 registrations.push(built.value.registration);
717 } else if (
718 cached !== undefined &&
719 canRetainCachedPlatformRegistrationAfterRefreshFailure(
720 cached,
721 endpointSignature,
722 nowEpochMs,
723 )
724 ) {
725 next.set(bootstrap.id, cached);
726 registrations.push(cached.registration);
727 }
728 }
729 yield* Ref.set(rejectedRef, nextRejected);
730 }
731
732 yield* Ref.set(cacheRef, next);
733 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
734 }).pipe(Effect.provide(FetchHttpClient.layer));
735
736 return PlatformConnectionSource.PlatformConnectionSource.of({
737 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
738 Stream.mapEffect(() => buildPlatformRegistrations),
739 ),
740 });
741 }),
742);
743
744const layerEnvironmentOwnedDataCleanup = Layer.succeed(
745 Persistence.EnvironmentOwnedDataCleanup,
746 Persistence.EnvironmentOwnedDataCleanup.of({
747 clear: (environmentId) =>
748 Effect.sync(() => {
749 clearComposerDraftsEnvironment(environmentId);
750 }),
751 }),
752);
753
754const layerRpcRequestObserver = Layer.succeed(
755 EnvironmentRpcRequestObserver,
756 EnvironmentRpcRequestObserver.of({
757 observe: ({ environmentId, method }) =>
758 Effect.sync(() => {
759 nextObservedRpcRequestId += 1;
760 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
761 trackRpcRequestSent(requestId, method, `${method} · ${environmentId}`);
762 return Effect.sync(() => {
763 acknowledgeRpcRequest(requestId);
764 });
765 }),
766 }),
767);
768
769type ConnectionPlatformLayerSource =
770 | typeof ConnectionStorage.layer
771 | typeof layerConnectivity
772 | typeof layerWakeups
773 | typeof layerCapabilities
774 | typeof layerPlatformConnectionSource
775 | typeof layerEnvironmentOwnedDataCleanup
776 | typeof layerRpcRequestObserver;
777
778export const layer: Layer.Layer<
779 Layer.Success<ConnectionPlatformLayerSource>,
780 Layer.Error<ConnectionPlatformLayerSource>,
781 Layer.Services<ConnectionPlatformLayerSource>
782> = Layer.mergeAll(
783 ConnectionStorage.layer,
784 layerConnectivity,
785 layerWakeups,
786 layerCapabilities,
787 layerPlatformConnectionSource,
788 layerEnvironmentOwnedDataCleanup,
789 layerRpcRequestObserver,
790);