1import { AuthDiagnosticsReadScope } from "@t3tools/contracts";
2import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";
3import type {
4 EnvironmentId,
5 ResourceTelemetryHistoryInput,
6 ResourceTelemetrySnapshot,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9
10import { usePrimaryEnvironment } from "../state/environments";
11import { useEnvironmentQuery } from "../state/query";
12import { serverEnvironment } from "../state/server";
13import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
14import { useAtomCommand } from "../state/use-atom-command";
15
16export interface ResourceTelemetryState {
17 readonly data: ResourceTelemetrySnapshot | null;
18 readonly error: string | null;
19 readonly isPending: boolean;
20 readonly refresh: () => void;
21 readonly retry: () => Promise<ResourceTelemetrySnapshot>;
22}
23
24export function useResourceTelemetry(
25 targetEnvironmentId?: EnvironmentId | null,
26): ResourceTelemetryState {
27 const primaryEnvironment = usePrimaryEnvironment();
28 const environmentId =
29 targetEnvironmentId === undefined
30 ? (primaryEnvironment?.environmentId ?? null)
31 : targetEnvironmentId;
32 const canReadDiagnostics = useEnvironmentScope(environmentId, AuthDiagnosticsReadScope);
33 const query = useEnvironmentQuery(
34 environmentId === null || !canReadDiagnostics
35 ? null
36 : serverEnvironment.resourceTelemetry({ environmentId, input: {} }),
37 );
38 const retryCommand = useAtomCommand(serverEnvironment.retryResourceTelemetry, {
39 reportFailure: false,
40 });
41 const retry = async () => {
42 if (environmentId === null) {
43 throw new Error("No environment is selected.");
44 }
45 if (
46 !readEnvironmentScope(environmentId, AuthEnvironmentMaintainScope) ||
47 !readEnvironmentScope(environmentId, AuthDiagnosticsReadScope)
48 ) {
49 throw new Error("This connection cannot restart the resource monitor.");
50 }
51 const result = await retryCommand({ environmentId, input: {} });
52 if (result._tag === "Failure") {
53 throw Cause.squash(result.cause);
54 }
55 query.refresh();
56 return result.value.snapshot;
57 };
58
59 return { ...query, retry };
60}
61
62export function useResourceTelemetryHistory(
63 input: ResourceTelemetryHistoryInput,
64 targetEnvironmentId?: EnvironmentId | null,
65) {
66 const primaryEnvironment = usePrimaryEnvironment();
67 const environmentId =
68 targetEnvironmentId === undefined
69 ? (primaryEnvironment?.environmentId ?? null)
70 : targetEnvironmentId;
71 const canReadDiagnostics = useEnvironmentScope(environmentId, AuthDiagnosticsReadScope);
72 return useEnvironmentQuery(
73 environmentId === null || !canReadDiagnostics
74 ? null
75 : serverEnvironment.resourceTelemetryHistory({ environmentId, input }),
76 );
77}