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

platform.ts

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