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

platform.ts

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