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

cloudLinkState.ts

71 lines2.6 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 AuthRelayReadScope,
4 type EnvironmentCloudLinkStateResult,
5 type EnvironmentId,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import { AsyncResult, Atom } from "effect/reactivity";
9​
10import { connectionAtomRuntime } from "../connection/runtime";
11import { usePrimaryEnvironmentId } from "../state/environments";
12import { appAtomRegistry } from "../rpc/atomRegistry";
13import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
14import { readCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";
15import { hasCloudPublicConfig } from "./publicConfig";
16​
17const cloudLinkStateAtom = Atom.family((environmentId: EnvironmentId) =>
18 connectionAtomRuntime
19 .atom(readCloudLinkState({ target: { environmentId } }))
20 .pipe(
21 Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
22 Atom.setIdleTTL(5 * 60_000),
23 Atom.withLabel(`cloud-link:${environmentId}`),
24 ),
25);
26​
27const EMPTY_CLOUD_LINK_STATE_ATOM = Atom.make(
28 AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),
29).pipe(Atom.keepAlive, Atom.withLabel("cloud-link:null"));
30​
31function refreshCloudLinkState(target: CloudLinkTarget | null): void {
32 if (target && readEnvironmentScope(target.environmentId, AuthRelayReadScope)) {
33 appAtomRegistry.refresh(cloudLinkStateAtom(target.environmentId));
34 }
36​
37export function readCachedCloudLinkState(target: CloudLinkTarget) {
38 if (!readEnvironmentScope(target.environmentId, AuthRelayReadScope)) return null;
39 const result = appAtomRegistry.get(cloudLinkStateAtom(target.environmentId));
40 return result._tag === "Success" ? result.value : null;
42​
43export function useCloudLinkState(environmentId: EnvironmentId | null) {
44 const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
45 const target: CloudLinkTarget | null = environmentId === null ? null : { environmentId };
46 const atom =
47 environmentId !== null && hasCloudPublicConfig() && canReadRelay
48 ? cloudLinkStateAtom(environmentId)
49 : EMPTY_CLOUD_LINK_STATE_ATOM;
50 const result = useAtomValue(atom);
51 const refresh = () => {
52 refreshCloudLinkState(target);
53 };
54 let error: string | null = null;
55 if (result._tag === "Failure") {
56 const cause = Cause.squash(result.cause);
57 error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";
58 }
59​
60 return {
61 data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),
62 error,
63 isPending: result.waiting,
64 refresh,
65 target,
66 };
68​
69export function usePrimaryCloudLinkState() {
70 return useCloudLinkState(usePrimaryEnvironmentId());