Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 AuthDiagnosticsReadScope,
4 USAGE_CONTRACT_VERSION,
5 type EnvironmentId,
6 type UsageSummary,
7 type UsageSummaryInput,
8} from "@t3tools/contracts";
9import { refreshUsage, usageSummaryInput } from "@t3tools/client-runtime/state/usage";
10import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
11import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
12import { AsyncResult, Atom } from "effect/reactivity";
13import { useCallback, useMemo } from "react";
14
15import { appAtomRegistry } from "./atom-registry";
16import { environmentPresentations } from "./presentation";
17import { serverEnvironment } from "./server";
18import { environmentSession, readEnvironmentScope } from "./session";
19
20export interface EnvironmentUsageStatus {
21 readonly environmentId: EnvironmentId;
22 readonly label: string;
23 readonly isPending: boolean;
24 readonly isConnected: boolean;
25 readonly canReadDiagnostics: boolean;
26 readonly error: string | null;
27 readonly summary: UsageSummary | null;
28}
29
30const usageByWindowAtom = Atom.family((windowKey: string) =>
31 Atom.make((get): readonly EnvironmentUsageStatus[] => {
32 const input = JSON.parse(windowKey) as UsageSummaryInput;
33 const presentations = get(environmentPresentations.presentationsAtom);
34
35 const statuses: EnvironmentUsageStatus[] = [];
36 for (const [environmentId, presentation] of presentations) {
37 const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
38 const access = resolveUsageAccess({
39 connectionPhase: presentation.connection.phase,
40 session: AsyncResult.getOrElse(sessionResult, () => null),
41 hasSessionError: sessionResult._tag === "Failure",
42 });
43 if (!access.canReadDiagnostics) {
44 statuses.push({
45 environmentId,
46 label: presentation.entry.target.label,
47 isConnected: presentation.connection.phase === "connected",
48 ...access,
49 summary: null,
50 });
51 continue;
52 }
53 const result = get(
54 serverEnvironment.usageSummary({
55 environmentId,
56 input: usageSummaryInput(
57 input,
58 get(serverEnvironment.usageModelFilterAtom(environmentId)),
59 ),
60 }),
61 );
62 const summary = AsyncResult.getOrElse(result, () => null);
63 statuses.push({
64 environmentId,
65 label: presentation.entry.target.label,
66 isPending: result.waiting,
67 isConnected: presentation.connection.phase === "connected",
68 canReadDiagnostics: true,
69 error: result._tag === "Failure" ? "This environment could not report usage." : null,
70 summary,
71 });
72 }
73 return statuses;
74 }).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
75);
76
77/** Every environment usage can come from, without asking any of them for usage. */
78const usageEnvironmentsAtom = Atom.make((get): readonly EnvironmentUsageStatus[] =>
79 [...get(environmentPresentations.presentationsAtom)].map(([environmentId, presentation]) => ({
80 environmentId,
81 label: presentation.entry.target.label,
82 isPending: true,
83 isConnected: presentation.connection.phase === "connected",
84 canReadDiagnostics: false,
85 error: null,
86 summary: null,
87 })),
88).pipe(Atom.withLabel("mobile-usage:environments"));
89
90export interface UsageView {
91 readonly merged: MergedUsage;
92 readonly environments: readonly EnvironmentUsageStatus[];
93 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
94
95 readonly isPending: boolean;
96
97 readonly isPartial: boolean;
98 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
99}
100
101export function useUsage(
102 input: UsageSummaryInput,
103 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
104 /** Off, it lists the environments without loading their usage. */
105 load = true,
106): UsageView {
107 const windowKey = useMemo(
108 () =>
109 JSON.stringify({
110 sinceDay: input.sinceDay,
111 untilDay: input.untilDay,
112 timeZone: input.timeZone,
113 resolution: input.resolution,
114 sinceTime: input.sinceTime,
115 untilTime: input.untilTime,
116 }),
117 [
118 input.sinceDay,
119 input.untilDay,
120 input.timeZone,
121 input.resolution,
122 input.sinceTime,
123 input.untilTime,
124 ],
125 );
126 const environments = useAtomValue(load ? usageByWindowAtom(windowKey) : usageEnvironmentsAtom);
127 const selectedEnvironments = useMemo(
128 () =>
129 selectedEnvironmentIds === null
130 ? environments
131 : environments.filter(({ environmentId }) => selectedEnvironmentIds.has(environmentId)),
132 [environments, selectedEnvironmentIds],
133 );
134
135 const refresh = useCallback(
136 (nextInput?: UsageSummaryInput) =>
137 refreshUsage({
138 registry: appAtomRegistry,
139 server: serverEnvironment,
140 presentations: environmentPresentations,
141
142 environmentIds: selectedEnvironments
143 .filter(
144 (environment) =>
145 environment.canReadDiagnostics &&
146 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
147 )
148 .map(({ environmentId }) => environmentId),
149 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
150 }),
151 [selectedEnvironments, windowKey],
152 );
153
154 const merged = useMemo(() => {
155 const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>
156 environment.summary === null
157 ? []
158 : [
159 {
160 environmentId: environment.environmentId,
161 label: environment.label,
162 summary: environment.summary,
163 },
164 ],
165 );
166 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
167 }, [selectedEnvironments]);
168
169 const answeredCount = selectedEnvironments.filter(
170 (environment) => environment.summary !== null,
171 ).length;
172 const stillReporting = selectedEnvironments.filter(
173 (environment) => environment.summary === null && environment.error === null,
174 ).length;
175
176 return {
177 merged,
178 environments,
179 selectedEnvironments,
180 isPending: answeredCount === 0 && stillReporting > 0,
181 isPartial: answeredCount > 0 && stillReporting > 0,
182 refresh,
183 };
184}