Open History to see the last commit
1import * as Effect from "effect/Effect";
2import { msg, type Msg } from "gt-react";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import * as SubscriptionRef from "effect/SubscriptionRef";
7import type { HttpClient } from "effect/http";
8import {
9 EnvironmentCloudEndpointUnavailableError,
10 type EnvironmentCloudLinkStateResult,
11 type EnvironmentConnectReachability,
12 EnvironmentHttpBadRequestError,
13 EnvironmentHttpConflictError,
14 EnvironmentHttpForbiddenError,
15 EnvironmentHttpInternalServerError,
16 EnvironmentHttpUnauthorizedError,
17 EnvironmentId,
18 WS_METHODS,
19} from "@t3tools/contracts";
20import {
21 type RelayEnvironmentLinkResponse,
22 type RelayManagedEndpointProviderKind,
23} from "@t3tools/contracts/relay";
24import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
25import { request, runStream } from "@t3tools/client-runtime/rpc";
26import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
27import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";
28
29import { m } from "../i18n/messages";
30import { resolveCloudPublicConfig } from "./publicConfig";
31import {
32 finishRelayClientInstall,
33 reportRelayClientInstallProgress,
34 requestRelayClientInstallConfirmation,
35} from "./relayClientInstallDialog";
36
37function relayUrl(): string | null {
38 return resolveCloudPublicConfig().relayUrl;
39}
40
41export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(
42 "CloudEnvironmentLinkError",
43 {
44 message: Schema.String,
45 cause: Schema.optional(Schema.Defect()),
46 traceId: Schema.optional(Schema.String),
47 },
48) {}
49
50export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
51
52const relayClientRpcError = (message: string) => (cause: unknown) =>
53 new CloudEnvironmentLinkError({
54 message,
55 cause,
56 });
57
58const ensureRelayClientAvailable = Effect.fn("linkEnvironment.ensureRelayClientAvailable")(
59 function* (
60 environmentId: EnvironmentId,
61 ): Effect.fn.Return<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {
62 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
63 const status = yield* registry
64 .run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))
65 .pipe(
66 Effect.mapError(relayClientRpcError(m(msg("Could not check relay client availability.")))),
67 );
68 if (status.status === "available") return;
69 if (status.status === "unsupported") {
70 return yield* new CloudEnvironmentLinkError({
71 message: m(
72 msg`T3 Code cannot install the relay client automatically on ${{ platform: status.platform }}-${{ arch: status.arch }}.`,
73 ),
74 });
75 }
76
77 const confirmed = yield* Effect.tryPromise({
78 try: () => requestRelayClientInstallConfirmation(status.version),
79 catch: relayClientRpcError(m(msg("Could not confirm relay client installation."))),
80 });
81 if (!confirmed) {
82 return yield* new CloudEnvironmentLinkError({
83 message: m(msg("Relay client installation was cancelled.")),
84 });
85 }
86
87 const installed = yield* registry
88 .runStream(
89 environmentId,
90 runStream(WS_METHODS.cloudInstallRelayClient, {}).pipe(
91 Stream.tap((event) => Effect.sync(() => reportRelayClientInstallProgress(event))),
92 ),
93 )
94 .pipe(
95 Stream.runLast,
96 Effect.mapError(relayClientRpcError(m(msg("Could not install the relay client.")))),
97 Effect.ensuring(Effect.sync(finishRelayClientInstall)),
98 );
99 if (Option.isNone(installed) || installed.value.type !== "complete") {
100 return yield* new CloudEnvironmentLinkError({
101 message: m(msg("The relay client install completed without a final status.")),
102 });
103 }
104 const installedStatus = installed.value.status;
105 if (installedStatus.status !== "available") {
106 return yield* new CloudEnvironmentLinkError({
107 message:
108 installedStatus.status === "unsupported"
109 ? m(
110 msg`T3 Code cannot install the relay client automatically on ${{ platform: installedStatus.platform }}-${{ arch: installedStatus.arch }}.`,
111 )
112 : m(msg("The relay client is still unavailable after installation.")),
113 });
114 }
115 },
116);
117
118const isEnvironmentCloudApiError = Schema.is(
119 Schema.Union([
120 EnvironmentHttpBadRequestError,
121 EnvironmentHttpUnauthorizedError,
122 EnvironmentHttpForbiddenError,
123 EnvironmentHttpConflictError,
124 EnvironmentHttpInternalServerError,
125 EnvironmentCloudEndpointUnavailableError,
126 ]),
127);
128
129function decodedRelayClientError(message: string) {
130 return (cause: ManagedRelay.ManagedRelayClientError) => {
131 const failed = cause._tag === "ManagedRelayRequestFailedError" ? cause : undefined;
132 const traceId = "traceId" in cause ? cause.traceId : undefined;
133 const detail = (failed && relayRequestFailureDetail(failed)) ?? cause.message;
134 return new CloudEnvironmentLinkError({
135 message: detail ? m(msg`${{ message }}: ${{ detail }}`) : message,
136 cause,
137 ...(traceId ? { traceId } : {}),
138 });
139 };
140}
141
142function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
143 if (isEnvironmentCloudApiError(cause)) {
144 return cause;
145 }
146 if (typeof cause !== "object" || cause === null) {
147 return null;
148 }
149 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
150}
151
152/** `msg()` sentences: the failure alone, and the same failure followed by the server's `{detail}`. */
153interface EnvironmentFailureCopy {
154 readonly message: string;
155 readonly withDetail: (values: { detail: string }) => string | Msg;
156}
157
158const environmentApiError = (copy: EnvironmentFailureCopy) => (cause: unknown) => {
159 const environmentError = findEnvironmentCloudApiError(cause);
160 return new CloudEnvironmentLinkError({
161 message: environmentError
162 ? m(copy.withDetail({ detail: environmentError.message }))
163 : m(copy.message),
164 cause,
165 });
166};
167
168function endpointOrigin(httpBaseUrl: string) {
169 const url = new URL(httpBaseUrl);
170 return {
171 localHttpHost: "127.0.0.1",
172 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
173 };
174}
175
176const MANAGED_ENDPOINT_PROVIDER_KIND =
177 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
178
179function ensureLinkedEnvironmentMatches(input: {
180 readonly expectedEnvironmentId: string;
181 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
182 readonly link: RelayEnvironmentLinkResponse;
183}): Effect.Effect<void, CloudEnvironmentLinkError> {
184 if (input.link.environmentId !== input.expectedEnvironmentId) {
185 return new CloudEnvironmentLinkError({
186 message: m(msg("Relay returned credentials for a different environment.")),
187 });
188 }
189 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
190 return new CloudEnvironmentLinkError({
191 message: m(msg("Relay returned credentials for a different endpoint provider.")),
192 });
193 }
194 return Effect.void;
195}
196
197export interface CloudLinkTarget {
198 readonly environmentId: EnvironmentId;
199}
200
201export type CloudLinkState = EnvironmentCloudLinkStateResult;
202
203// Linking can install the relay client and start a managed tunnel before it answers.
204const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000;
205
206type ConnectedEnvironmentHttpRequest<A, E, R> = Parameters<
207 typeof executeConnectedEnvironmentHttpRequest<"connect", A, E, R>
208>[0];
209
210/** Runs on the target environment with this client's own credentials for it. */
211const connectRequest = <A, E, R>(
212 target: CloudLinkTarget,
213 input: Omit<ConnectedEnvironmentHttpRequest<A, E, R>, "group" | "timeoutMs">,
214 failure: EnvironmentFailureCopy,
215) =>
216 Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>
217 registry.run(
218 target.environmentId,
219 executeConnectedEnvironmentHttpRequest({
220 ...input,
221 group: "connect",
222 timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
223 }),
224 ),
225 ).pipe(Effect.mapError(environmentApiError(failure)));
226
227const preparedEndpoint = (target: CloudLinkTarget) =>
228 Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>
229 registry.run(
230 target.environmentId,
231 Effect.flatMap(EnvironmentSupervisor.EnvironmentSupervisor, (supervisor) =>
232 SubscriptionRef.get(supervisor.prepared),
233 ),
234 ),
235 ).pipe(
236 Effect.mapError(
237 environmentApiError({
238 message: msg("Could not reach the environment."),
239 withDetail: ({ detail }: { detail: string }) =>
240 msg`Could not reach the environment: ${{ detail }}`,
241 }),
242 ),
243 Effect.flatMap(
244 Option.match({
245 onNone: () =>
246 Effect.fail(
247 new CloudEnvironmentLinkError({ message: m(msg("The environment is not connected.")) }),
248 ),
249 onSome: ({ httpBaseUrl, target }) =>
250 Effect.succeed({
251 httpBaseUrl,
252 wsBaseUrl:
253 target._tag === "PrimaryConnectionTarget"
254 ? target.wsBaseUrl
255 : httpBaseUrl.replace(/^http/, "ws"),
256 }),
257 }),
258 ),
259 );
260
261type CloudLinkServices = EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient;
262
263export const readCloudLinkState: (input: {
264 readonly target: CloudLinkTarget;
265}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, CloudLinkServices> =
266 Effect.fn("linkEnvironment.readCloudLinkState")(function* (input: {
267 readonly target: CloudLinkTarget;
268 }) {
269 return yield* connectRequest(
270 input.target,
271 {
272 method: "GET",
273 url: (urls) => urls.linkState(),
274 request: ({ client, headers }) => client.linkState({ headers }),
275 },
276 {
277 message: msg("Could not read environment cloud link state."),
278 withDetail: ({ detail }: { detail: string }) =>
279 msg`Could not read environment cloud link state: ${{ detail }}`,
280 },
281 );
282 });
283
284/** Runs the environment's T3 Connect reachability check now; the link state then reports it. */
285export const checkCloudReachability: (input: {
286 readonly target: CloudLinkTarget;
287}) => Effect.Effect<EnvironmentConnectReachability, CloudEnvironmentLinkError, CloudLinkServices> =
288 Effect.fn("linkEnvironment.checkCloudReachability")(function* (input: {
289 readonly target: CloudLinkTarget;
290 }) {
291 return yield* connectRequest(
292 input.target,
293 {
294 method: "POST",
295 url: (urls) => urls.checkReachability(),
296 request: ({ client, headers }) => client.checkReachability({ headers }),
297 },
298 {
299 message: msg("Could not check T3 Connect."),
300 withDetail: ({ detail }: { detail: string }) =>
301 msg`Could not check T3 Connect: ${{ detail }}`,
302 },
303 );
304 });
305
306export const updateCloudPreferences: (input: {
307 readonly target: CloudLinkTarget;
308 readonly publishAgentActivity: boolean;
309 readonly holdWebhooksWhileOffline?: boolean;
310}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, CloudLinkServices> = Effect.fn(
311 "linkEnvironment.updateCloudPreferences",
312)(function* (input: {
313 readonly target: CloudLinkTarget;
314 readonly publishAgentActivity: boolean;
315 readonly holdWebhooksWhileOffline?: boolean;
316}) {
317 const { target, ...payload } = input;
318 return yield* connectRequest(
319 target,
320 {
321 method: "POST",
322 url: (urls) => urls.preferences(),
323 request: ({ client, headers }) => client.preferences({ headers, payload }),
324 },
325 {
326 message: msg("Could not update environment cloud preferences."),
327 withDetail: ({ detail }: { detail: string }) =>
328 msg`Could not update environment cloud preferences: ${{ detail }}`,
329 },
330 );
331});
332
333export const unlinkEnvironmentFromCloud: (input: {
334 readonly target: CloudLinkTarget;
335 readonly clerkToken: string | null;
336}) => Effect.Effect<
337 void,
338 CloudEnvironmentLinkError,
339 CloudLinkServices | ManagedRelay.ManagedRelayClient
340> = Effect.fn("linkEnvironment.unlinkEnvironmentFromCloud")(function* (input: {
341 readonly target: CloudLinkTarget;
342 readonly clerkToken: string | null;
343}) {
344 yield* connectRequest(
345 input.target,
346 {
347 method: "POST",
348 url: (urls) => urls.unlink(),
349 request: ({ client, headers }) => client.unlink({ headers }),
350 },
351 {
352 message: msg("Could not unlink the environment from cloud."),
353 withDetail: ({ detail }: { detail: string }) =>
354 msg`Could not unlink the environment from cloud: ${{ detail }}`,
355 },
356 );
357
358 const configuredRelayUrl = relayUrl();
359 if (configuredRelayUrl && input.clerkToken) {
360 const relayClient = yield* ManagedRelay.ManagedRelayClient;
361 yield* relayClient
362 .unlinkEnvironment({
363 clerkToken: input.clerkToken,
364 environmentId: input.target.environmentId,
365 })
366 .pipe(
367 Effect.mapError(
368 decodedRelayClientError(
369 m(
370 msg(
371 "Disconnected locally, but T3 Connect did not confirm it removed this environment",
372 ),
373 ),
374 ),
375 ),
376 );
377 }
378});
379
380export type CloudLinkMode = "managed" | "publish_only";
381
382const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
383
384export const linkEnvironmentToCloud: (input: {
385 readonly target: CloudLinkTarget;
386 readonly clerkToken: string;
387 readonly mode?: CloudLinkMode;
388}) => Effect.Effect<
389 void,
390 CloudEnvironmentLinkError,
391 CloudLinkServices | ManagedRelay.ManagedRelayClient
392> = Effect.fn("linkEnvironment.linkEnvironmentToCloud")(function* (input: {
393 readonly target: CloudLinkTarget;
394 readonly clerkToken: string;
395 readonly mode?: CloudLinkMode;
396}) {
397 const configuredRelayUrl = relayUrl();
398 if (!configuredRelayUrl) {
399 return yield* new CloudEnvironmentLinkError({
400 message: m(msg`${{ name: "T3CODE_RELAY_URL" }} is not configured.`),
401 });
402 }
403 const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
404 const providerKind = managedTunnelsEnabled
405 ? MANAGED_ENDPOINT_PROVIDER_KIND
406 : PUBLISH_ONLY_PROVIDER_KIND;
407 const relayClient = yield* ManagedRelay.ManagedRelayClient;
408 // The environment only signs a proof for the loopback origin this request reaches it on.
409 const endpoint = yield* preparedEndpoint(input.target);
410 if (managedTunnelsEnabled) {
411 yield* ensureRelayClientAvailable(input.target.environmentId);
412 }
413
414 const challenge = yield* relayClient
415 .createEnvironmentLinkChallenge({
416 clerkToken: input.clerkToken,
417 payload: {
418 notificationsEnabled: true,
419 liveActivitiesEnabled: true,
420 managedTunnelsEnabled,
421 },
422 })
423 .pipe(
424 Effect.mapError(
425 decodedRelayClientError(
426 m(msg`${{ url: `${configuredRelayUrl}/v1/client/environment-link-challenges` }} failed`),
427 ),
428 ),
429 );
430 const proof = yield* connectRequest(
431 input.target,
432 {
433 method: "POST",
434 url: (urls) => urls.linkProof(),
435 request: ({ client, headers }) =>
436 client.linkProof({
437 headers,
438 payload: {
439 challenge: challenge.challenge,
440 relayIssuer: configuredRelayUrl,
441 endpoint: { ...endpoint, providerKind },
442 origin: endpointOrigin(endpoint.httpBaseUrl),
443 },
444 }),
445 },
446 {
447 message: msg("Could not obtain environment link proof."),
448 withDetail: ({ detail }: { detail: string }) =>
449 msg`Could not obtain environment link proof: ${{ detail }}`,
450 },
451 );
452 const link = yield* relayClient
453 .linkEnvironment({
454 clerkToken: input.clerkToken,
455 payload: {
456 proof,
457 notificationsEnabled: true,
458 liveActivitiesEnabled: true,
459 managedTunnelsEnabled,
460 },
461 })
462 .pipe(
463 Effect.mapError(
464 decodedRelayClientError(
465 m(msg`${{ url: `${configuredRelayUrl}/v1/client/environment-links` }} failed`),
466 ),
467 ),
468 );
469 yield* ensureLinkedEnvironmentMatches({
470 expectedEnvironmentId: input.target.environmentId,
471 expectedProviderKind: providerKind,
472 link,
473 });
474
475 yield* connectRequest(
476 input.target,
477 {
478 method: "POST",
479 url: (urls) => urls.relayConfig(),
480 request: ({ client, headers }) =>
481 client.relayConfig({
482 headers,
483 payload: {
484 relayUrl: configuredRelayUrl,
485 relayIssuer: link.relayIssuer,
486 cloudUserId: link.cloudUserId,
487 environmentCredential: link.environmentCredential,
488 cloudMintPublicKey: link.cloudMintPublicKey,
489 endpointRuntime: link.endpointRuntime,
490 },
491 }),
492 },
493 {
494 message: msg("Could not configure environment relay access."),
495 withDetail: ({ detail }: { detail: string }) =>
496 msg`Could not configure environment relay access: ${{ detail }}`,
497 },
498 );
499});