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

platform.ts

622 lines21.5 KB

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