Open History to see the last commit
1import {
2 ClientPresentation,
3 CloudSession,
4 EnvironmentOwnedDataCleanup,
5 PlatformConnectionSource,
6 PrimaryEnvironmentAuth,
7 RelayDeviceIdentity,
8 SshEnvironmentGateway,
9} from "@t3tools/client-runtime/platform";
10import {
11 ConnectionBlockedError,
12 ConnectionTransientError,
13 Connectivity,
14 mapRemoteEnvironmentError,
15 PrimaryConnectionRegistration,
16 PrimaryConnectionTarget,
17 Wakeups,
18} from "@t3tools/client-runtime/connection";
19import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
20import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
21import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
22import {
23 AuthStandardClientScopes,
24 type DesktopBridge,
25 type DesktopSshEnvironmentTarget,
26} from "@t3tools/contracts";
27import * as Context from "effect/Context";
28import * as Effect from "effect/Effect";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Queue from "effect/Queue";
32import * as Schedule from "effect/Schedule";
33import * as Stream from "effect/Stream";
34
35import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
36import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
37import { readPrimaryEnvironmentTarget } from "../environments/primary/target";
38import { clearComposerDraftsEnvironment } from "../composerDraftStore";
39import { isHostedStaticApp } from "../hostedPairing";
40import { appAtomRegistry } from "../rpc/atomRegistry";
41import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
42import { connectionStorageLayer } from "./storage";
43
44let nextObservedRpcRequestId = 0;
45
46function currentNetworkStatus(): "unknown" | "offline" | "online" {
47 if (typeof navigator === "undefined") {
48 return "unknown";
49 }
50 return navigator.onLine ? "online" : "offline";
51}
52
53const connectivityLayer = Connectivity.layer({
54 status: Effect.sync(currentNetworkStatus),
55 changes: Stream.callback((queue) =>
56 Effect.acquireRelease(
57 Effect.sync(() => {
58 const online = () => Queue.offerUnsafe(queue, "online");
59 const offline = () => Queue.offerUnsafe(queue, "offline");
60 window.addEventListener("online", online);
61 window.addEventListener("offline", offline);
62 return { online, offline };
63 }),
64 ({ online, offline }) =>
65 Effect.sync(() => {
66 window.removeEventListener("online", online);
67 window.removeEventListener("offline", offline);
68 }),
69 ).pipe(Effect.asVoid),
70 ),
71});
72
73const wakeupsLayer = Wakeups.layer({
74 changes: Stream.merge(
75 Stream.callback<"application-active">((queue) =>
76 Effect.acquireRelease(
77 Effect.sync(() => {
78 const listener = () => {
79 if (document.visibilityState === "visible") {
80 Queue.offerUnsafe(queue, "application-active");
81 }
82 };
83 document.addEventListener("visibilitychange", listener);
84 return listener;
85 }),
86 (listener) =>
87 Effect.sync(() => {
88 document.removeEventListener("visibilitychange", listener);
89 }),
90 ).pipe(Effect.asVoid),
91 ),
92 managedRelayAccountChanges(appAtomRegistry).pipe(
93 Stream.map(() => "credentials-changed" as const),
94 ),
95 ),
96});
97
98function clientMetadata() {
99 const desktop = window.desktopBridge !== undefined;
100 const platform = navigator.platform.trim();
101 return {
102 label: desktop ? "T3 Code Desktop" : "T3 Code Web",
103 deviceType: "desktop" as const,
104 ...(platform === "" ? {} : { os: platform }),
105 };
106}
107
108function sshPreparationError(cause: unknown) {
109 const message = cause instanceof Error ? cause.message : String(cause);
110 if (message.toLowerCase().includes("cancel")) {
111 return new ConnectionBlockedError({
112 reason: "authentication",
113 detail: message,
114 });
115 }
116 return new ConnectionTransientError({
117 reason: "remote-unavailable",
118 detail: `Could not prepare the SSH environment: ${message}`,
119 });
120}
121
122export const provisionDesktopSshEnvironment = Effect.fn(
123 "web.connectionPlatform.ssh.provisionDesktop",
124)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) {
125 const bootstrap = yield* Effect.tryPromise({
126 try: () =>
127 bridge.ensureSshEnvironment(target, {
128 issuePairingToken: true,
129 }),
130 catch: sshPreparationError,
131 });
132 const pairingToken = bootstrap.pairingToken;
133 if (pairingToken === null) {
134 return yield* new ConnectionBlockedError({
135 reason: "authentication",
136 detail: "The SSH environment did not issue a pairing credential.",
137 });
138 }
139 const descriptor = yield* Effect.tryPromise({
140 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
141 catch: sshPreparationError,
142 });
143 const access = yield* Effect.tryPromise({
144 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
145 catch: sshPreparationError,
146 });
147 return {
148 environmentId: descriptor.environmentId,
149 label: descriptor.label,
150 bootstrap,
151 bearerToken: access.access_token,
152 };
153});
154
155const capabilitiesLayer = Layer.effectContext(
156 Effect.sync(() => {
157 const presentation = ClientPresentation.of({
158 metadata: clientMetadata(),
159 scopes: AuthStandardClientScopes,
160 });
161 const cloudSession = CloudSession.of({
162 clerkToken: Effect.gen(function* () {
163 const session = appAtomRegistry.get(managedRelaySessionAtom);
164 if (session === null) {
165 return yield* new ConnectionBlockedError({
166 reason: "authentication",
167 detail: "Sign in to T3 Cloud to connect this environment.",
168 });
169 }
170 const token = yield* session.readClerkToken().pipe(
171 Effect.mapError(
172 (error) =>
173 new ConnectionTransientError({
174 reason: "network",
175 detail: error.message,
176 }),
177 ),
178 );
179 if (token === null) {
180 return yield* new ConnectionBlockedError({
181 reason: "authentication",
182 detail: "The T3 Cloud session is unavailable.",
183 });
184 }
185 return token;
186 }),
187 });
188 const identity = RelayDeviceIdentity.of({
189 deviceId: Effect.succeed(Option.none()),
190 });
191 const primaryAuth = PrimaryEnvironmentAuth.of({
192 bearerToken: Effect.tryPromise({
193 try: readDesktopPrimaryBearerToken,
194 catch: (cause) =>
195 new ConnectionTransientError({
196 reason: "remote-unavailable",
197 detail: `Could not load the desktop primary credential: ${String(cause)}`,
198 }),
199 }).pipe(Effect.map(Option.fromNullishOr)),
200 });
201 const ssh = SshEnvironmentGateway.of({
202 provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
203 const bridge = window.desktopBridge;
204 if (bridge === undefined) {
205 return yield* new ConnectionBlockedError({
206 reason: "unsupported",
207 detail: "SSH environments are only available in the desktop app.",
208 });
209 }
210 return yield* provisionDesktopSshEnvironment(bridge, target);
211 }),
212 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
213 const bridge = window.desktopBridge;
214 if (bridge === undefined) {
215 return yield* new ConnectionBlockedError({
216 reason: "unsupported",
217 detail: "SSH environments are only available in the desktop app.",
218 });
219 }
220 const bootstrap = yield* Effect.tryPromise({
221 try: () =>
222 bridge.ensureSshEnvironment(input.target, {
223 issuePairingToken: true,
224 }),
225 catch: sshPreparationError,
226 });
227 if (bootstrap.pairingToken === null) {
228 return yield* new ConnectionBlockedError({
229 reason: "authentication",
230 detail: "The SSH environment did not issue a pairing credential.",
231 });
232 }
233 const access = yield* Effect.tryPromise({
234 try: () =>
235 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
236 catch: sshPreparationError,
237 });
238 return {
239 bootstrap,
240 bearerToken: access.access_token,
241 };
242 }),
243 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
244 const bridge = window.desktopBridge;
245 if (bridge === undefined) {
246 return;
247 }
248 yield* Effect.tryPromise({
249 try: () => bridge.disconnectSshEnvironment(target),
250 catch: (cause) =>
251 new ConnectionTransientError({
252 reason: "remote-unavailable",
253 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
254 }),
255 });
256 }),
257 });
258
259 return Context.make(CloudSession, cloudSession).pipe(
260 Context.add(PrimaryEnvironmentAuth, primaryAuth),
261 Context.add(RelayDeviceIdentity, identity),
262 Context.add(ClientPresentation, presentation),
263 Context.add(SshEnvironmentGateway, ssh),
264 );
265 }),
266);
267
268const loadPrimaryConnectionRegistration = Effect.fn(
269 "web.connectionPlatform.loadPrimaryConnectionRegistration",
270)(function* () {
271 const resolved = readPrimaryEnvironmentTarget();
272 if (resolved === null) {
273 return yield* new ConnectionBlockedError({
274 reason: "configuration",
275 detail: "Unable to resolve the primary environment endpoint.",
276 });
277 }
278 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
279 httpBaseUrl: resolved.target.httpBaseUrl,
280 }).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
281 return new PrimaryConnectionRegistration({
282 target: new PrimaryConnectionTarget({
283 environmentId: descriptor.environmentId,
284 label: descriptor.label,
285 httpBaseUrl: resolved.target.httpBaseUrl,
286 wsBaseUrl: resolved.target.wsBaseUrl,
287 }),
288 });
289});
290
291const primaryRegistrationRetrySchedule = Schedule.exponential("1 second").pipe(
292 Schedule.either(Schedule.spaced("16 seconds")),
293);
294
295const platformConnectionSourceLayer = Layer.sync(PlatformConnectionSource, () => {
296 if (isHostedStaticApp()) {
297 return PlatformConnectionSource.of({
298 registrations: Stream.empty,
299 });
300 }
301 return PlatformConnectionSource.of({
302 registrations: Stream.fromEffect(loadPrimaryConnectionRegistration()).pipe(
303 Stream.tapError((error) =>
304 Effect.logWarning("Could not discover the primary environment.", {
305 error,
306 }),
307 ),
308 Stream.retry(primaryRegistrationRetrySchedule),
309 Stream.catchCause(() => Stream.empty),
310 ),
311 });
312});
313
314const environmentOwnedDataCleanupLayer = Layer.succeed(
315 EnvironmentOwnedDataCleanup,
316 EnvironmentOwnedDataCleanup.of({
317 clear: (environmentId) =>
318 Effect.sync(() => {
319 clearComposerDraftsEnvironment(environmentId);
320 }),
321 }),
322);
323
324const rpcRequestObserverLayer = Layer.succeed(
325 EnvironmentRpcRequestObserver,
326 EnvironmentRpcRequestObserver.of({
327 observe: ({ environmentId, method }) =>
328 Effect.sync(() => {
329 nextObservedRpcRequestId += 1;
330 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
331 trackRpcRequestSent(requestId, `${method} · ${environmentId}`);
332 return Effect.sync(() => {
333 acknowledgeRpcRequest(requestId);
334 });
335 }),
336 }),
337);
338
339type ConnectionPlatformLayerSource =
340 | typeof connectionStorageLayer
341 | typeof connectivityLayer
342 | typeof wakeupsLayer
343 | typeof capabilitiesLayer
344 | typeof platformConnectionSourceLayer
345 | typeof environmentOwnedDataCleanupLayer
346 | typeof rpcRequestObserverLayer;
347
348export const connectionPlatformLayer: Layer.Layer<
349 Layer.Success<ConnectionPlatformLayerSource>,
350 Layer.Error<ConnectionPlatformLayerSource>,
351 Layer.Services<ConnectionPlatformLayerSource>
352> = Layer.mergeAll(
353 connectionStorageLayer,
354 connectivityLayer,
355 wakeupsLayer,
356 capabilitiesLayer,
357 platformConnectionSourceLayer,
358 environmentOwnedDataCleanupLayer,
359 rpcRequestObserverLayer,
360);