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

useCloudLinkController.ts

220 lines8.3 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 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;
35​
36// Require managed discovery: stale tunnel config after a publish-only switch causes endpoint_provider_not_managed.
37function isManagedTunnelActive(
38 linkState: EnvironmentCloudLinkStateResult,
39 relayProviderKind: RelayManagedEndpointProviderKind | undefined,
40) {
41 const localManagedTunnel = linkState.managedTunnelActive ?? linkState.linked;
42 return (
43 linkState.linkRevoked !== true &&
44 localManagedTunnel &&
45 (relayProviderKind === undefined || relayProviderKind === "cloudflare_tunnel")
46 );
48​
49export function useCloudLinkController() {
50 const { getToken, isSignedIn } = useAuth();
51 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
52 reportFailure: false,
53 });
54 const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
55 reportFailure: false,
56 });
57 const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
58 reportFailure: false,
59 });
60 const updatePrimaryEnvironmentPreferences = useAtomCommand(
61 updatePrimaryEnvironmentPreferencesAtom,
62 { reportFailure: false },
63 );
64 const primaryCloudLinkState = usePrimaryCloudLinkState();
65 const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments;
66 const primaryEnvironmentId = primaryCloudLinkState.target?.environmentId;
67 const relayProviderKind = primaryEnvironmentId
68 ? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind
69 : undefined;
70 const [operationError, setOperationError] = useState<string | null>(null);
71​
72 const reportUpdateFailure = (cause: unknown) => {
73 const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
74 const traceId = findErrorTraceId(cause);
75 console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
76 setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
77 toastManager.add({
78 type: "error",
79 title: "Could not update T3 Connect",
80 description: message,
81 data: traceId
82 ? {
83 secondaryActionProps: {
84 children: "Copy trace ID",
85 onClick: () => void navigator.clipboard?.writeText(traceId),
86 },
87 }
88 : undefined,
89 });
90 };
91​
92 const linkData = primaryCloudLinkState.data;
93 const linkRevoked = linkData?.linkRevoked ?? false;
94 const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false;
95 const managedTunnelOutOfSync =
96 linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined);
97 const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
98 const holdWebhooksWhileOffline = primaryCloudLinkState.data?.holdWebhooksWhileOffline ?? false;
99 const linked = !linkRevoked && (primaryCloudLinkState.data?.linked ?? false);
100​
101 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
102 setOperationError(null);
103 const target = primaryCloudLinkState.target;
104 if (!target) {
105 reportUpdateFailure(new Error("Local environment is not ready yet."));
106 return false;
107 }
108 const environmentId = EnvironmentId.make(target.environmentId);
109 const canManageLink = () => {
110 if (
111 !readEnvironmentScope(environmentId, AuthRelayReadScope) ||
112 !readEnvironmentScope(environmentId, AuthRelayWriteScope)
113 ) {
114 reportUpdateFailure(
115 new Error("This connection needs permission to view and manage T3 Connect settings."),
116 );
117 return false;
118 }
119 return true;
120 };
121 const readLinkState = () => {
122 const state = readCachedPrimaryCloudLinkState(target);
123 if (state === null) {
124 reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));
125 }
126 return state;
127 };
128 if (!canManageLink()) return false;
129 const wantsLink = desired.managedTunnel || desired.publish;
130 if (wantsLink && readLinkState() === null) return false;
131 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
132 if (!canManageLink()) return false;
133​
134 // A failed mutation may have partially applied, so refresh server state on every exit.
135 if (!wantsLink) {
136 // Unlink needs no relay token; failed token reads must still allow it.
137 const unlinkResult = await unlinkPrimaryEnvironment({
138 target,
139 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
140 });
141 if (unlinkResult._tag === "Failure") {
142 if (!isAtomCommandInterrupted(unlinkResult)) {
143 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
144 }
145 primaryCloudLinkState.refresh();
146 return false;
147 }
148 } else {
149 const currentLinkState = readLinkState();
150 if (currentLinkState === null) return false;
151 if (tokenResult._tag === "Failure") {
152 reportUpdateFailure(squashAtomCommandFailure(tokenResult));
153 return false;
154 }
155 const clerkToken = tokenResult.value;
156 if (!clerkToken) {
157 reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
158 return false;
159 }
160 const currentManagedTunnel = isManagedTunnelActive(currentLinkState, relayProviderKind);
161 if (
162 !currentLinkState.linked ||
163 currentLinkState.linkRevoked === true ||
164 currentManagedTunnel !== desired.managedTunnel
165 ) {
166 const linkResult = await linkPrimaryEnvironment({
167 target,
168 clerkToken,
169 mode: desired.managedTunnel ? "managed" : "publish_only",
170 });
171 if (linkResult._tag === "Failure") {
172 if (!isAtomCommandInterrupted(linkResult)) {
173 reportUpdateFailure(squashAtomCommandFailure(linkResult));
174 }
175 primaryCloudLinkState.refresh();
176 return false;
177 }
178 }
179 if (!canManageLink() || readLinkState() === null) {
180 primaryCloudLinkState.refresh();
181 return false;
182 }
183 const prefResult = await updatePrimaryEnvironmentPreferences({
184 target,
185 publishAgentActivity: desired.publish,
186 ...(desired.holdWebhooksWhileOffline === undefined
187 ? {}
188 : { holdWebhooksWhileOffline: desired.holdWebhooksWhileOffline }),
189 });
190 if (prefResult._tag === "Failure") {
191 if (!isAtomCommandInterrupted(prefResult)) {
192 reportUpdateFailure(squashAtomCommandFailure(prefResult));
193 }
194 primaryCloudLinkState.refresh();
195 return false;
196 }
197 }
198​
199 primaryCloudLinkState.refresh();
200 const refreshResult = await refreshRelayEnvironments();
201 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
202 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
203 return false;
204 }
205 return true;
206 };
207​
208 return {
209 isSignedIn,
210 linkState: primaryCloudLinkState,
211 linked,
212 linkRevoked,
213 managedTunnelActive,
214 managedTunnelOutOfSync,
215 publishAgentActivity,
216 holdWebhooksWhileOffline,
217 operationError,
218 reconcileCloudState,
219 };