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

useCloudLinkController.ts

163 lines6.2 KB

1import { useAuth } from "@clerk/react";
2import { findErrorTraceId } from "@t3tools/client-runtime/errors";
3import {
4 isAtomCommandInterrupted,
5 settlePromise,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { useState } from "react";
9​
10import { toastManager } from "../components/ui/toast";
11import { relayEnvironmentDiscovery } from "../state/relay";
12import { useAtomCommand } from "../state/use-atom-command";
13import {
14 linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
15 unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
16 updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
17} from "./linkEnvironmentAtoms";
18import { usePrimaryCloudLinkState } from "./primaryCloudLinkState";
19import { resolveRelayClerkTokenOptions } from "./publicConfig";
20​
21export interface CloudLinkDesiredState {
22 readonly managedTunnel: boolean;
23 readonly publish: boolean;
25​
26/**
27 * Drives the primary environment's T3 Connect link. T3 Connect (managed
28 * tunnel) and agent-activity publishing are independent capabilities backed by
29 * a single relay link, so consumers express the full desired state and
30 * `reconcileCloudState` applies it: unlink when neither is wanted, otherwise
31 * (re)link with the mode the managed-tunnel bit implies and set the publish
32 * preference. Re-linking only happens when the managed-tunnel mode actually
33 * changes, so flipping publish alone is cheap.
34 */
35export function useCloudLinkController() {
36 const { getToken, isSignedIn } = useAuth();
37 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
38 reportFailure: false,
39 });
40 const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
41 reportFailure: false,
42 });
43 const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
44 reportFailure: false,
45 });
46 const updatePrimaryEnvironmentPreferences = useAtomCommand(
47 updatePrimaryEnvironmentPreferencesAtom,
48 { reportFailure: false },
49 );
50 const primaryCloudLinkState = usePrimaryCloudLinkState();
51 const [operationError, setOperationError] = useState<string | null>(null);
52​
53 const reportUpdateFailure = (cause: unknown) => {
54 const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
55 const traceId = findErrorTraceId(cause);
56 console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
57 setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
58 toastManager.add({
59 type: "error",
60 title: "Could not update T3 Connect",
61 description: message,
62 data: traceId
63 ? {
64 secondaryActionProps: {
65 children: "Copy trace ID",
66 onClick: () => void navigator.clipboard?.writeText(traceId),
67 },
68 }
69 : undefined,
70 });
71 };
72​
73 // Older environment servers predate the managedTunnelActive field; for them a
74 // link always implies a managed tunnel, so fall back to `linked`.
75 const managedTunnelActive =
76 primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
77 const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
78 const linked = primaryCloudLinkState.data?.linked ?? false;
79​
80 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
81 setOperationError(null);
82 const target = primaryCloudLinkState.target;
83 if (!target) {
84 reportUpdateFailure(new Error("Local environment is not ready yet."));
85 return false;
86 }
87 const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
88 const wantsLink = desired.managedTunnel || desired.publish;
89​
90 // A failure after this point may follow a partially applied mutation (e.g.
91 // the link succeeded but the preference update did not), so every exit —
92 // success or failure — refreshes the rendered state to whatever the server
93 // actually holds now.
94 if (!wantsLink) {
95 // Unlink works without a relay token — a failed token read must not
96 // leave the user unable to turn T3 Connect off.
97 const unlinkResult = await unlinkPrimaryEnvironment({
98 target,
99 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
100 });
101 if (unlinkResult._tag === "Failure") {
102 if (!isAtomCommandInterrupted(unlinkResult)) {
103 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
104 }
105 primaryCloudLinkState.refresh();
106 return false;
107 }
108 } else {
109 if (tokenResult._tag === "Failure") {
110 reportUpdateFailure(squashAtomCommandFailure(tokenResult));
111 return false;
112 }
113 const clerkToken = tokenResult.value;
114 if (!clerkToken) {
115 reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
116 return false;
117 }
118 if (!linked || managedTunnelActive !== desired.managedTunnel) {
119 const linkResult = await linkPrimaryEnvironment({
120 target,
121 clerkToken,
122 mode: desired.managedTunnel ? "managed" : "publish_only",
123 });
124 if (linkResult._tag === "Failure") {
125 if (!isAtomCommandInterrupted(linkResult)) {
126 reportUpdateFailure(squashAtomCommandFailure(linkResult));
127 }
128 primaryCloudLinkState.refresh();
129 return false;
130 }
131 }
132 const prefResult = await updatePrimaryEnvironmentPreferences({
133 target,
134 publishAgentActivity: desired.publish,
135 });
136 if (prefResult._tag === "Failure") {
137 if (!isAtomCommandInterrupted(prefResult)) {
138 reportUpdateFailure(squashAtomCommandFailure(prefResult));
139 }
140 primaryCloudLinkState.refresh();
141 return false;
142 }
143 }
144​
145 primaryCloudLinkState.refresh();
146 const refreshResult = await refreshRelayEnvironments();
147 if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
148 reportUpdateFailure(squashAtomCommandFailure(refreshResult));
149 return false;
150 }
151 return true;
152 };
153​
154 return {
155 isSignedIn,
156 linkState: primaryCloudLinkState,
157 linked,
158 managedTunnelActive,
159 publishAgentActivity,
160 operationError,
161 reconcileCloudState,
162 };