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 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";
73}
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;
97}
98
99// change also fires for same-network bandwidth and latency estimates; count only type changes.
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 // A window left visible beside another app never fires visibilitychange when refocused.
146 Stream.callback<"application-focused">((queue) =>
147 Effect.acquireRelease(
148 Effect.sync(() => {
149 const listener = () => {
150 if (document.visibilityState === "visible") {
151 Queue.offerUnsafe(queue, "application-focused");
152 }
153 };
154 window.addEventListener("focus", listener);
155 return listener;
156 }),
157 (listener) =>
158 Effect.sync(() => {
159 window.removeEventListener("focus", listener);
160 }),
161 ).pipe(Effect.asVoid),
162 ),
163 managedRelayAccountChanges(appAtomRegistry).pipe(
164 Stream.map(() => "credentials-changed" as const),
165 ),
166 networkPathChanges,
167 ],
168 { concurrency: "unbounded" },
169 ),
170});
171
172export function currentClientMetadata() {
173 return clientPresentationMetadata({
174 appVersion: APP_VERSION,
175 hosted: isHostedStaticApp(),
176 identity: {
177 userAgent: navigator.userAgent,
178 platform: navigator.platform,
179 maxTouchPoints: navigator.maxTouchPoints,
180 },
181 desktopBridge: window.desktopBridge,
182 });
183}
184
185function sshPreparationError(cause: unknown) {
186 const message = cause instanceof Error ? cause.message : String(cause);
187 if (message.toLowerCase().includes("cancel")) {
188 return new ConnectionBlockedError({
189 reason: "authentication",
190 detail: message,
191 });
192 }
193 return new ConnectionTransientError({
194 reason: "remote-unavailable",
195 detail: `Could not prepare the SSH environment: ${message}`,
196 });
197}
198
199// IPC keeps running after its waiter is interrupted. A retry can adopt only
200// that interrupted waiter's unfinished setup.
201const pendingSshSetups = new Map<
202 string,
203 { readonly promise: Promise<DesktopSshEnvironmentBootstrap>; signal: AbortSignal }
204>();
205
206const ensureDesktopSshEnvironment = (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) =>
207 Effect.tryPromise({
208 try: (signal) => {
209 const key = sshTargetKey(target);
210 const pending = pendingSshSetups.get(key);
211 if (pending?.signal.aborted) {
212 pending.signal = signal;
213 return pending.promise;
214 }
215 const setup = {
216 promise: bridge.ensureSshEnvironment(target, { issuePairingToken: true }),
217 signal,
218 };
219 pendingSshSetups.set(key, setup);
220 const forget = () => {
221 if (pendingSshSetups.get(key) === setup) pendingSshSetups.delete(key);
222 };
223 setup.promise.then(forget, forget);
224 return setup.promise;
225 },
226 catch: sshPreparationError,
227 });
228
229export const provisionDesktopSshEnvironment = Effect.fn(
230 "web.connectionPlatform.ssh.provisionDesktop",
231)(function* (
232 bridge: DesktopBridge,
233 target: DesktopSshEnvironmentTarget,
234 expectedEnvironmentId?: EnvironmentId,
235) {
236 const bootstrap = yield* ensureDesktopSshEnvironment(bridge, target);
237 const pairingToken = bootstrap.pairingToken;
238 if (pairingToken === null) {
239 return yield* new ConnectionBlockedError({
240 reason: "authentication",
241 detail: "The SSH environment did not issue a pairing credential.",
242 });
243 }
244 const descriptor = yield* Effect.tryPromise({
245 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
246 catch: sshPreparationError,
247 });
248 if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) {
249 return yield* new ConnectionBlockedError({
250 reason: "configuration",
251 detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
252 });
253 }
254 const access = yield* Effect.tryPromise({
255 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
256 catch: (cause) => {
257 const error = sshPreparationError(cause);
258 // A reused remote server on another build can fail to decode the grant
259 // the desktop's runner just minted, and answers 500 on every retry.
260 if (
261 error._tag === "ConnectionBlockedError" ||
262 descriptor.serverVersion === APP_VERSION ||
263 !error.detail.includes("[ssh_http:500]")
264 ) {
265 return error;
266 }
267 return new ConnectionBlockedError({
268 reason: "configuration",
269 detail: `${descriptor.label} runs T3 Code ${descriptor.serverVersion}, but this desktop is ${APP_VERSION}, and that server could not accept its pairing. Restart the T3 server on ${descriptor.label} so it runs ${APP_VERSION}, then retry.`,
270 });
271 },
272 });
273 return {
274 environmentId: descriptor.environmentId,
275 label: descriptor.label,
276 bootstrap,
277 bearerToken: access.access_token,
278 };
279});
280
281/** Reuses SSH pairing tokens with all standard scopes to avoid adding a session on each connection. */
282export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ssh.prepareDesktop")(
283 function* (
284 bridge: DesktopBridge,
285 input: {
286 readonly target: DesktopSshEnvironmentTarget;
287 readonly expectedEnvironmentId: EnvironmentId;
288 readonly bearerToken?: string;
289 },
290 ) {
291 const bearerToken = input.bearerToken;
292 if (bearerToken !== undefined) {
293 const bootstrap = yield* Effect.tryPromise({
294 try: () => bridge.ensureSshEnvironment(input.target, { issuePairingToken: false }),
295 catch: sshPreparationError,
296 });
297 // Check identity before sending saved credentials or pairing.
298 const descriptor = yield* Effect.tryPromise({
299 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
300 catch: sshPreparationError,
301 });
302 if (descriptor.environmentId !== input.expectedEnvironmentId) {
303 return yield* new ConnectionBlockedError({
304 reason: "configuration",
305 detail: `That host reaches ${descriptor.label}, a different machine. Add it as its own environment instead.`,
306 });
307 }
308 const session = yield* Effect.tryPromise({
309 try: () => bridge.fetchSshSessionState(bootstrap.httpBaseUrl, bearerToken),
310 catch: sshPreparationError,
311 });
312 // Stored grants never widen; re-pair tokens missing newer standard scopes.
313 const granted = session.permissions ?? session.scopes ?? [];
314 if (
315 session.authenticated &&
316 AuthStandardClientScopes.every((scope) => granted.includes(scope))
317 ) {
318 return { bootstrap, bearerToken };
319 }
320 }
321 const provisioned = yield* provisionDesktopSshEnvironment(
322 bridge,
323 input.target,
324 input.expectedEnvironmentId,
325 );
326 return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken };
327 },
328);
329
330const ANALYTICS_DEVICE_ID_KEY = "t3code:analytics-device-id";
331
332// Lives as long as this browser profile's site data. Storage can be blocked, which only drops the id.
333const analyticsDevice = {
334 id: Effect.sync(
335 Option.liftThrowable(() => {
336 const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY);
337 if (existing) return existing;
338 const created = randomUUID();
339 window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created);
340 return created;
341 }),
342 ),
343};
344
345const layerCapabilities = Layer.effectContext(
346 Effect.sync(() => {
347 const presentation = ClientCapabilities.ClientPresentation.of({
348 metadata: currentClientMetadata(),
349 });
350 const cloudSession = ClientCapabilities.CloudSession.of({
351 identity: Effect.sync(() =>
352 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
353 ),
354 clerkToken: Effect.gen(function* () {
355 const session = appAtomRegistry.get(managedRelaySessionAtom);
356 if (session === null) {
357 return yield* new ConnectionBlockedError({
358 reason: "authentication",
359 detail: "Sign in to T3 Connect to connect this environment.",
360 });
361 }
362 const token = yield* session.readClerkToken().pipe(
363 Effect.mapError(
364 (error) =>
365 new ConnectionTransientError({
366 reason: "network",
367 detail: error.message,
368 }),
369 ),
370 );
371 if (token === null) {
372 return yield* new ConnectionBlockedError({
373 reason: "authentication",
374 detail: "The T3 Connect session is unavailable.",
375 });
376 }
377 return token;
378 }),
379 });
380 const identity = ClientCapabilities.RelayDeviceIdentity.of({
381 deviceId: Effect.succeedNone,
382 });
383 const primaryAuth = ClientCapabilities.PrimaryEnvironmentAuth.of({
384 bearerToken: Effect.tryPromise({
385 try: readDesktopPrimaryBearerToken,
386 catch: (cause) =>
387 new ConnectionTransientError({
388 reason: "remote-unavailable",
389 detail: `Could not load the desktop primary credential: ${String(cause)}`,
390 }),
391 }).pipe(Effect.map(Option.fromNullishOr)),
392 });
393 const ssh = ClientCapabilities.SshEnvironmentGateway.of({
394 provision: Effect.fn("web.connectionPlatform.ssh.provision")(
395 function* (target, expectedEnvironmentId) {
396 const bridge = window.desktopBridge;
397 if (bridge === undefined) {
398 return yield* new ConnectionBlockedError({
399 reason: "unsupported",
400 detail: "SSH environments are only available in the desktop app.",
401 });
402 }
403 return yield* provisionDesktopSshEnvironment(bridge, target, expectedEnvironmentId);
404 },
405 ),
406 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
407 const bridge = window.desktopBridge;
408 if (bridge === undefined) {
409 return yield* new ConnectionBlockedError({
410 reason: "unsupported",
411 detail: "SSH environments are only available in the desktop app.",
412 });
413 }
414 return yield* prepareDesktopSshEnvironment(bridge, input);
415 }),
416 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
417 const bridge = window.desktopBridge;
418 if (bridge === undefined) {
419 return;
420 }
421 pendingSshSetups.delete(sshTargetKey(target));
422 yield* Effect.tryPromise({
423 try: () => bridge.disconnectSshEnvironment(target),
424 catch: (cause) =>
425 new ConnectionTransientError({
426 reason: "remote-unavailable",
427 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
428 }),
429 });
430 }),
431 });
432
433 return Context.make(ClientCapabilities.CloudSession, cloudSession).pipe(
434 Context.add(ClientCapabilities.AnalyticsDevice, analyticsDevice),
435 Context.add(ClientCapabilities.PrimaryEnvironmentAuth, primaryAuth),
436 Context.add(ClientCapabilities.RelayDeviceIdentity, identity),
437 Context.add(ClientCapabilities.ClientPresentation, presentation),
438 Context.add(ClientCapabilities.SshEnvironmentGateway, ssh),
439 );
440 }),
441);
442
443const loadPrimaryConnectionRegistration = Effect.fn(
444 "web.connectionPlatform.loadPrimaryConnectionRegistration",
445)(function* (resolved: PrimaryEnvironmentTarget) {
446 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
447 httpBaseUrl: resolved.target.httpBaseUrl,
448 }).pipe(
449 Effect.provide(PrimaryEnvironmentHttpLayer.layer),
450 Effect.mapError(mapRemoteEnvironmentError),
451 );
452 return new PrimaryConnectionRegistration({
453 target: new PrimaryConnectionTarget({
454 environmentId: descriptor.environmentId,
455 label: descriptor.label,
456 httpBaseUrl: resolved.target.httpBaseUrl,
457 wsBaseUrl: resolved.target.wsBaseUrl,
458 }),
459 });
460});
461
462const loadSecondaryConnectionRegistration = Effect.fn(
463 "web.connectionPlatform.loadSecondaryConnectionRegistration",
464)(function* (entry: DesktopEnvironmentBootstrap) {
465 if (
466 entry.httpBaseUrl === null ||
467 entry.wsBaseUrl === null ||
468 entry.bootstrapToken === undefined
469 ) {
470 return yield* new ConnectionTransientError({
471 reason: "endpoint-unavailable",
472 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
473 });
474 }
475 const httpBaseUrl = entry.httpBaseUrl;
476 const wsBaseUrl = entry.wsBaseUrl;
477 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
478 Effect.mapError(mapRemoteEnvironmentError),
479 );
480 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
481 const access = yield* bootstrapRemoteBearerSession({
482 httpBaseUrl,
483 credential: entry.bootstrapToken,
484 scopes: AuthStandardClientScopes,
485 clientMetadata: currentClientMetadata(),
486 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
487 // Desktop operations need the pool backend id to reach the owning instance; RPC uses the environment id.
488 const connectionId = desktopLocalConnectionId(entry.id);
489 const label = entry.label || descriptor.label;
490 return {
491 registration: new BearerConnectionRegistration({
492 target: new BearerConnectionTarget({
493 environmentId: descriptor.environmentId,
494 label,
495 connectionId,
496 }),
497 profile: new BearerConnectionProfile({
498 connectionId,
499 environmentId: descriptor.environmentId,
500 label,
501 httpBaseUrl,
502 wsBaseUrl,
503 }),
504 credential: new BearerConnectionCredential({ token: access.access_token }),
505 }),
506 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
507 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
508 };
509});
510
511// The bridge has no topology event. Cache registrations until bearer credentials near expiry.
512const PLATFORM_POLL_INTERVAL = "3 seconds";
513const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
514
515function secondaryBearerExpiresAtEpochMs(
516 issuedAtEpochMs: number,
517 expiresInSeconds: number,
518): number {
519 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
520}
521
522function secondaryBearerRefreshAtEpochMs(
523 issuedAtEpochMs: number,
524 expiresInSeconds: number,
525): number {
526 return Math.max(
527 issuedAtEpochMs,
528 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
529 SECONDARY_BEARER_REFRESH_SKEW_MS,
530 );
531}
532
533interface CachedPlatformRegistration {
534 readonly signature: string;
535 readonly registration: PlatformConnectionRegistration;
536 readonly expiresAtEpochMs?: number;
537 readonly refreshAtEpochMs?: number;
538 readonly bootstrapToken?: string;
539}
540
541export type PrimaryEnvironmentTargetRead =
542 | {
543 readonly _tag: "Success";
544 readonly target: PrimaryEnvironmentTarget | null;
545 }
546 | {
547 readonly _tag: "Failure";
548 readonly cause: unknown;
549 };
550
551function readPrimaryEnvironmentTargetResult(
552 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
553): PrimaryEnvironmentTargetRead {
554 try {
555 return { _tag: "Success", target: readTarget() };
556 } catch (cause) {
557 return { _tag: "Failure", cause };
558 }
559}
560
561export function primaryRegistrationToRetainAfterTopologyRead(
562 previous: ReadonlyMap<string, CachedPlatformRegistration>,
563 topologyRead: PrimaryEnvironmentTargetRead,
564): CachedPlatformRegistration | undefined {
565 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
566}
567
568export function canReuseCachedPlatformRegistration(
569 cached: CachedPlatformRegistration,
570 signature: string,
571 nowEpochMs: number,
572): boolean {
573 return (
574 cached.signature === signature &&
575 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
576 );
577}
578
579export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
580 cached: CachedPlatformRegistration,
581 signature: string,
582 nowEpochMs: number,
583): boolean {
584 return (
585 cached.signature === signature &&
586 cached.expiresAtEpochMs !== undefined &&
587 nowEpochMs < cached.expiresAtEpochMs
588 );
589}
590
591const REJECTED_BOOTSTRAP_RETRY_INITIAL_MS = 60_000;
592const REJECTED_BOOTSTRAP_RETRY_MAX_MS = 30 * 60_000;
593
594export interface RejectedSecondaryBootstrap {
595 readonly signature: string;
596 readonly retryAtEpochMs: number;
597 readonly delayMs: number;
598}
599
600/** Retry with backoff: a backend can restart on the same port with a fresh grant and no topology change. */
601export function isRejectedSecondaryBootstrap(
602 rejected: RejectedSecondaryBootstrap | undefined,
603 signature: string,
604 nowEpochMs: number,
605): rejected is RejectedSecondaryBootstrap {
606 return (
607 rejected !== undefined &&
608 rejected.signature === signature &&
609 nowEpochMs < rejected.retryAtEpochMs
610 );
611}
612
613export function nextRejectedSecondaryBootstrap(
614 previous: RejectedSecondaryBootstrap | undefined,
615 signature: string,
616 nowEpochMs: number,
617): RejectedSecondaryBootstrap {
618 const delayMs =
619 previous?.signature === signature
620 ? Math.min(previous.delayMs * 2, REJECTED_BOOTSTRAP_RETRY_MAX_MS)
621 : REJECTED_BOOTSTRAP_RETRY_INITIAL_MS;
622 return { signature, retryAtEpochMs: nowEpochMs + delayMs, delayMs };
623}
624
625export function isRejectedBootstrapCredentialError(error: ConnectionAttemptError): boolean {
626 return error._tag === "ConnectionBlockedError" && error.reason === "authentication";
627}
628
629export function secondaryRegistrationsToRetainAfterTopologyRead(
630 previous: ReadonlyMap<string, CachedPlatformRegistration>,
631 topologyRead: DesktopSecondaryBootstrapsRead,
632 nowEpochMs: number,
633): ReadonlyMap<string, CachedPlatformRegistration> {
634 if (topologyRead._tag === "Success") {
635 return new Map();
636 }
637 return new Map(
638 [...previous].filter(
639 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
640 ),
641 );
642}
643
644const layerPlatformConnectionSource = Layer.effect(
645 PlatformConnectionSource.PlatformConnectionSource,
646 Effect.gen(function* () {
647 if (isHostedStaticApp() || isLocalEnvironmentDisabled()) {
648 return PlatformConnectionSource.PlatformConnectionSource.of({
649 registrations: Stream.empty,
650 });
651 }
652 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
653 const rejectedRef = yield* Ref.make(new Map<string, RejectedSecondaryBootstrap>());
654
655 const buildPlatformRegistrations = Effect.gen(function* () {
656 const previous = yield* Ref.get(cacheRef);
657 const nowEpochMs = yield* Clock.currentTimeMillis;
658 const next = new Map<string, CachedPlatformRegistration>();
659 const registrations: Array<PlatformConnectionRegistration> = [];
660
661 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
662 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
663 previous,
664 primaryTopologyRead,
665 );
666 if (retainedPrimary !== undefined) {
667 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
668 registrations.push(retainedPrimary.registration);
669 }
670
671 if (primaryTopologyRead._tag === "Failure") {
672 yield* Effect.logWarning("Could not read the primary environment topology.", {
673 cause: primaryTopologyRead.cause,
674 });
675 } else if (primaryTopologyRead.target !== null) {
676 const primaryTarget = primaryTopologyRead.target;
677 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
678 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
679 if (
680 cached !== undefined &&
681 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
682 ) {
683 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
684 registrations.push(cached.registration);
685 } else {
686 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
687 Effect.tapError((error) =>
688 Effect.logWarning("Could not discover the primary environment.", { error }),
689 ),
690 Effect.option,
691 );
692 if (Option.isSome(built)) {
693 const cacheEntry = { signature, registration: built.value };
694 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
695 registrations.push(built.value);
696 }
697 }
698 }
699
700 const topologyRead = readDesktopSecondaryBootstrapsResult();
701 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
702 previous,
703 topologyRead,
704 nowEpochMs,
705 )) {
706 next.set(id, cached);
707 registrations.push(cached.registration);
708 }
709
710 if (topologyRead._tag === "Failure") {
711 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
712 cause: topologyRead.cause,
713 });
714 } else {
715 const rejected = yield* Ref.get(rejectedRef);
716 const nextRejected = new Map<string, RejectedSecondaryBootstrap>();
717 for (const bootstrap of topologyRead.bootstraps) {
718 // Token rotation only controls exchange retries; dropping endpoint bearers also clears drafts.
719 const endpointSignature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}`;
720 const signature = `${endpointSignature}|${bootstrap.bootstrapToken ?? ""}`;
721 const cached = previous.get(bootstrap.id);
722 // Rotation may mean a restart; retain the old bearer if the new exchange fails.
723 if (
724 cached !== undefined &&
725 cached.bootstrapToken === bootstrap.bootstrapToken &&
726 canReuseCachedPlatformRegistration(cached, endpointSignature, nowEpochMs)
727 ) {
728 next.set(bootstrap.id, cached);
729 registrations.push(cached.registration);
730 continue;
731 }
732 const previouslyRejected = rejected.get(bootstrap.id);
733 if (isRejectedSecondaryBootstrap(previouslyRejected, signature, nowEpochMs)) {
734 nextRejected.set(bootstrap.id, previouslyRejected);
735 if (
736 cached !== undefined &&
737 canRetainCachedPlatformRegistrationAfterRefreshFailure(
738 cached,
739 endpointSignature,
740 nowEpochMs,
741 )
742 ) {
743 next.set(bootstrap.id, cached);
744 registrations.push(cached.registration);
745 }
746 continue;
747 }
748 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
749 Effect.tapError((error) =>
750 Effect.logWarning("Could not connect a desktop-local backend.", {
751 id: bootstrap.id,
752 error,
753 }),
754 ),
755 Effect.tapError((error) =>
756 isRejectedBootstrapCredentialError(error)
757 ? // Start backoff at rejection; this poll can outlast the first delay.
758 Clock.currentTimeMillis.pipe(
759 Effect.map((rejectedAtEpochMs) =>
760 nextRejected.set(
761 bootstrap.id,
762 nextRejectedSecondaryBootstrap(
763 previouslyRejected,
764 signature,
765 rejectedAtEpochMs,
766 ),
767 ),
768 ),
769 )
770 : Effect.void,
771 ),
772 Effect.option,
773 );
774 if (Option.isSome(built)) {
775 const cacheEntry = {
776 signature: endpointSignature,
777 ...(bootstrap.bootstrapToken === undefined
778 ? {}
779 : { bootstrapToken: bootstrap.bootstrapToken }),
780 ...built.value,
781 };
782 next.set(bootstrap.id, cacheEntry);
783 registrations.push(built.value.registration);
784 } else if (
785 cached !== undefined &&
786 canRetainCachedPlatformRegistrationAfterRefreshFailure(
787 cached,
788 endpointSignature,
789 nowEpochMs,
790 )
791 ) {
792 next.set(bootstrap.id, cached);
793 registrations.push(cached.registration);
794 }
795 }
796 yield* Ref.set(rejectedRef, nextRejected);
797 }
798
799 yield* Ref.set(cacheRef, next);
800 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
801 }).pipe(Effect.provide(FetchHttpClient.layer));
802
803 return PlatformConnectionSource.PlatformConnectionSource.of({
804 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
805 Stream.mapEffect(() => buildPlatformRegistrations),
806 ),
807 });
808 }),
809);
810
811const layerEnvironmentOwnedDataCleanup = Layer.succeed(
812 Persistence.EnvironmentOwnedDataCleanup,
813 Persistence.EnvironmentOwnedDataCleanup.of({
814 clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) {
815 return Effect.sync(() => {
816 clearComposerDraftsEnvironment(environmentId);
817 });
818 }),
819 }),
820);
821
822const layerRpcRequestObserver = Layer.succeed(
823 EnvironmentRpcRequestObserver,
824 EnvironmentRpcRequestObserver.of({
825 // Every RPC passes through this observer; the request owns its span.
826 observe: Effect.fnUntraced(function* ({ environmentId, environmentLabel, method }) {
827 return yield* Effect.sync(() => {
828 nextObservedRpcRequestId += 1;
829 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
830 trackRpcRequestSent(requestId, method, `${method} · ${environmentLabel}`);
831 return Effect.sync(() => {
832 acknowledgeRpcRequest(requestId);
833 });
834 });
835 }),
836 }),
837);
838
839type ConnectionPlatformLayerSource =
840 | typeof ConnectionStorage.layer
841 | typeof layerConnectivity
842 | typeof layerWakeups
843 | typeof layerCapabilities
844 | typeof layerPlatformConnectionSource
845 | typeof layerEnvironmentOwnedDataCleanup
846 | typeof layerRpcRequestObserver;
847
848export const layer: Layer.Layer<
849 Layer.Success<ConnectionPlatformLayerSource>,
850 Layer.Error<ConnectionPlatformLayerSource>,
851 Layer.Services<ConnectionPlatformLayerSource>
852> = Layer.mergeAll(
853 ConnectionStorage.layer,
854 layerConnectivity,
855 layerWakeups,
856 layerCapabilities,
857 layerPlatformConnectionSource,
858 layerEnvironmentOwnedDataCleanup,
859 layerRpcRequestObserver,
860);