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

linkEnvironment.ts

430 lines14.0 KB

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