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

platform.ts

837 lines29.5 KB

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