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

traceDiagnosticsState.ts

63 lines1.8 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { ServerTraceDiagnosticsResult } 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 TRACE_DIAGNOSTICS_STALE_TIME_MS = 5_000;
11const TRACE_DIAGNOSTICS_IDLE_TTL_MS = 5 * 60_000;
12​
13const traceDiagnosticsAtom = Atom.make(
14 Effect.promise(() => ensureLocalApi().server.getTraceDiagnostics()),
15).pipe(
16 Atom.swr({
17 staleTime: TRACE_DIAGNOSTICS_STALE_TIME_MS,
18 revalidateOnMount: true,
19 }),
20 Atom.setIdleTTL(TRACE_DIAGNOSTICS_IDLE_TTL_MS),
21 Atom.withLabel("trace-diagnostics"),
22);
23​
24export interface TraceDiagnosticsState {
25 readonly data: ServerTraceDiagnosticsResult | null;
26 readonly error: string | null;
27 readonly isPending: boolean;
28 readonly refresh: () => void;
30​
31function formatTraceDiagnosticsError(error: unknown): string {
32 return error instanceof Error ? error.message : "Failed to load trace diagnostics.";
34​
35function readTraceDiagnosticsError(
36 result: AsyncResult.AsyncResult<ServerTraceDiagnosticsResult, unknown>,
37): string | null {
38 if (result._tag !== "Failure") {
39 return null;
40 }
41​
42 const squashed = Cause.squash(result.cause);
43 return formatTraceDiagnosticsError(squashed);
45​
46export function refreshTraceDiagnostics(): void {
47 appAtomRegistry.refresh(traceDiagnosticsAtom);
49​
50export function useTraceDiagnostics(): TraceDiagnosticsState {
51 const result = useAtomValue(traceDiagnosticsAtom);
52 const data = Option.getOrNull(AsyncResult.value(result));
53 const refresh = useCallback(() => {
54 refreshTraceDiagnostics();
55 }, []);
56​
57 return {
58 data,
59 error: readTraceDiagnosticsError(result),
60 isPending: result.waiting,
61 refresh,
62 };