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

useCloudLinkController.ts

246 lines9.5 KB

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