Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { EnvironmentCloudLinkStateResult, EnvironmentId } from "@t3tools/contracts";
3import * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import { AsyncResult, Atom } from "effect/unstable/reactivity";
9import { HttpClient } from "effect/unstable/http";
10import { useCallback } from "react";
11
12import { usePrimaryEnvironmentId } from "../environments/primary";
13import { webRuntime } from "../lib/runtime";
14import { appAtomRegistry } from "../rpc/atomRegistry";
15import { readPrimaryCloudLinkState } from "./linkEnvironment";
16
17const primaryCloudLinkAtomRuntime = Atom.runtime(
18 Layer.effect(
19 HttpClient.HttpClient,
20 webRuntime.contextEffect.pipe(
21 Effect.map((context) => Context.get(context, HttpClient.HttpClient)),
22 ),
23 ),
24);
25
26const primaryCloudLinkStateAtom = Atom.family((environmentId: EnvironmentId) =>
27 primaryCloudLinkAtomRuntime
28 .atom(readPrimaryCloudLinkState())
29 .pipe(
30 Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
31 Atom.setIdleTTL(5 * 60_000),
32 Atom.withLabel(`primary-cloud-link:${environmentId}`),
33 ),
34);
35
36const EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM = Atom.make(
37 AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),
38).pipe(Atom.keepAlive, Atom.withLabel("primary-cloud-link:null"));
39
40export function refreshPrimaryCloudLinkState(environmentId: EnvironmentId | null): void {
41 if (environmentId) {
42 appAtomRegistry.refresh(primaryCloudLinkStateAtom(environmentId));
43 }
44}
45
46export function usePrimaryCloudLinkState() {
47 const environmentId = usePrimaryEnvironmentId();
48 const atom = environmentId
49 ? primaryCloudLinkStateAtom(environmentId)
50 : EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM;
51 const result = useAtomValue(atom);
52 const refresh = useCallback(() => {
53 refreshPrimaryCloudLinkState(environmentId);
54 }, [environmentId]);
55 let error: string | null = null;
56 if (result._tag === "Failure") {
57 const cause = Cause.squash(result.cause);
58 error = cause instanceof Error ? cause.message : "Could not read T3 Cloud link state.";
59 }
60
61 return {
62 data: Option.getOrNull(AsyncResult.value(result)),
63 error,
64 isPending: result.waiting,
65 refresh,
66 };
67}