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

linkEnvironment.ts

350 lines12.3 KB

1import * as Data from "effect/Data";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import { 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 } from "@t3tools/client-runtime/connection";
23import { request, runStream } from "@t3tools/client-runtime/rpc";
24import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
25import { ManagedRelay, relayProtectedErrorMessage } from "@t3tools/client-runtime/relay";
26​
27import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";
28import { resolveCloudPublicConfig } from "./publicConfig";
29import {
30 finishRelayClientInstall,
31 reportRelayClientInstallProgress,
32 requestRelayClientInstallConfirmation,
33} from "./relayClientInstallDialog";
34​
35function relayUrl(): string | null {
36 return resolveCloudPublicConfig().relayUrl;
38​
39export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
40 readonly message: string;
41 readonly cause?: unknown;
42 readonly traceId?: string;
43}> {}
44​
45const relayClientRpcError = (message: string) => (cause: unknown) =>
46 new CloudEnvironmentLinkError({
47 message,
48 cause,
49 });
50​
51function ensureRelayClientAvailable(
52 environmentId: EnvironmentId,
53): Effect.Effect<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {
54 return Effect.gen(function* () {
55 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
56 const status = yield* registry
57 .run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))
58 .pipe(Effect.mapError(relayClientRpcError("Could not check relay client availability.")));
59 if (status.status === "available") return;
60 if (status.status === "unsupported") {
61 return yield* new CloudEnvironmentLinkError({
62 message: `T3 Code cannot install the relay client automatically on ${status.platform}-${status.arch}.`,
63 });
64 }
65​
66 const confirmed = yield* Effect.tryPromise({
67 try: () => requestRelayClientInstallConfirmation(status.version),
68 catch: relayClientRpcError("Could not confirm relay client installation."),
69 });
70 if (!confirmed) {
71 return yield* new CloudEnvironmentLinkError({
72 message: "Relay client installation was cancelled.",
73 });
74 }
75​
76 const installed = yield* registry
77 .runStream(
78 environmentId,
79 runStream(WS_METHODS.cloudInstallRelayClient, {}).pipe(
80 Stream.tap((event) => Effect.sync(() => reportRelayClientInstallProgress(event))),
81 ),
82 )
83 .pipe(
84 Stream.runLast,
85 Effect.mapError(relayClientRpcError("Could not install the relay client.")),
86 Effect.ensuring(Effect.sync(finishRelayClientInstall)),
87 );
88 if (Option.isNone(installed) || installed.value.type !== "complete") {
89 return yield* new CloudEnvironmentLinkError({
90 message: "The relay client install completed without a final status.",
91 });
92 }
93 const installedStatus = installed.value.status;
94 if (installedStatus.status !== "available") {
95 return yield* new CloudEnvironmentLinkError({
96 message:
97 installedStatus.status === "unsupported"
98 ? `T3 Code cannot install the relay client automatically on ${installedStatus.platform}-${installedStatus.arch}.`
99 : "The relay client is still unavailable after installation.",
100 });
101 }
102 });
104​
105const isEnvironmentCloudApiError = Schema.is(
106 Schema.Union([
107 EnvironmentHttpBadRequestError,
108 EnvironmentHttpUnauthorizedError,
109 EnvironmentHttpForbiddenError,
110 EnvironmentHttpConflictError,
111 EnvironmentHttpInternalServerError,
112 EnvironmentCloudEndpointUnavailableError,
113 ]),
114);
115​
116function decodedRelayClientError(message: string) {
117 return (cause: ManagedRelay.ManagedRelayClientError) => {
118 const relayError =
119 cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
120 const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
121 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
122 return new CloudEnvironmentLinkError({
123 message: detail ? `${message}: ${detail}` : message,
124 cause,
125 ...(traceId ? { traceId } : {}),
126 });
127 };
129​
130function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
131 if (isEnvironmentCloudApiError(cause)) {
132 return cause;
133 }
134 if (typeof cause !== "object" || cause === null) {
135 return null;
136 }
137 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
139​
140const environmentApiError = (message: string) => (cause: unknown) => {
141 const environmentError = findEnvironmentCloudApiError(cause);
142 return new CloudEnvironmentLinkError({
143 message: environmentError
144 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
145 : message,
146 cause,
147 });
148};
149​
150function endpointOrigin(httpBaseUrl: string) {
151 const url = new URL(httpBaseUrl);
152 return {
153 localHttpHost: "127.0.0.1",
154 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
155 };
157​
158const MANAGED_ENDPOINT_PROVIDER_KIND =
159 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
160​
161function ensureLinkedEnvironmentMatches(input: {
162 readonly expectedEnvironmentId: string;
163 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
164 readonly link: RelayEnvironmentLinkResponse;
165}): Effect.Effect<void, CloudEnvironmentLinkError> {
166 if (input.link.environmentId !== input.expectedEnvironmentId) {
167 return new CloudEnvironmentLinkError({
168 message: "Relay returned credentials for a different environment.",
169 });
170 }
171 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
172 return new CloudEnvironmentLinkError({
173 message: "Relay returned credentials for a different endpoint provider.",
174 });
175 }
176 return Effect.void;
178​
179export interface CloudLinkTarget {
180 readonly environmentId: string;
181 readonly label: string;
182 readonly httpBaseUrl: string;
183 readonly wsBaseUrl: string;
185​
186export type CloudLinkState = EnvironmentCloudLinkStateResult;
187​
188export function readPrimaryCloudLinkState(input: {
189 readonly target: CloudLinkTarget;
190}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {
191 return Effect.gen(function* () {
192 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
193 return yield* client.connect
194 .linkState({ headers: {} })
195 .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
196 }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
198​
199export function updatePrimaryCloudPreferences(input: {
200 readonly target: CloudLinkTarget;
201 readonly publishAgentActivity: boolean;
202 readonly holdWebhooksWhileOffline?: boolean;
203}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
204 return Effect.gen(function* () {
205 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
206 const { target: _target, ...payload } = input;
207 return yield* client.connect
208 .preferences({
209 headers: {},
210 payload,
211 })
212 .pipe(
213 Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
214 );
215 }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
217​
218export function unlinkPrimaryEnvironmentFromCloud(input: {
219 readonly target: CloudLinkTarget;
220 readonly clerkToken: string | null;
221}): Effect.Effect<
222 void,
223 CloudEnvironmentLinkError,
224 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
225> {
226 return Effect.gen(function* () {
227 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
228 yield* client.connect
229 .unlink({ headers: {} })
230 .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
231​
232 const configuredRelayUrl = relayUrl();
233 if (configuredRelayUrl && input.clerkToken) {
234 const relayClient = yield* ManagedRelay.ManagedRelayClient;
235 yield* relayClient
236 .unlinkEnvironment({
237 clerkToken: input.clerkToken,
238 environmentId: EnvironmentId.make(input.target.environmentId),
239 })
240 .pipe(
241 Effect.catch((cause) =>
242 Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
243 cause,
244 }),
245 ),
246 );
247 }
248 }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
250​
251// "publish_only" links the environment to the relay for agent-activity
252// publishing alone: no managed tunnel is provisioned, so it can be toggled
253// independently of T3 Connect while clients reach the environment out of band.
254export type CloudLinkMode = "managed" | "publish_only";
255​
256const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
257​
258export function linkPrimaryEnvironmentToCloud(input: {
259 readonly target: CloudLinkTarget;
260 readonly clerkToken: string;
261 readonly mode?: CloudLinkMode;
262}): Effect.Effect<
263 void,
264 CloudEnvironmentLinkError,
265 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
266> {
267 return Effect.gen(function* () {
268 const configuredRelayUrl = relayUrl();
269 if (!configuredRelayUrl) {
270 return yield* new CloudEnvironmentLinkError({
271 message: "T3CODE_RELAY_URL is not configured.",
272 });
273 }
274 const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
275 const providerKind = managedTunnelsEnabled
276 ? MANAGED_ENDPOINT_PROVIDER_KIND
277 : PUBLISH_ONLY_PROVIDER_KIND;
278 const relayClient = yield* ManagedRelay.ManagedRelayClient;
279 const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
280 if (managedTunnelsEnabled) {
281 yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
282 }
283​
284 const challenge = yield* relayClient
285 .createEnvironmentLinkChallenge({
286 clerkToken: input.clerkToken,
287 payload: {
288 notificationsEnabled: true,
289 liveActivitiesEnabled: true,
290 managedTunnelsEnabled,
291 },
292 })
293 .pipe(
294 Effect.mapError(
295 decodedRelayClientError(
296 `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
297 ),
298 ),
299 );
300 const proof = yield* environmentClient.connect
301 .linkProof({
302 headers: {},
303 payload: {
304 challenge: challenge.challenge,
305 relayIssuer: configuredRelayUrl,
306 endpoint: {
307 httpBaseUrl: input.target.httpBaseUrl,
308 wsBaseUrl: input.target.wsBaseUrl,
309 providerKind,
310 },
311 origin: endpointOrigin(input.target.httpBaseUrl),
312 },
313 })
314 .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
315 const link = yield* relayClient
316 .linkEnvironment({
317 clerkToken: input.clerkToken,
318 payload: {
319 proof,
320 notificationsEnabled: true,
321 liveActivitiesEnabled: true,
322 managedTunnelsEnabled,
323 },
324 })
325 .pipe(
326 Effect.mapError(
327 decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
328 ),
329 );
330 yield* ensureLinkedEnvironmentMatches({
331 expectedEnvironmentId: input.target.environmentId,
332 expectedProviderKind: providerKind,
333 link,
334 });
335​
336 yield* environmentClient.connect
337 .relayConfig({
338 headers: {},
339 payload: {
340 relayUrl: configuredRelayUrl,
341 relayIssuer: link.relayIssuer,
342 cloudUserId: link.cloudUserId,
343 environmentCredential: link.environmentCredential,
344 cloudMintPublicKey: link.cloudMintPublicKey,
345 endpointRuntime: link.endpointRuntime,
346 },
347 })
348 .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
349 }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));