Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useAuth } from "@clerk/react";
3import { findErrorTraceId } from "@t3tools/client-runtime/errors";
4import {
5 EnvironmentId,
6 AuthRelayReadScope,
7 AuthRelayWriteScope,
8 type EnvironmentCloudLinkStateResult,
9} from "@t3tools/contracts";
10import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
11import {
12 isAtomCommandInterrupted,
13 settlePromise,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import { useState } from "react";
17
18import { toastManager } from "../components/ui/toast";
19import { relayEnvironmentDiscovery } from "../state/relay";
20import { readEnvironmentScope } from "../state/session";
21import { useAtomCommand } from "../state/use-atom-command";
22import {
23 linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
24 unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
25 updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
26} from "./linkEnvironmentAtoms";
27import { readCachedPrimaryCloudLinkState, usePrimaryCloudLinkState } from "./primaryCloudLinkState";
28import { resolveRelayClerkTokenOptions } from "./publicConfig";
29
30export interface CloudLinkDesiredState {
31 readonly managedTunnel: boolean;
32 readonly publish: boolean;
33 readonly holdWebhooksWhileOffline?: boolean;
34}
35
36/**
37 * The local tunnel config can outlive a relay link that drifted to
38 * publish-only, and clients then get `endpoint_provider_not_managed`. So when
39 * relay discovery has this environment's record, it must also say managed.
40 */
41function isManagedTunnelActive(
42 linkState: EnvironmentCloudLinkStateResult,
43 relayProviderKind: RelayManagedEndpointProviderKind | undefined,
44) {
45 const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked;
46 return (
47 linkState.linkRevoked !== true &&
48 localManagedTunnel &&
49 (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel")
50 );
51}
52
53export function useCloudLinkController() {
54 const { getToken, isSignedIn } = useAuth();
55 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
56 reportFailure: false,
57 });
58 const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
59 reportFailure: false,
60 });
61 const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
62 reportFailure: false,
63 });
64 const updatePrimaryEnvironmentPreferences = useAtomCommand(
65 updatePrimaryEnvironmentPreferencesAtom,
66 { reportFailure: false },
67 );
68 const primaryCloudLinkState = usePrimaryCloudLinkState();
69 const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments;
70 const primaryEnvironmentId = primaryCloudLinkState.target?.environmentId;
71 const relayProviderKind = primaryEnvironmentId
72 ? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind
73 : undefined;
74 const [operationError, setOperationError] = useState<string | null>(null);
75
76 const reportUpdateFailure = (cause: unknown) => {
77 const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
78 const traceId = findErrorTraceId(cause);
79 console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
80 setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
81 toastManager.add({
82 type: "error",
83 title: "Could not update T3 Connect",
84 description: message,
85 data: traceId
86 ? {
87 secondaryActionProps: {
88 children: "Copy trace ID",
89 onClick: () => void navigator.clipboard?.writeText(traceId),
90 },
91 }
92 : undefined,
93 });
94 };
95
96 const linkData = primaryCloudLinkState.data;
97 const linkRevoked = linkData?.linkRevoked ?? false;
98 const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false;
99 const managedTunnelOutOfSync =
100 linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined);
101 const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
102 const holdWebhooksWhileOffline = primaryCloudLinkState.data?.holdWebhooksWhileOffline ?? false;
103 const linked = !linkRevoked && (primaryCloudLinkState.data?.linked ?? false);
104
105 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
106 setOperationError(null);
107 const target = primaryCloudLinkState.target;
108 if (!target) {
109 reportUpdateFailure(new Error("Local environment is not ready yet."));
110 return false;
111 }
112 const environmentId = EnvironmentId.make(target.environmentId);
113 const canManageLink = () => {
114 if (
115 !readEnvironmentScope(environmentId, AuthRelayReadScope) ||
116 !readEnvironmentScope(environmentId, AuthRelayWriteScope)
117 ) {
118 reportUpdateFailure(
119 new Error("This connection needs permission to view and manage T3 Connect settings."),
120 );
121 return false;
122 }
123 return true;
124 };
125 const readLinkState = () => {
126 const state = readCachedPrimaryCloudLinkState(target);
127 if (state === null) {
128 reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));
129 }
130 return state;
131 };
132 if (!canManageLink()) return false;
133 const wantsLink = desired.managedTunnel || desired.publish;
134 if (wantsLink && readLinkState() === null) return false;
135 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
136 if (!canManageLink()) return false;
137
138 // A failure after this point may follow a partially applied mutation (e.g.
139 // the link succeeded but the preference update did not), so every exit —
140 // success or failure — refreshes the rendered state to whatever the server
141 // actually holds now.
142 if (!wantsLink) {
143 // Unlink works without a relay token — a failed token read must not
144 // leave the user unable to turn T3 Connect off.
145 const unlinkResult = await unlinkPrimaryEnvironment({
146 target,
147 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
148 });
149 if (unlinkResult._tag === "Failure") {
150 if (!isAtomCommandInterrupted(unlinkResult)) {
151 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
152 }
153 primaryCloudLinkState.refresh();
154 return false;
155 }
156 } else {
157 const currentLinkState = readLinkState();
158 if (currentLinkState === null) return false;
159 if (tokenResult._tag === "Failure") {
160 reportUpdateFailure(squashAtomCommandFailure(tokenResult));
161 return false;
162 }
163 const clerkToken = tokenResult.value;
164 if (!clerkToken) {
165 reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
166 return false;
167 }
168 const currentManagedTunnel = isManagedTunnelActive(currentLinkState, relayProviderKind);
169 if (
170 !currentLinkState.linked ||
171 currentLinkState.linkRevoked === true ||
172 currentManagedTunnel !== desired.managedTunnel
173 ) {
174 const linkResult = await linkPrimaryEnvironment({
175 target,
176 clerkToken,
177 mode: desired.managedTunnel ? "managed" : "publish_only",
178 });
179 if (linkResult._tag === "Failure") {
180 if (!isAtomCommandInterrupted(linkResult)) {
181 reportUpdateFailure(squashAtomCommandFailure(linkResult));
182 }
183 primaryCloudLinkState.refresh();
184 return false;
185 }
186 }
187 if (!canManageLink() || readLinkState() === null) {
188 primaryCloudLinkState.refresh();
189 return false;
190 }
191 const prefResult = await updatePrimaryEnvironmentPreferences({
192 target,
193 publishAgentActivity: desired.publish,
194 ...(desired.holdWebhooksWhileOffline === undefined
195 ? {}
196 : { holdWebhooksWhileOffline: desired.holdWebhooksWhileOffline }),
197 });
198 if (prefResult._tag === "Failure") {
199 if (!isAtomCommandInterrupted(prefResult)) {
200 reportUpdateFailure(squashAtomCommandFailure(prefResult));
201 }
202 primaryCloudLinkState.refresh();
203 return false;
204 }
205 }
206
207 primaryCloudLinkState.refresh();
208 const refreshResult = await refreshRelayEnvironments();
209 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
210 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
211 return false;
212 }
213 return true;
214 };
215
216 return {
217 isSignedIn,
218 linkState: primaryCloudLinkState,
219 linked,
220 linkRevoked,
221 managedTunnelActive,
222 managedTunnelOutOfSync,
223 publishAgentActivity,
224 holdWebhooksWhileOffline,
225 operationError,
226 reconcileCloudState,
227 };
228}