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

platform.ts

630 lines21.8 KB

1import {
2 ClientPresentation,
3 CloudSession,
4 EnvironmentOwnedDataCleanup,
5 PlatformConnectionSource,
6 PrimaryEnvironmentAuth,
7 RelayDeviceIdentity,
8 SshEnvironmentGateway,
9} from "@t3tools/client-runtime/platform";
10import {
11 BearerConnectionCredential,
12 BearerConnectionProfile,
13 BearerConnectionRegistration,
14 BearerConnectionTarget,
15 ConnectionBlockedError,
16 ConnectionTransientError,
17 Connectivity,
18 mapRemoteEnvironmentError,
19 type PlatformConnectionRegistration,
20 PrimaryConnectionRegistration,
21 PrimaryConnectionTarget,
22 Wakeups,
23} from "@t3tools/client-runtime/connection";
24import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
25import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
26import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
27import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
28import {
29 AuthStandardClientScopes,
30 type DesktopBridge,
31 type DesktopEnvironmentBootstrap,
32 type DesktopSshEnvironmentTarget,
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/unstable/http";
44​
45import { APP_VERSION } from "../branding";
46import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
47import { 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 { appAtomRegistry } from "../rpc/atomRegistry";
55import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
56import {
57 desktopLocalConnectionId,
58 readDesktopSecondaryBootstrapsResult,
59 type DesktopSecondaryBootstrapsRead,
60} from "./desktopLocal";
61import { connectionStorageLayer } from "./storage";
62import { clientPresentationMetadata } from "./clientMetadata";
63​
64let nextObservedRpcRequestId = 0;
65​
66function currentNetworkStatus(): "unknown" | "offline" | "online" {
67 if (typeof navigator === "undefined") {
68 return "unknown";
69 }
70 return navigator.onLine ? "online" : "offline";
72​
73const connectivityLayer = Connectivity.layer({
74 status: Effect.sync(currentNetworkStatus),
75 changes: Stream.callback((queue) =>
76 Effect.acquireRelease(
77 Effect.sync(() => {
78 const online = () => Queue.offerUnsafe(queue, "online");
79 const offline = () => Queue.offerUnsafe(queue, "offline");
80 window.addEventListener("online", online);
81 window.addEventListener("offline", offline);
82 return { online, offline };
83 }),
84 ({ online, offline }) =>
85 Effect.sync(() => {
86 window.removeEventListener("online", online);
87 window.removeEventListener("offline", offline);
88 }),
89 ).pipe(Effect.asVoid),
90 ),
91});
92​
93const wakeupsLayer = Wakeups.layer({
94 changes: Stream.merge(
95 Stream.callback<"application-active">((queue) =>
96 Effect.acquireRelease(
97 Effect.sync(() => {
98 const listener = () => {
99 if (document.visibilityState === "visible") {
100 Queue.offerUnsafe(queue, "application-active");
101 }
102 };
103 document.addEventListener("visibilitychange", listener);
104 return listener;
105 }),
106 (listener) =>
107 Effect.sync(() => {
108 document.removeEventListener("visibilitychange", listener);
109 }),
110 ).pipe(Effect.asVoid),
111 ),
112 managedRelayAccountChanges(appAtomRegistry).pipe(
113 Stream.map(() => "credentials-changed" as const),
114 ),
115 ),
116});
117​
118function clientMetadata() {
119 return clientPresentationMetadata({
120 appVersion: APP_VERSION,
121 hosted: isHostedStaticApp(),
122 identity: {
123 userAgent: navigator.userAgent,
124 platform: navigator.platform,
125 maxTouchPoints: navigator.maxTouchPoints,
126 },
127 desktopBridge: window.desktopBridge,
128 });
130​
131function sshPreparationError(cause: unknown) {
132 const message = cause instanceof Error ? cause.message : String(cause);
133 if (message.toLowerCase().includes("cancel")) {
134 return new ConnectionBlockedError({
135 reason: "authentication",
136 detail: message,
137 });
138 }
139 return new ConnectionTransientError({
140 reason: "remote-unavailable",
141 detail: `Could not prepare the SSH environment: ${message}`,
142 });
144​
145export const provisionDesktopSshEnvironment = Effect.fn(
146 "web.connectionPlatform.ssh.provisionDesktop",
147)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) {
148 const bootstrap = yield* Effect.tryPromise({
149 try: () =>
150 bridge.ensureSshEnvironment(target, {
151 issuePairingToken: true,
152 }),
153 catch: sshPreparationError,
154 });
155 const pairingToken = bootstrap.pairingToken;
156 if (pairingToken === null) {
157 return yield* new ConnectionBlockedError({
158 reason: "authentication",
159 detail: "The SSH environment did not issue a pairing credential.",
160 });
161 }
162 const descriptor = yield* Effect.tryPromise({
163 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
164 catch: sshPreparationError,
165 });
166 const access = yield* Effect.tryPromise({
167 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
168 catch: sshPreparationError,
169 });
170 return {
171 environmentId: descriptor.environmentId,
172 label: descriptor.label,
173 bootstrap,
174 bearerToken: access.access_token,
175 };
176});
177​
178const capabilitiesLayer = Layer.effectContext(
179 Effect.sync(() => {
180 const presentation = ClientPresentation.of({
181 metadata: clientMetadata(),
182 scopes: AuthStandardClientScopes,
183 });
184 const cloudSession = CloudSession.of({
185 identity: Effect.sync(() =>
186 Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
187 ),
188 clerkToken: Effect.gen(function* () {
189 const session = appAtomRegistry.get(managedRelaySessionAtom);
190 if (session === null) {
191 return yield* new ConnectionBlockedError({
192 reason: "authentication",
193 detail: "Sign in to T3 Connect to connect this environment.",
194 });
195 }
196 const token = yield* session.readClerkToken().pipe(
197 Effect.mapError(
198 (error) =>
199 new ConnectionTransientError({
200 reason: "network",
201 detail: error.message,
202 }),
203 ),
204 );
205 if (token === null) {
206 return yield* new ConnectionBlockedError({
207 reason: "authentication",
208 detail: "The T3 Connect session is unavailable.",
209 });
210 }
211 return token;
212 }),
213 });
214 const identity = RelayDeviceIdentity.of({
215 deviceId: Effect.succeed(Option.none()),
216 });
217 const primaryAuth = PrimaryEnvironmentAuth.of({
218 bearerToken: Effect.tryPromise({
219 try: readDesktopPrimaryBearerToken,
220 catch: (cause) =>
221 new ConnectionTransientError({
222 reason: "remote-unavailable",
223 detail: `Could not load the desktop primary credential: ${String(cause)}`,
224 }),
225 }).pipe(Effect.map(Option.fromNullishOr)),
226 });
227 const ssh = SshEnvironmentGateway.of({
228 provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
229 const bridge = window.desktopBridge;
230 if (bridge === undefined) {
231 return yield* new ConnectionBlockedError({
232 reason: "unsupported",
233 detail: "SSH environments are only available in the desktop app.",
234 });
235 }
236 return yield* provisionDesktopSshEnvironment(bridge, target);
237 }),
238 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
239 const bridge = window.desktopBridge;
240 if (bridge === undefined) {
241 return yield* new ConnectionBlockedError({
242 reason: "unsupported",
243 detail: "SSH environments are only available in the desktop app.",
244 });
245 }
246 const bootstrap = yield* Effect.tryPromise({
247 try: () =>
248 bridge.ensureSshEnvironment(input.target, {
249 issuePairingToken: true,
250 }),
251 catch: sshPreparationError,
252 });
253 if (bootstrap.pairingToken === null) {
254 return yield* new ConnectionBlockedError({
255 reason: "authentication",
256 detail: "The SSH environment did not issue a pairing credential.",
257 });
258 }
259 const access = yield* Effect.tryPromise({
260 try: () =>
261 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
262 catch: sshPreparationError,
263 });
264 return {
265 bootstrap,
266 bearerToken: access.access_token,
267 };
268 }),
269 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
270 const bridge = window.desktopBridge;
271 if (bridge === undefined) {
272 return;
273 }
274 yield* Effect.tryPromise({
275 try: () => bridge.disconnectSshEnvironment(target),
276 catch: (cause) =>
277 new ConnectionTransientError({
278 reason: "remote-unavailable",
279 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
280 }),
281 });
282 }),
283 });
284​
285 return Context.make(CloudSession, cloudSession).pipe(
286 Context.add(PrimaryEnvironmentAuth, primaryAuth),
287 Context.add(RelayDeviceIdentity, identity),
288 Context.add(ClientPresentation, presentation),
289 Context.add(SshEnvironmentGateway, ssh),
290 );
291 }),
292);
293​
294const loadPrimaryConnectionRegistration = Effect.fn(
295 "web.connectionPlatform.loadPrimaryConnectionRegistration",
296)(function* (resolved: PrimaryEnvironmentTarget) {
297 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
298 httpBaseUrl: resolved.target.httpBaseUrl,
299 }).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
300 return new PrimaryConnectionRegistration({
301 target: new PrimaryConnectionTarget({
302 environmentId: descriptor.environmentId,
303 label: descriptor.label,
304 httpBaseUrl: resolved.target.httpBaseUrl,
305 wsBaseUrl: resolved.target.wsBaseUrl,
306 }),
307 });
308});
309​
310// A desktop-local secondary backend (e.g. a parallel WSL backend) lives on its
311// own loopback origin, so — unlike the same-origin primary — it authenticates
312// with a bearer token minted from the bootstrap credential the desktop issues.
313const loadSecondaryConnectionRegistration = Effect.fn(
314 "web.connectionPlatform.loadSecondaryConnectionRegistration",
315)(function* (entry: DesktopEnvironmentBootstrap) {
316 if (
317 entry.httpBaseUrl === null ||
318 entry.wsBaseUrl === null ||
319 entry.bootstrapToken === undefined
320 ) {
321 return yield* new ConnectionTransientError({
322 reason: "endpoint-unavailable",
323 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
324 });
325 }
326 const httpBaseUrl = entry.httpBaseUrl;
327 const wsBaseUrl = entry.wsBaseUrl;
328 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
329 Effect.mapError(mapRemoteEnvironmentError),
330 );
331 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
332 const access = yield* bootstrapRemoteBearerSession({
333 httpBaseUrl,
334 credential: entry.bootstrapToken,
335 scopes: AuthStandardClientScopes,
336 clientMetadata: clientMetadata(),
337 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
338 // Keep the desktop pool's stable backend id in the connection id. The
339 // descriptor environment id still scopes projects and RPC state, while the
340 // backend id lets desktop-only operations (notably the WSL folder picker)
341 // route back to the instance that owns the environment.
342 const connectionId = desktopLocalConnectionId(entry.id);
343 // Prefer the desktop's bootstrap label (it identifies the backend and distro,
344 // e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
345 // a meaningful name without recovering it from the bootstrap list later.
346 const label = entry.label || descriptor.label;
347 return {
348 registration: new BearerConnectionRegistration({
349 target: new BearerConnectionTarget({
350 environmentId: descriptor.environmentId,
351 label,
352 connectionId,
353 }),
354 profile: new BearerConnectionProfile({
355 connectionId,
356 environmentId: descriptor.environmentId,
357 label,
358 httpBaseUrl,
359 wsBaseUrl,
360 }),
361 credential: new BearerConnectionCredential({ token: access.access_token }),
362 }),
363 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
364 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
365 };
366});
367​
368// Poll cadence for the desktop bootstrap topology. There is no change event on
369// the bridge, so the renderer polls; successful registrations are cached by a
370// signature of their endpoint + token until bearer credentials approach expiry.
371const PLATFORM_POLL_INTERVAL = "3 seconds";
372const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
373​
374export function secondaryBearerExpiresAtEpochMs(
375 issuedAtEpochMs: number,
376 expiresInSeconds: number,
377): number {
378 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
380​
381export function secondaryBearerRefreshAtEpochMs(
382 issuedAtEpochMs: number,
383 expiresInSeconds: number,
384): number {
385 return Math.max(
386 issuedAtEpochMs,
387 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
388 SECONDARY_BEARER_REFRESH_SKEW_MS,
389 );
391​
392interface CachedPlatformRegistration {
393 readonly signature: string;
394 readonly registration: PlatformConnectionRegistration;
395 readonly expiresAtEpochMs?: number;
396 readonly refreshAtEpochMs?: number;
398​
399export type PrimaryEnvironmentTargetRead =
400 | {
401 readonly _tag: "Success";
402 readonly target: PrimaryEnvironmentTarget | null;
403 }
404 | {
405 readonly _tag: "Failure";
406 readonly cause: unknown;
407 };
408​
409export function readPrimaryEnvironmentTargetResult(
410 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
411): PrimaryEnvironmentTargetRead {
412 try {
413 return { _tag: "Success", target: readTarget() };
414 } catch (cause) {
415 return { _tag: "Failure", cause };
416 }
418​
419export function primaryRegistrationToRetainAfterTopologyRead(
420 previous: ReadonlyMap<string, CachedPlatformRegistration>,
421 topologyRead: PrimaryEnvironmentTargetRead,
422): CachedPlatformRegistration | undefined {
423 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
425​
426export function canReuseCachedPlatformRegistration(
427 cached: CachedPlatformRegistration,
428 signature: string,
429 nowEpochMs: number,
430): boolean {
431 return (
432 cached.signature === signature &&
433 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
434 );
436​
437export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
438 cached: CachedPlatformRegistration,
439 signature: string,
440 nowEpochMs: number,
441): boolean {
442 return (
443 cached.signature === signature &&
444 cached.expiresAtEpochMs !== undefined &&
445 nowEpochMs < cached.expiresAtEpochMs
446 );
448​
449export function secondaryRegistrationsToRetainAfterTopologyRead(
450 previous: ReadonlyMap<string, CachedPlatformRegistration>,
451 topologyRead: DesktopSecondaryBootstrapsRead,
452 nowEpochMs: number,
453): ReadonlyMap<string, CachedPlatformRegistration> {
454 if (topologyRead._tag === "Success") {
455 return new Map();
456 }
457 return new Map(
458 [...previous].filter(
459 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
460 ),
461 );
463​
464const platformConnectionSourceLayer = Layer.effect(
465 PlatformConnectionSource,
466 Effect.gen(function* () {
467 if (isHostedStaticApp()) {
468 return PlatformConnectionSource.of({
469 registrations: Stream.empty,
470 });
471 }
472 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
473​
474 // Resolve the full set of platform-managed environments the host currently
475 // reports: the primary (same-origin cookie auth) plus any desktop-local
476 // backends running alongside it (bearer auth). Reused registrations come
477 // from the cache; a failed entry is skipped and retried on the next poll.
478 const buildPlatformRegistrations = Effect.gen(function* () {
479 const previous = yield* Ref.get(cacheRef);
480 const nowEpochMs = yield* Clock.currentTimeMillis;
481 const next = new Map<string, CachedPlatformRegistration>();
482 const registrations: Array<PlatformConnectionRegistration> = [];
483​
484 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
485 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
486 previous,
487 primaryTopologyRead,
488 );
489 if (retainedPrimary !== undefined) {
490 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
491 registrations.push(retainedPrimary.registration);
492 }
493​
494 if (primaryTopologyRead._tag === "Failure") {
495 yield* Effect.logWarning("Could not read the primary environment topology.", {
496 cause: primaryTopologyRead.cause,
497 });
498 } else if (primaryTopologyRead.target !== null) {
499 const primaryTarget = primaryTopologyRead.target;
500 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
501 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
502 if (
503 cached !== undefined &&
504 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
505 ) {
506 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
507 registrations.push(cached.registration);
508 } else {
509 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
510 Effect.tapError((error) =>
511 Effect.logWarning("Could not discover the primary environment.", { error }),
512 ),
513 Effect.option,
514 );
515 if (Option.isSome(built)) {
516 const cacheEntry = { signature, registration: built.value };
517 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
518 registrations.push(built.value);
519 }
520 }
521 }
522​
523 const topologyRead = readDesktopSecondaryBootstrapsResult();
524 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
525 previous,
526 topologyRead,
527 nowEpochMs,
528 )) {
529 next.set(id, cached);
530 registrations.push(cached.registration);
531 }
532​
533 if (topologyRead._tag === "Failure") {
534 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
535 cause: topologyRead.cause,
536 });
537 } else {
538 for (const bootstrap of topologyRead.bootstraps) {
539 const signature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}|${bootstrap.bootstrapToken ?? ""}`;
540 const cached = previous.get(bootstrap.id);
541 if (
542 cached !== undefined &&
543 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
544 ) {
545 next.set(bootstrap.id, cached);
546 registrations.push(cached.registration);
547 continue;
548 }
549 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
550 Effect.tapError((error) =>
551 Effect.logWarning("Could not connect a desktop-local backend.", {
552 id: bootstrap.id,
553 error,
554 }),
555 ),
556 Effect.option,
557 );
558 if (Option.isSome(built)) {
559 const cacheEntry = { signature, ...built.value };
560 next.set(bootstrap.id, cacheEntry);
561 registrations.push(built.value.registration);
562 } else if (
563 cached !== undefined &&
564 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, signature, nowEpochMs)
565 ) {
566 next.set(bootstrap.id, cached);
567 registrations.push(cached.registration);
568 }
569 }
570 }
571​
572 yield* Ref.set(cacheRef, next);
573 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
574 }).pipe(Effect.provide(FetchHttpClient.layer));
575​
576 return PlatformConnectionSource.of({
577 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
578 Stream.mapEffect(() => buildPlatformRegistrations),
579 ),
580 });
581 }),
582);
583​
584const environmentOwnedDataCleanupLayer = Layer.succeed(
585 EnvironmentOwnedDataCleanup,
586 EnvironmentOwnedDataCleanup.of({
587 clear: (environmentId) =>
588 Effect.sync(() => {
589 clearComposerDraftsEnvironment(environmentId);
590 }),
591 }),
592);
593​
594const rpcRequestObserverLayer = Layer.succeed(
595 EnvironmentRpcRequestObserver,
596 EnvironmentRpcRequestObserver.of({
597 observe: ({ environmentId, method }) =>
598 Effect.sync(() => {
599 nextObservedRpcRequestId += 1;
600 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
601 trackRpcRequestSent(requestId, method, `${method} · ${environmentId}`);
602 return Effect.sync(() => {
603 acknowledgeRpcRequest(requestId);
604 });
605 }),
606 }),
607);
608​
609type ConnectionPlatformLayerSource =
610 | typeof connectionStorageLayer
611 | typeof connectivityLayer
612 | typeof wakeupsLayer
613 | typeof capabilitiesLayer
614 | typeof platformConnectionSourceLayer
615 | typeof environmentOwnedDataCleanupLayer
616 | typeof rpcRequestObserverLayer;
617​
618export const connectionPlatformLayer: Layer.Layer<
619 Layer.Success<ConnectionPlatformLayerSource>,
620 Layer.Error<ConnectionPlatformLayerSource>,
621 Layer.Services<ConnectionPlatformLayerSource>
622> = Layer.mergeAll(
623 connectionStorageLayer,
624 connectivityLayer,
625 wakeupsLayer,
626 capabilitiesLayer,
627 platformConnectionSourceLayer,
628 environmentOwnedDataCleanupLayer,
629 rpcRequestObserverLayer,
630);