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

platform.ts

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