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

useCloudLinkController.browser.test.tsx

262 lines8.7 KB

1import {
2 AuthRelayReadScope,
3 AuthRelayWriteScope,
4 EnvironmentId,
5 type EnvironmentCloudLinkStateResult,
6} from "@t3tools/contracts";
7import { ManagedRelay } from "@t3tools/client-runtime/relay";
8import {
9 RelayEnvironmentLinkLimitExceededError,
10 type RelayManagedEndpointProviderKind,
11} from "@t3tools/contracts/relay";
12import * as Cause from "effect/Cause";
13import { AsyncResult } from "effect/reactivity";
14import { useLayoutEffect } from "react";
15import { describe, expect, it, vi } from "vite-plus/test";
16​
17import { act, render } from "../../test/render";
18​
19const testState = vi.hoisted(() => ({
20 scopes: new Set<string>(),
21 snapshot: null as EnvironmentCloudLinkStateResult | null,
22 renderedSnapshot: null as EnvironmentCloudLinkStateResult | null,
23 relayProviderKind: null as RelayManagedEndpointProviderKind | null,
24 getToken: vi.fn<() => Promise<string | null>>(),
25 link: vi.fn(),
26 unlink: vi.fn(),
27 preferences: vi.fn(),
28 refreshDiscovery: vi.fn(),
29 refreshLink: vi.fn(),
30 toast: vi.fn(),
31}));
32​
33vi.mock(import("@effect/atom-react"), async (original) => ({
34 ...(await original()),
35 useAtomValue: (() => ({
36 environments: new Map(
37 testState.relayProviderKind === null
38 ? []
39 : [
40 [
41 "primary",
42 { environment: { endpoint: { providerKind: testState.relayProviderKind } } },
43 ],
44 ],
45 ),
46 })) as never,
47}));
48vi.mock(import("@clerk/react"), async (original) => ({
49 ...(await original()),
50 useAuth: (() => ({ getToken: testState.getToken, isSignedIn: true })) as never,
51}));
52vi.mock(import("../components/ui/toast"), async (original) => {
53 const actual = await original();
54 return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } as never };
55});
56vi.mock(import("../state/relay"), async (original) => {
57 const actual = await original();
58 return {
59 ...actual,
60 relayEnvironmentDiscovery: {
61 ...actual.relayEnvironmentDiscovery,
62 refresh: testState.refreshDiscovery,
63 } as never,
64 };
65});
66vi.mock(import("../state/session"), async (original) => ({
67 ...(await original()),
68 readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
69}));
70vi.mock(import("../state/use-atom-command"), async (original) => ({
71 ...(await original()),
72 useAtomCommand: ((command: unknown) => command) as never,
73}));
74vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
75 ...(await original()),
76 linkPrimaryEnvironment: testState.link as never,
77 unlinkPrimaryEnvironment: testState.unlink as never,
78 updatePrimaryEnvironmentPreferences: testState.preferences as never,
79}));
80vi.mock(import("./primaryCloudLinkState"), async (original) => ({
81 ...(await original()),
82 readCachedPrimaryCloudLinkState: () => testState.snapshot,
83 usePrimaryCloudLinkState: (() => ({
84 target,
85 data: testState.renderedSnapshot,
86 error: null,
87 isPending: false,
88 refresh: testState.refreshLink,
89 })) as never,
90}));
91vi.mock(import("./publicConfig"), async (original) => ({
92 ...(await original()),
93 resolveRelayClerkTokenOptions: () => ({}) as never,
94}));
95​
96import { CloudEnvironmentLinkError } from "./linkEnvironment";
97import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
98​
99const target = {
100 environmentId: EnvironmentId.make("primary"),
101 label: "Primary",
102 httpBaseUrl: "http://localhost:3773",
103 wsBaseUrl: "ws://localhost:3773/ws",
104};
105const linkedState: EnvironmentCloudLinkStateResult = {
106 linked: true,
107 cloudUserId: "account-1",
108 relayUrl: "https://relay.example.com",
109 relayIssuer: "https://relay.example.com",
110 managedTunnelActive: true,
111 publishAgentActivity: false,
112};
113​
114type Controller = ReturnType<typeof useCloudLinkController>;
115​
116function ControllerProbe({ onRender }: { onRender: (controller: Controller) => void }) {
117 const value = useCloudLinkController();
118 useLayoutEffect(() => {
119 onRender(value);
120 });
121 return null;
123​
124async function mountController() {
125 let controller: Controller | null = null;
126 const screen = await render(
127 <ControllerProbe
128 onRender={(value) => {
129 controller = value;
130 }}
131 />,
132 );
133 return Object.assign(screen, {
134 // Object.assign would copy a getter's value once, so read the latest render through a function.
135 controller: () => controller,
136 async reconcile(desired: CloudLinkDesiredState) {
137 let succeeded = false;
138 await act(async () => {
139 if (controller === null) throw new Error("Controller is not mounted.");
140 succeeded = await controller.reconcileCloudState(desired);
141 });
142 return succeeded;
143 },
144 });
146​
147function expectNoMutations() {
148 expect(testState.link).not.toHaveBeenCalled();
149 expect(testState.unlink).not.toHaveBeenCalled();
150 expect(testState.preferences).not.toHaveBeenCalled();
152​
153function setup() {
154 testState.scopes = new Set([AuthRelayReadScope, AuthRelayWriteScope]);
155 testState.snapshot = linkedState;
156 testState.renderedSnapshot = linkedState;
157 testState.relayProviderKind = null;
158 testState.getToken.mockReset().mockResolvedValue("clerk-token");
159 for (const command of [
160 testState.link,
161 testState.unlink,
162 testState.preferences,
163 testState.refreshDiscovery,
164 ]) {
165 command.mockReset().mockResolvedValue(AsyncResult.success({}));
166 }
167 testState.refreshLink.mockReset();
168 testState.toast.mockReset();
169 return vi.spyOn(console, "error").mockImplementation(() => undefined);
171​
172describe("useCloudLinkController", () => {
173 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
174 "does not mutate without %s, even with a cached link snapshot",
175 async (scope) => {
176 using _setup = setup();
177 await using screen = await mountController();
178 testState.scopes.delete(scope);
179​
180 expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
181 expect(testState.getToken).not.toHaveBeenCalled();
182 expectNoMutations();
183 },
184 );
185​
186 it("does not interpret unavailable link state as an unlinked environment", async () => {
187 using _setup = setup();
188 testState.snapshot = null;
189 await using screen = await mountController();
190​
191 expect(await screen.reconcile({ managedTunnel: false, publish: true })).toBe(false);
192 expect(testState.getToken).not.toHaveBeenCalled();
193 expectNoMutations();
194 });
195​
196 it.each([AuthRelayReadScope, AuthRelayWriteScope])(
197 "rechecks %s after requesting the cloud token",
198 async (scope) => {
199 using _setup = setup();
200 await using screen = await mountController();
201 testState.getToken.mockImplementationOnce(async () => {
202 testState.scopes.delete(scope);
203 return "clerk-token";
204 });
205​
206 expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(false);
207 expectNoMutations();
208 },
209 );
210​
211 it("stops if the link-state read fails while requesting the cloud token", async () => {
212 using _setup = setup();
213 await using screen = await mountController();
214 testState.getToken.mockImplementationOnce(async () => {
215 testState.snapshot = null;
216 return "clerk-token";
217 });
218​
219 expect(await screen.reconcile({ managedTunnel: true, publish: true })).toBe(false);
220 expectNoMutations();
221 });
222​
223 it("still lets an authorized user unlink when the cloud token is unavailable", async () => {
224 using _setup = setup();
225 await using screen = await mountController();
226 testState.getToken.mockRejectedValueOnce(new Error("Cloud sign-in unavailable"));
227​
228 expect(await screen.reconcile({ managedTunnel: false, publish: false })).toBe(true);
229 expect(testState.unlink).toHaveBeenCalledExactlyOnceWith({ target, clerkToken: null });
230 expect(testState.link).not.toHaveBeenCalled();
231 expect(testState.preferences).not.toHaveBeenCalled();
232 });
233​
234 it("reports a relay tunnel cap refusal as tunnelLimit instead of an error", async () => {
235 using _setup = setup();
236 testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false };
237 testState.link.mockResolvedValueOnce(
238 AsyncResult.failure(
239 Cause.fail(
240 new CloudEnvironmentLinkError({
241 message: "environment-links failed",
242 cause: new ManagedRelay.ManagedRelayRequestFailedError({
243 action: "link relay environment",
244 cause: null,
245 relayError: new RelayEnvironmentLinkLimitExceededError({
246 code: "environment_link_limit_exceeded",
247 maxTunnels: 3,
248 traceId: "trace-1",
249 }),
250 }),
251 }),
252 ),
253 ),
254 );
255 await using screen = await mountController();
256​
257 expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(false);
258 expect(screen.controller()?.tunnelLimit).toBe(3);
259 expect(screen.controller()?.operationError).toBeNull();
260 expect(testState.toast).not.toHaveBeenCalled();
261 });
262});