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

platform.ts

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