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

resourceTelemetryState.ts

76 lines2.7 KB

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>;
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 return result.value.snapshot;
56 };
57​
58 return { ...query, retry };
60​
61export function useResourceTelemetryHistory(
62 input: ResourceTelemetryHistoryInput,
63 targetEnvironmentId?: EnvironmentId | null,
64) {
65 const primaryEnvironment = usePrimaryEnvironment();
66 const environmentId =
67 targetEnvironmentId === undefined
68 ? (primaryEnvironment?.environmentId ?? null)
69 : targetEnvironmentId;
70 const canReadDiagnostics = useEnvironmentScope(environmentId, AuthDiagnosticsReadScope);
71 return useEnvironmentQuery(
72 environmentId === null || !canReadDiagnostics
73 ? null
74 : serverEnvironment.resourceTelemetryHistory({ environmentId, input }),
75 );