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
17let relayTokenProvider: (() => Promise<string | null>) | null = null;
18
19export async function readManagedRelayClerkToken(): Promise<string | null> {
20 return relayTokenProvider?.() ?? null;
21}
22
23export function deactivateManagedRelayAuthentication(): void {
24 relayTokenProvider = null;
25 setManagedRelaySession(appAtomRegistry, null);
26}
27
28export function activateManagedRelayAuthentication(
29 accountId: string,
30 readClerkToken: () => Promise<string | null>,
31): void {
32 relayTokenProvider = readClerkToken;
33 setManagedRelaySession(appAtomRegistry, {
34 accountId,
35 readClerkToken,
36 });
37}
38
39export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
40 const { getToken, isLoaded, isSignedIn, userId } = useAuth({
41 treatPendingAsSignedOut: false,
42 });
43 const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {
44 reportFailure: false,
45 reportDefect: false,
46 });
47 const observedAccountRef = useRef<string | null | undefined>(undefined);
48 const accountTransitionRef = useRef<Promise<void> | null>(null);
49
50 useEffect(() => {
51 if (!isLoaded) {
52 return;
53 }
54
55 let cancelled = false;
56 const previousAccount = observedAccountRef.current;
57 const nextAccount = isSignedIn && userId ? userId : null;
58 observedAccountRef.current = nextAccount;
59
60 const queueAccountCleanup = () => {
61 const previousTransition = accountTransitionRef.current ?? Promise.resolve();
62 accountTransitionRef.current = previousTransition.then(async () => {
63 const results = await Promise.all([
64 removeRelayEnvironments(),
65 settleAsyncResult(() =>
66 runtime.runPromiseExit(
67 ManagedRelay.ManagedRelayClient.pipe(
68 Effect.flatMap((client) => client.resetTokenCache),
69 ),
70 ),
71 ),
72 ]);
73 for (const result of results) {
74 reportAtomCommandResult(result, { label: "cloud account cleanup" });
75 }
76 });
77 return accountTransitionRef.current;
78 };
79
80 if (!isSignedIn || !userId) {
81 deactivateManagedRelayAuthentication();
82 if (previousAccount !== null) {
83 void queueAccountCleanup();
84 }
85 } else {
86 const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());
87 const activateSession = () => {
88 if (!cancelled) {
89 activateManagedRelayAuthentication(userId, tokenProvider);
90 }
91 };
92 const activateAfterTransition = (transition: Promise<void>) => {
93 void (async () => {
94 const result = await settlePromise(async () => {
95 await transition;
96 activateSession();
97 });
98 reportAtomCommandResult(result, { label: "cloud account activation" });
99 })();
100 };
101 if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {
102 deactivateManagedRelayAuthentication();
103 activateAfterTransition(queueAccountCleanup());
104 } else {
105 activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());
106 }
107 }
108 return () => {
109 cancelled = true;
110 };
111 }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);
112
113 useEffect(() => () => deactivateManagedRelayAuthentication(), []);
114
115 return children;
116}