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

useCloudLinkController.ts

244 lines9.2 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useAuth } from "@clerk/react";
3import { findErrorTraceId } from "@t3tools/client-runtime/errors";
4import {
5 AuthRelayReadScope,
6 AuthRelayWriteScope,
7 type EnvironmentCloudLinkStateResult,
8 type EnvironmentId,
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 { isCloudEnvironmentLinkError } from "./linkEnvironment";
25import { refreshManagedTunnelUsage } from "./managedRelayState";
26import {
27 linkEnvironment as linkEnvironmentAtom,
28 unlinkEnvironment as unlinkEnvironmentAtom,
29 updateEnvironmentPreferences as updateEnvironmentPreferencesAtom,
30} from "./linkEnvironmentAtoms";
31import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState";
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 (!isCloudEnvironmentLinkError(cause)) 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(environmentId: EnvironmentId | null) {
66 const { getToken, isSignedIn } = useAuth();
67 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
68 reportFailure: false,
69 });
70 const linkEnvironment = useAtomCommand(linkEnvironmentAtom, {
71 reportFailure: false,
72 });
73 const unlinkEnvironment = useAtomCommand(unlinkEnvironmentAtom, {
74 reportFailure: false,
75 });
76 const updateEnvironmentPreferences = useAtomCommand(updateEnvironmentPreferencesAtom, {
77 reportFailure: false,
78 });
79 const cloudLinkState = useCloudLinkState(environmentId);
80 const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments;
81 const relayProviderKind = environmentId
82 ? relayEnvironments.get(environmentId)?.environment.endpoint.providerKind
83 : undefined;
84 const [operationError, setOperationError] = useState<string | null>(null);
85 const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);
86​
87 const reportUpdateFailure = (cause: unknown) => {
88 const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
89 const traceId = findErrorTraceId(cause);
90 console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
91 setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
92 toastManager.add({
93 type: "error",
94 title: "Could not update T3 Connect",
95 description: message,
96 data: traceId
97 ? {
98 secondaryActionProps: {
99 children: "Copy trace ID",
100 onClick: () => void navigator.clipboard?.writeText(traceId),
101 },
102 }
103 : undefined,
104 });
105 };
106​
107 const linkData = cloudLinkState.data;
108 const linkRevoked = linkData?.linkRevoked ?? false;
109 const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false;
110 const managedTunnelOutOfSync =
111 linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined);
112 const publishAgentActivity = cloudLinkState.data?.publishAgentActivity ?? false;
113 const holdWebhooksWhileOffline = cloudLinkState.data?.holdWebhooksWhileOffline ?? false;
114 const linked = !linkRevoked && (cloudLinkState.data?.linked ?? false);
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("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("This connection needs permission to view and manage T3 Connect settings."),
132 );
133 return false;
134 }
135 return true;
136 };
137 const readLinkState = () => {
138 const state = readCachedCloudLinkState(target);
139 if (state === null) {
140 reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));
141 }
142 return state;
143 };
144 if (!canManageLink()) return false;
145 const wantsLink = desired.managedTunnel || desired.publish;
146 if (wantsLink && readLinkState() === null) return false;
147 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
148 if (!canManageLink()) return false;
149​
150 // A failed mutation may have partially applied, so refresh server state on every exit.
151 if (!wantsLink) {
152 // Unlink needs no relay token; failed token reads must still allow it.
153 const unlinkResult = await unlinkEnvironment({
154 target,
155 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
156 });
157 refreshManagedTunnelUsage();
158 if (unlinkResult._tag === "Failure") {
159 if (!isAtomCommandInterrupted(unlinkResult)) {
160 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
161 }
162 cloudLinkState.refresh();
163 return false;
164 }
165 } else {
166 const currentLinkState = readLinkState();
167 if (currentLinkState === null) return false;
168 if (tokenResult._tag === "Failure") {
169 reportUpdateFailure(squashAtomCommandFailure(tokenResult));
170 return false;
171 }
172 const clerkToken = tokenResult.value;
173 if (!clerkToken) {
174 reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
175 return false;
176 }
177 const currentManagedTunnel = isManagedTunnelActive(currentLinkState, relayProviderKind);
178 if (
179 !currentLinkState.linked ||
180 currentLinkState.linkRevoked === true ||
181 currentManagedTunnel !== desired.managedTunnel
182 ) {
183 const linkResult = await linkEnvironment({
184 target,
185 clerkToken,
186 mode: desired.managedTunnel ? "managed" : "publish_only",
187 });
188 // Any link attempt can change the account's tunnel count.
189 refreshManagedTunnelUsage();
190 if (linkResult._tag === "Failure") {
191 if (!isAtomCommandInterrupted(linkResult)) {
192 const cause = squashAtomCommandFailure(linkResult);
193 // The caller shows an upgrade prompt instead of an error.
194 const limit = tunnelLimitFromLinkFailure(cause);
195 if (limit === null) reportUpdateFailure(cause);
196 else setTunnelLimit(limit);
197 }
198 cloudLinkState.refresh();
199 return false;
200 }
201 }
202 if (!canManageLink() || readLinkState() === null) {
203 cloudLinkState.refresh();
204 return false;
205 }
206 const prefResult = await updateEnvironmentPreferences({
207 target,
208 publishAgentActivity: desired.publish,
209 ...(desired.holdWebhooksWhileOffline === undefined
210 ? {}
211 : { holdWebhooksWhileOffline: desired.holdWebhooksWhileOffline }),
212 });
213 if (prefResult._tag === "Failure") {
214 if (!isAtomCommandInterrupted(prefResult)) {
215 reportUpdateFailure(squashAtomCommandFailure(prefResult));
216 }
217 cloudLinkState.refresh();
218 return false;
219 }
220 }
221​
222 cloudLinkState.refresh();
223 const refreshResult = await refreshRelayEnvironments();
224 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
225 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
226 return false;
227 }
228 return true;
229 };
230​
231 return {
232 isSignedIn,
233 linkState: cloudLinkState,
234 linked,
235 linkRevoked,
236 managedTunnelActive,
237 managedTunnelOutOfSync,
238 publishAgentActivity,
239 holdWebhooksWhileOffline,
240 operationError,
241 tunnelLimit,
242 reconcileCloudState,
243 };