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

platform.ts

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