Open History to see the last commit
1import { useAuth } from "@clerk/react";
2import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
3import {
4 reportAtomCommandResult,
5 settleAsyncResult,
6 settlePromise,
7} from "@t3tools/client-runtime/state/runtime";
8import * as Effect from "effect/Effect";
9import { useEffect, useRef, type ReactNode } from "react";
10
11import { environmentCatalog } from "../connection/catalog";
12import { runtime } from "../lib/runtime";
13import { appAtomRegistry } from "../rpc/atomRegistry";
14import { useAtomCommand } from "../state/use-atom-command";
15import { resolveRelayClerkTokenOptions } from "./publicConfig";
16
17export function deactivateManagedRelayAuthentication(): void {
18 setManagedRelaySession(appAtomRegistry, null);
19}
20
21export function activateManagedRelayAuthentication(
22 accountId: string,
23 readClerkToken: () => Promise<string | null>,
24): void {
25 setManagedRelaySession(appAtomRegistry, {
26 accountId,
27 readClerkToken,
28 });
29}
30
31export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
32 const { getToken, isLoaded, isSignedIn, userId } = useAuth({
33 treatPendingAsSignedOut: false,
34 });
35 const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
36 reportFailure: false,
37 reportDefect: false,
38 });
39 const observedAccountRef = useRef<string | null | undefined>(undefined);
40 const accountTransitionRef = useRef<Promise<void> | null>(null);
41
42 useEffect(() => {
43 if (!isLoaded) {
44 return;
45 }
46
47 let cancelled = false;
48 const previousAccount = observedAccountRef.current;
49 const nextAccount = isSignedIn && userId ? userId : null;
50 observedAccountRef.current = nextAccount;
51
52 const queueAccountCleanup = () => {
53 const previousTransition = accountTransitionRef.current ?? Promise.resolve();
54 accountTransitionRef.current = previousTransition.then(async () => {
55 const results = await Promise.all([
56 removeRelayEnvironments(),
57 settleAsyncResult(() =>
58 runtime.runPromiseExit(
59 ManagedRelay.ManagedRelayClient.pipe(
60 Effect.flatMap((client) => client.resetTokenCache),
61 ),
62 ),
63 ),
64 ]);
65 for (const result of results) {
66 reportAtomCommandResult(result, { label: "cloud account cleanup" });
67 }
68 });
69 return accountTransitionRef.current;
70 };
71
72 if (!isSignedIn || !userId) {
73 deactivateManagedRelayAuthentication();
74 if (previousAccount !== null) {
75 void queueAccountCleanup();
76 }
77 } else {
78 const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
79 const activateSession = () => {
80 if (!cancelled) {
81 activateManagedRelayAuthentication(userId, tokenProvider);
82 }
83 };
84 const activateAfterTransition = (transition: Promise<void>) => {
85 void (async () => {
86 const result = await settlePromise(async () => {
87 await transition;
88 activateSession();
89 });
90 reportAtomCommandResult(result, { label: "cloud account activation" });
91 })();
92 };
93 if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {
94 deactivateManagedRelayAuthentication();
95 activateAfterTransition(queueAccountCleanup());
96 } else {
97 activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
98 }
99 }
100 return () => {
101 cancelled = true;
102 };
103 }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
104
105 useEffect(() => () => deactivateManagedRelayAuthentication(), []);
106
107 return children;
108}