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