| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 6 | import { useCallback } from "react"; |
| 7 | |
| 8 | import { isLocalEnvironmentDisabled } from "../../localEnvironment"; |
| 9 | import { appAtomRegistry } from "../../rpc/atomRegistry"; |
| 10 | import { fetchSessionState } from "./auth"; |
| 11 | |
| 12 | const primarySessionStateAtom = Atom.make( |
| 13 | Effect.suspend(() => |
| 14 | isLocalEnvironmentDisabled() ? Effect.succeed(null) : Effect.promise(fetchSessionState), |
| 15 | ), |
| 16 | ).pipe( |
| 17 | Atom.swr({ staleTime: 5_000, revalidateOnMount: true }), |
| 18 | Atom.setIdleTTL(5 * 60_000), |
| 19 | Atom.withLabel("primary-environment:session"), |
| 20 | ); |
| 21 | |
| 22 | function refreshPrimarySessionState(): void { |
| 23 | appAtomRegistry.refresh(primarySessionStateAtom); |
| 24 | } |
| 25 | |
| 26 | export function usePrimarySessionState() { |
| 27 | const result = useAtomValue(primarySessionStateAtom); |
| 28 | const refresh = useCallback(() => { |
| 29 | refreshPrimarySessionState(); |
| 30 | }, []); |
| 31 | let error: string | null = null; |
| 32 | if (result._tag === "Failure") { |
| 33 | const cause = Cause.squash(result.cause); |
| 34 | error = cause instanceof Error ? cause.message : "Could not read environment session."; |
| 35 | } |
| 36 | return { |
| 37 | data: Option.getOrNull(AsyncResult.value(result)), |
| 38 | error, |
| 39 | isPending: result.waiting, |
| 40 | refresh, |
| 41 | }; |
| 42 | } |