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

useCloudLinkController.browser.test.tsx

311 lines10.5 KB

1import {
2 AuthRelayReadScope,
3 AuthRelayWriteScope,
4 EnvironmentId,
5 type EnvironmentCloudLinkStateResult,
6} from "@t3tools/contracts";
7import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
8import { AsyncResult } from "effect/reactivity";
9import { act, useLayoutEffect } from "react";
10import { createRoot, type Root } from "react-dom/client";
11import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12​
13const testState = vi.hoisted(() => ({
14 scopes: new Set<string>(),
15 snapshot: null as EnvironmentCloudLinkStateResult | null,
16 renderedSnapshot: null as EnvironmentCloudLinkStateResult | null,
17 relayProviderKind: null as RelayManagedEndpointProviderKind | null,
18 getToken: vi.fn<() => Promise<string | null>>(),
19 link: vi.fn(),
20 unlink: vi.fn(),
21 preferences: vi.fn(),
22 refreshDiscovery: vi.fn(),
23 refreshLink: vi.fn(),
24 toast: vi.fn(),
25}));
26​
27vi.mock(import("@effect/atom-react"), async (original) => ({
28 ...(await original()),
29 useAtomValue: (() => ({
30 environments: new Map(
31 testState.relayProviderKind === null
32 ? []
33 : [
34 [
35 "primary",
36 { environment: { endpoint: { providerKind: testState.relayProviderKind } } },
37 ],
38 ],
39 ),
40 })) as never,
41}));
42vi.mock(import("@clerk/react"), async (original) => ({
43 ...(await original()),
44 useAuth: (() => ({ getToken: testState.getToken, isSignedIn: true })) as never,
45}));
46vi.mock(import("../components/ui/toast"), async (original) => {
47 const actual = await original();
48 return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } as never };
49});
50vi.mock(import("../state/relay"), async (original) => {
51 const actual = await original();
52 return {
53 ...actual,
54 relayEnvironmentDiscovery: {
55 ...actual.relayEnvironmentDiscovery,
56 refresh: testState.refreshDiscovery,
57 } as never,
58 };
59});
60vi.mock(import("../state/session"), async (original) => ({
61 ...(await original()),
62 readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
63}));
64vi.mock(import("../state/use-atom-command"), async (original) => ({
65 ...(await original()),
66 useAtomCommand: ((command: unknown) => command) as never,
67}));
68vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
69 ...(await original()),
70 linkPrimaryEnvironment: testState.link as never,
71 unlinkPrimaryEnvironment: testState.unlink as never,
72 updatePrimaryEnvironmentPreferences: testState.preferences as never,
73}));
74vi.mock(import("./primaryCloudLinkState"), async (original) => ({
75 ...(await original()),
76 readCachedPrimaryCloudLinkState: () => testState.snapshot,
77 usePrimaryCloudLinkState: (() => ({
78 target,
79 data: testState.renderedSnapshot,
80 error: null,
81 isPending: false,
82 refresh: testState.refreshLink,
83 })) as never,
84}));
85// The Clerk JWT template is build-time config the test environment does not set.
86vi.mock(import("./publicConfig"), async (original) => ({
87 ...(await original()),
88 resolveRelayClerkTokenOptions: () => ({}) as never,
89}));
90​
91import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
92​
93const target = {
94 environmentId: EnvironmentId.make("primary"),
95 label: "Primary",
96 httpBaseUrl: "http://localhost:3773",
97 wsBaseUrl: "ws://localhost:3773/ws",
98};
99const linkedState: EnvironmentCloudLinkStateResult = {
100 linked: true,
101 cloudUserId: "account-1",
102 relayUrl: "https://relay.example.com",
103 relayIssuer: "https://relay.example.com",
104 managedTunnelActive: true,
105 publishAgentActivity: false,
106};
107​
108let root: Root | null = null;
109let controller: ReturnType<typeof useCloudLinkController> | null = null;
110​
111function ControllerProbe() {
112 const value = useCloudLinkController();
113 useLayoutEffect(() => {
114 controller = value;
115 });
116 return null;
118​
119async function mountController() {
120 root = createRoot(document.createElement("div"));
121 await act(async () => root!.render(<ControllerProbe />));
123​
124async function reconcile(desired: CloudLinkDesiredState) {
125 let succeeded = false;
126 await act(async () => {
127 if (controller === null) throw new Error("Controller is not mounted.");
128 succeeded = await controller.reconcileCloudState(desired);
129 });
130 return succeeded;
132​
133function expectNoMutations() {
134 expect(testState.link).not.toHaveBeenCalled();
135 expect(testState.unlink).not.toHaveBeenCalled();
136 expect(testState.preferences).not.toHaveBeenCalled();
138​
139beforeEach(() => {
140 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
141 vi.spyOn(console, "error").mockImplementation(() => undefined);
142 testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
143 testState.snapshot = linkedState;
144 testState.renderedSnapshot = linkedState;
145 testState.relayProviderKind = null;
146 testState.getToken.mockReset().mockResolvedValue("clerk-token");
147 for (const command of [
148 testState.link,
149 testState.unlink,
150 testState.preferences,
151 testState.refreshDiscovery,
152 ]) {
153 command.mockReset().mockResolvedValue(AsyncResult.success({}));
154 }
155 testState.refreshLink.mockReset();
156 testState.toast.mockReset();
157});
158​
159afterEach(async () => {
160 await act(async () => root?.unmount());
161 root = null;
162 controller = null;
163 vi.restoreAllMocks();
164 vi.unstubAllGlobals();
165});
166​
167describe("useCloudLinkController", () => {
168 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
169 "does not mutate without %s, even with a cached link snapshot",
170 async (scope) => {
171 await mountController();
172 testState.scopes.delete(scope);
173​
174 expect(await reconcile({ managedTunnel: true, publish: true })).toBe(false);
175 expect(testState.getToken).not.toHaveBeenCalled();
176 expectNoMutations();
177 },
178 );
179​
180 it("does not interpret unavailable link state as an unlinked environment", async () => {
181 testState.snapshot = null;
182 await mountController();
183​
184 expect(await reconcile({ managedTunnel: false, publish: true })).toBe(false);
185 expect(testState.getToken).not.toHaveBeenCalled();
186 expectNoMutations();
187 });
188​
189 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
190 "rechecks %s after requesting the cloud token",
191 async (scope) => {
192 await mountController();
193 testState.getToken.mockImplementationOnce(async () => {
194 testState.scopes.delete(scope);
195 return "clerk-token";
196 });
197​
198 expect(await reconcile({ managedTunnel: false, publish: false })).toBe(false);
199 expectNoMutations();
200 },
201 );
202​
203 it("stops if the link-state read fails while requesting the cloud token", async () => {
204 await mountController();
205 testState.getToken.mockImplementationOnce(async () => {
206 testState.snapshot = null;
207 return "clerk-token";
208 });
209​
210 expect(await reconcile({ managedTunnel: true, publish: true })).toBe(false);
211 expectNoMutations();
212 });
213​
214 it("uses the latest linked mode to change publishing without replacing the tunnel", async () => {
215 testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false };
216 testState.renderedSnapshot = testState.snapshot;
217 await mountController();
218 testState.getToken.mockImplementationOnce(async () => {
219 testState.snapshot = linkedState;
220 return "clerk-token";
221 });
222​
223 expect(await reconcile({ managedTunnel: true, publish: true })).toBe(true);
224 expect(testState.link).not.toHaveBeenCalled();
225 expect(testState.unlink).not.toHaveBeenCalled();
226 expect(testState.preferences).toHaveBeenCalledExactlyOnceWith({
227 target,
228 publishAgentActivity: true,
229 });
230 });
231​
232 it("shows a link the relay holds as publish-only as off and relinks it as managed", async () => {
233 testState.relayProviderKind = "manual";
234 await mountController();
235​
236 expect(controller?.managedTunnelActive).toBe(false);
237 expect(controller?.managedTunnelOutOfSync).toBe(true);
238 expect(await reconcile({ managedTunnel: true, publish: false })).toBe(true);
239 expect(testState.link).toHaveBeenCalledExactlyOnceWith({
240 target,
241 clerkToken: "clerk-token",
242 mode: "managed",
243 });
244 });
245​
246 it("shows a revoked link as off and links it again when turned on", async () => {
247 testState.snapshot = { ...linkedState, linkRevoked: true };
248 testState.renderedSnapshot = testState.snapshot;
249 await mountController();
250 expect(controller).toMatchObject({
251 linked: false,
252 linkRevoked: true,
253 managedTunnelActive: false,
254 managedTunnelOutOfSync: false,
255 });
256​
257 expect(await reconcile({ managedTunnel: true, publish: false })).toBe(true);
258 expect(testState.link).toHaveBeenCalledExactlyOnceWith({
259 target,
260 clerkToken: "clerk-token",
261 mode: "managed",
262 });
263 });
264​
265 it("keeps a managed link that the relay also holds as managed", async () => {
266 testState.relayProviderKind = "cloudflare_tunnel";
267 await mountController();
268​
269 expect(controller?.managedTunnelActive).toBe(true);
270 expect(controller?.managedTunnelOutOfSync).toBe(false);
271 expect(await reconcile({ managedTunnel: true, publish: false })).toBe(true);
272 expect(testState.link).not.toHaveBeenCalled();
273 });
274​
275 it("stops the preference write if management permission is lost after linking", async () => {
276 await mountController();
277 testState.link.mockImplementationOnce(async () => {
278 testState.scopes.delete(AuthRelayWriteScope);
279 return AsyncResult.success({});
280 });
281​
282 expect(await reconcile({ managedTunnel: false, publish: true })).toBe(false);
283 expect(testState.link).toHaveBeenCalledOnce();
284 expect(testState.preferences).not.toHaveBeenCalled();
285 expect(testState.refreshLink).toHaveBeenCalledOnce();
286 });
287​
288 it("still lets an authorized user unlink when the cloud token is unavailable", async () => {
289 await mountController();
290 testState.getToken.mockRejectedValueOnce(new Error("Cloud sign-in unavailable"));
291​
292 expect(await reconcile({ managedTunnel: false, publish: false })).toBe(true);
293 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
294 expect(testState.link).not.toHaveBeenCalled();
295 expect(testState.preferences).not.toHaveBeenCalled();
296 });
297​
298 it("unlinks if the link-state read fails while requesting the cloud token", async () => {
299 await mountController();
300 testState.getToken.mockImplementationOnce(async () => {
301 testState.snapshot = null;
302 throw new Error("Cloud sign-in unavailable");
303 });
304​
305 expect(await reconcile({ managedTunnel: false, publish: false })).toBe(true);
306 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
307 expect(testState.link).not.toHaveBeenCalled();
308 expect(testState.preferences).not.toHaveBeenCalled();
309 expect(testState.refreshLink).toHaveBeenCalledOnce();
310 });
311});