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

platform.ts

945 lines32.9 KB

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