Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

platform.ts

791 lines28.4 KB

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