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

processDiagnosticsState.ts

63 lines1.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { ServerProcessDiagnosticsResult } from "@t3tools/contracts";
3import { Cause, Effect, Option } from "effect";
4import { AsyncResult, Atom } from "effect/unstable/reactivity";
5import { useCallback } from "react";
6​
7import { ensureLocalApi } from "../localApi";
8import { appAtomRegistry } from "../rpc/atomRegistry";
9​
10const PROCESS_DIAGNOSTICS_STALE_TIME_MS = 2_000;
11const PROCESS_DIAGNOSTICS_IDLE_TTL_MS = 5 * 60_000;
12​
13const processDiagnosticsAtom = Atom.make(
14 Effect.promise(() => ensureLocalApi().server.getProcessDiagnostics()),
15).pipe(
16 Atom.swr({
17 staleTime: PROCESS_DIAGNOSTICS_STALE_TIME_MS,
18 revalidateOnMount: true,
19 }),
20 Atom.setIdleTTL(PROCESS_DIAGNOSTICS_IDLE_TTL_MS),
21 Atom.withLabel("process-diagnostics"),
22);
23​
24export interface ProcessDiagnosticsState {
25 readonly data: ServerProcessDiagnosticsResult | null;
26 readonly error: string | null;
27 readonly isPending: boolean;
28 readonly refresh: () => void;
30​
31function formatProcessDiagnosticsError(error: unknown): string {
32 return error instanceof Error ? error.message : "Failed to load process diagnostics.";
34​
35function readProcessDiagnosticsError(
36 result: AsyncResult.AsyncResult<ServerProcessDiagnosticsResult, unknown>,
37): string | null {
38 if (result._tag !== "Failure") {
39 return null;
40 }
41​
42 const squashed = Cause.squash(result.cause);
43 return formatProcessDiagnosticsError(squashed);
45​
46export function refreshProcessDiagnostics(): void {
47 appAtomRegistry.refresh(processDiagnosticsAtom);
49​
50export function useProcessDiagnostics(): ProcessDiagnosticsState {
51 const result = useAtomValue(processDiagnosticsAtom);
52 const data = Option.getOrNull(AsyncResult.value(result));
53 const refresh = useCallback(() => {
54 refreshProcessDiagnostics();
55 }, []);
56​
57 return {
58 data,
59 error: readProcessDiagnosticsError(result),
60 isPending: result.waiting,
61 refresh,
62 };