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

useCloudLinkController.ts

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