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

platform.ts

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