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

platform.ts

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