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

useCloudLinkController.ts

266 lines10.3 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useAuth } from "@clerk/react";
3import { findErrorTraceId, thrownErrorMessage } from "@t3tools/client-runtime/errors";
4import { AuthRelayReadScope, AuthRelayWriteScope, type EnvironmentId } from "@t3tools/contracts";
5import { ManagedRelay } from "@t3tools/client-runtime/relay";
6import {
7 isAtomCommandInterrupted,
8 settlePromise,
9 squashAtomCommandFailure,
10} from "@t3tools/client-runtime/state/runtime";
11import * as Schema from "effect/Schema";
12import { useState } from "react";
13import { msg } from "gt-react";
14​
15import { toastManager } from "../components/ui/toast";
16import { m } from "../i18n/messages";
17import { stackedThreadToast } from "../components/ui/toastHelpers";
18import { relayFailureReason } from "./relayFailureReason";
19import { relayEnvironmentDiscovery } from "../state/relay";
20import {
21 readEnvironmentCanConfigureRelay,
22 readEnvironmentScope,
23 useEnvironmentCanConfigureRelay,
24} from "../state/session";
25import { useAtomCommand } from "../state/use-atom-command";
26import { isCloudEnvironmentLinkError } from "./linkEnvironment";
27import { refreshManagedTunnelUsage } from "./managedRelayState";
28import {
29 linkEnvironment as linkEnvironmentAtom,
30 unlinkEnvironment as unlinkEnvironmentAtom,
31 updateEnvironmentPreferences as updateEnvironmentPreferencesAtom,
32} from "./linkEnvironmentAtoms";
33import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState";
34import { resolveRelayClerkTokenOptions } from "./publicConfig";
35import { cloudChangeReplacesLink, isManagedTunnelActive } from "./t3ConnectState";
36​
37export interface CloudLinkDesiredState {
38 readonly managedTunnel: boolean;
39 readonly publish: boolean;
40 readonly holdWebhooksWhileOffline?: boolean;
42​
43const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
44const isManagedRelayClientError = Schema.is(ManagedRelay.ManagedRelayClientError);
45​
46/** The account's tunnel cap when the relay refused a new tunnel for being at it. */
47function tunnelLimitFromLinkFailure(cause: unknown): number | null {
48 if (!isCloudEnvironmentLinkError(cause)) return null;
49 const relayCause = cause.cause;
50 if (!isManagedRelayRequestFailedError(relayCause)) return null;
51 return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError"
52 ? relayCause.relayError.maxTunnels
53 : null;
55​
56export function useCloudLinkController(environmentId: EnvironmentId | null) {
57 const { getToken, isSignedIn } = useAuth();
58 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
59 reportFailure: false,
60 });
61 const linkEnvironment = useAtomCommand(linkEnvironmentAtom, {
62 reportFailure: false,
63 });
64 const unlinkEnvironment = useAtomCommand(unlinkEnvironmentAtom, {
65 reportFailure: false,
66 });
67 const updateEnvironmentPreferences = useAtomCommand(updateEnvironmentPreferencesAtom, {
68 reportFailure: false,
69 });
70 const cloudLinkState = useCloudLinkState(environmentId);
71 const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments;
72 const relayProviderKind = environmentId
73 ? relayEnvironments.get(environmentId)?.environment.endpoint.providerKind
74 : undefined;
75 const [operationError, setOperationError] = useState<string | null>(null);
76 const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);
77​
78 const reportUpdateFailure = (cause: unknown, reason?: string) => {
79 const message = thrownErrorMessage(cause, m) ?? m(msg("Could not update T3 Connect access."));
80 const traceId = findErrorTraceId(cause);
81 console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
82 setOperationError(traceId ? m(msg`${{ message }} Trace ID: ${{ traceId }}`) : message);
83 toastManager.add(
84 stackedThreadToast({
85 type: "error",
86 title: m(msg("Could not update T3 Connect")),
87 description: reason ?? relayFailureReason(cause) ?? message,
88 ...(traceId
89 ? {
90 actionProps: {
91 children: m(msg("Copy trace ID")),
92 onClick: () => void navigator.clipboard?.writeText(traceId),
93 },
94 actionVariant: "outline",
95 }
96 : {}),
97 data: { hideCopyButton: true },
98 }),
99 );
100 };
101​
102 const linkData = cloudLinkState.data;
103 const linkRevoked = linkData?.linkRevoked ?? false;
104 const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false;
105 const managedTunnelOutOfSync =
106 linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined);
107 const publishAgentActivity = cloudLinkState.data?.publishAgentActivity ?? false;
108 const holdWebhooksWhileOffline = cloudLinkState.data?.holdWebhooksWhileOffline ?? false;
109 const linked = !linkRevoked && (cloudLinkState.data?.linked ?? false);
110 const canConfigureRelay = useEnvironmentCanConfigureRelay(environmentId);
111 const needsRelayConfiguration = (desired: CloudLinkDesiredState) =>
112 !canConfigureRelay &&
113 linkData !== null &&
114 cloudChangeReplacesLink(linkData, relayProviderKind, desired);
115​
116 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
117 setOperationError(null);
118 setTunnelLimit(null);
119 const target = cloudLinkState.target;
120 if (!target) {
121 reportUpdateFailure(new Error(m(msg("Choose an environment first."))));
122 return false;
123 }
124 const environmentId = target.environmentId;
125 const canManageLink = () => {
126 if (
127 !readEnvironmentScope(environmentId, AuthRelayReadScope) ||
128 !readEnvironmentScope(environmentId, AuthRelayWriteScope)
129 ) {
130 reportUpdateFailure(
131 new Error(
132 m(msg("This connection needs permission to view and manage T3 Connect settings.")),
133 ),
134 );
135 return false;
136 }
137 return true;
138 };
139 const readLinkState = () => {
140 const state = readCachedCloudLinkState(target);
141 if (state === null) {
142 reportUpdateFailure(
143 new Error(m(msg("Wait until the current T3 Connect settings can be read."))),
144 );
145 }
146 return state;
147 };
148 if (!canManageLink()) return false;
149 const wantsLink = desired.managedTunnel || desired.publish;
150 if (wantsLink && readLinkState() === null) return false;
151 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
152 if (!canManageLink()) return false;
153​
154 // A failed mutation may have partially applied, so refresh server state on every exit.
155 if (!wantsLink) {
156 // Unlink needs no relay token; failed token reads must still allow it.
157 const unlinkResult = await unlinkEnvironment({
158 target,
159 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
160 });
161 refreshManagedTunnelUsage();
162 if (unlinkResult._tag === "Failure") {
163 if (!isAtomCommandInterrupted(unlinkResult)) {
164 const cause = squashAtomCommandFailure(unlinkResult);
165 // Only the relay delete fails with a relay error, and it runs after the local unlink.
166 const relayKeptLink =
167 isCloudEnvironmentLinkError(cause) && isManagedRelayClientError(cause.cause);
168 reportUpdateFailure(
169 cause,
170 relayKeptLink
171 ? m(msg("Disconnected here, but T3 Connect still lists it. Remove it in Account."))
172 : undefined,
173 );
174 }
175 cloudLinkState.refresh();
176 await refreshRelayEnvironments();
177 return false;
178 }
179 } else {
180 const currentLinkState = readLinkState();
181 if (currentLinkState === null) return false;
182 if (tokenResult._tag === "Failure") {
183 reportUpdateFailure(squashAtomCommandFailure(tokenResult));
184 return false;
185 }
186 const clerkToken = tokenResult.value;
187 if (!clerkToken) {
188 reportUpdateFailure(new Error(m(msg("Sign in to T3 Connect before enabling this."))));
189 return false;
190 }
191 if (cloudChangeReplacesLink(currentLinkState, relayProviderKind, desired)) {
192 if (!readEnvironmentCanConfigureRelay(environmentId)) {
193 reportUpdateFailure(
194 new Error(
195 m(
196 msg(
197 "This connection needs the relay configuration permission to configure T3 Connect.",
198 ),
199 ),
200 ),
201 );
202 return false;
203 }
204 const linkResult = await linkEnvironment({
205 target,
206 clerkToken,
207 mode: desired.managedTunnel ? "managed" : "publish_only",
208 });
209 // Any link attempt can change the account's tunnel count.
210 refreshManagedTunnelUsage();
211 if (linkResult._tag === "Failure") {
212 if (!isAtomCommandInterrupted(linkResult)) {
213 const cause = squashAtomCommandFailure(linkResult);
214 // The caller shows an upgrade prompt instead of an error.
215 const limit = tunnelLimitFromLinkFailure(cause);
216 if (limit === null) reportUpdateFailure(cause);
217 else setTunnelLimit(limit);
218 }
219 cloudLinkState.refresh();
220 return false;
221 }
222 }
223 if (!canManageLink() || readLinkState() === null) {
224 cloudLinkState.refresh();
225 return false;
226 }
227 const prefResult = await updateEnvironmentPreferences({
228 target,
229 publishAgentActivity: desired.publish,
230 ...(desired.holdWebhooksWhileOffline === undefined
231 ? {}
232 : { holdWebhooksWhileOffline: desired.holdWebhooksWhileOffline }),
233 });
234 if (prefResult._tag === "Failure") {
235 if (!isAtomCommandInterrupted(prefResult)) {
236 reportUpdateFailure(squashAtomCommandFailure(prefResult));
237 }
238 cloudLinkState.refresh();
239 return false;
240 }
241 }
242​
243 cloudLinkState.refresh();
244 const refreshResult = await refreshRelayEnvironments();
245 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
246 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
247 return false;
248 }
249 return true;
250 };
251​
252 return {
253 isSignedIn,
254 linkState: cloudLinkState,
255 linked,
256 linkRevoked,
257 managedTunnelActive,
258 managedTunnelOutOfSync,
259 publishAgentActivity,
260 holdWebhooksWhileOffline,
261 operationError,
262 tunnelLimit,
263 needsRelayConfiguration,
264 reconcileCloudState,
265 };