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

cloudAccountService.ts

108 lines3.8 KB

1import type { getClerkInstance } from "@clerk/expo";
2import {
3 createCloudAccountService,
4 ManagedRelay,
5 setManagedRelaySession,
6} from "@t3tools/client-runtime/relay";
7import {
8 reportAtomCommandResult,
9 runAtomCommand,
10 settleAsyncResult,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import * as Effect from "effect/Effect";
14​
15import { runtime } from "../../lib/runtime";
16import { appAtomRegistry } from "../../state/atom-registry";
17import {
18 getComposerCloudAccountId,
19 restoreCloudComposerDrafts,
20} from "../../state/use-composer-drafts";
21import {
22 releaseAgentAwarenessRelayTokenProvider,
23 setAgentAwarenessRelayTokenProvider,
24 unregisterAgentAwarenessDeviceForCurrentUser,
25} from "../agent-awareness/remoteRegistration";
26import { removeCloudEnvironments } from "./cloud-drafts";
27import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
28import { resolveRelayClerkTokenOptions } from "./publicConfig";
29​
30type ClerkInstance = ReturnType<typeof getClerkInstance>;
31​
32export function deactivateCloudRelayAccount(): void {
33 setAgentAwarenessRelayTokenProvider(null);
34 setManagedRelaySession(appAtomRegistry, null);
36​
37export function activateCloudRelayAccount(
38 accountId: string,
39 tokenProvider: () => Promise<string | null>,
40): void {
41 setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
42 setManagedRelaySession(appAtomRegistry, {
43 accountId,
44 readClerkToken: tokenProvider,
45 });
47​
48function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
49 return async () =>
50 clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
52​
53const cleanUpCloudAccount = async (
54 clerk: ClerkInstance,
55 accountId: string | null,
56 wasActive: boolean,
57) => {
58 const removal = await runAtomCommand(appAtomRegistry, removeCloudEnvironments, accountId, {
59 reportFailure: false,
60 reportDefect: false,
61 });
62 if (removal._tag !== "Success") throw squashAtomCommandFailure(removal);
63 const results = await Promise.all([
64 settleAsyncResult(() =>
65 runtime.runPromiseExit(
66 ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
67 ),
68 ),
69 ...(wasActive
70 ? [
71 settleAsyncResult(() =>
72 runtime.runPromiseExit(
73 unregisterAgentAwarenessDeviceForCurrentUser(clerkTokenReader(clerk)),
74 ),
75 ),
76 ]
77 : []),
78 ]);
79 for (const result of results) {
80 reportAtomCommandResult(result, { label: "cloud account cleanup" });
81 }
82};
83​
84export const cloudAccountService = createCloudAccountService<ClerkInstance>({
85 deactivate: deactivateCloudRelayAccount,
86 // Detaching is not a sign-out: the user is usually still signed in, so keep
87 // lock-screen activities and the persisted registration for the next attach.
88 detach: () => {
89 releaseAgentAwarenessRelayTokenProvider();
90 setManagedRelaySession(appAtomRegistry, null);
91 },
92 // A not-yet-presented onboarding request belongs to the account that left.
93 onSignOutTransition: clearConnectOnboardingRequest,
94 cleanUp: ({ source, accountId, wasActive }) => cleanUpCloudAccount(source, accountId, wasActive),
95 prepare: async ({ source, accountId, isCurrent }) => {
96 const storedAccount = await getComposerCloudAccountId();
97 if (storedAccount !== null && storedAccount !== accountId) {
98 await cleanUpCloudAccount(source, storedAccount, false);
99 }
100 if (!isCurrent()) return;
101 await restoreCloudComposerDrafts(accountId);
102 },
103 activate: ({ source, accountId, isAccountTransition }) => {
104 activateCloudRelayAccount(accountId, clerkTokenReader(source));
105 // Issued after cleanup so the sheet never lists the previous account's environments.
106 if (isAccountTransition) requestConnectOnboarding(accountId);
107 },
108});