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 UsageBucket,
7 type UsageSummary,
8 type UsageProviderKind,
9 type UsageSummaryInput,
10} from "@t3tools/contracts";
11import { refreshUsage, usageSummaryInput } from "@t3tools/client-runtime/state/usage";
12import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
13import { AsyncResult, Atom } from "effect/reactivity";
14import { useState } from "react";
15
16import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
17import { appAtomRegistry } from "../rpc/atomRegistry";
18import { environmentPresentations } from "./presentation";
19import { serverEnvironment } from "./server";
20import { environmentSession, readEnvironmentScope } from "./session";
21
22export interface EnvironmentUsageStatus {
23 readonly environmentId: EnvironmentId;
24 readonly label: string;
25 readonly isPending: boolean;
26 readonly canReadDiagnostics: boolean;
27 readonly isConnected: boolean;
28 readonly error: string | null;
29 readonly summary: UsageSummary | null;
30}
31
32const usageByWindowAtom = Atom.family((windowKey: string) =>
33 Atom.make((get): readonly EnvironmentUsageStatus[] => {
34 const input = JSON.parse(windowKey) as UsageSummaryInput;
35 const presentations = get(environmentPresentations.presentationsAtom);
36
37 const statuses: EnvironmentUsageStatus[] = [];
38 for (const [environmentId, presentation] of presentations) {
39 const isConnected = presentation.connection.phase === "connected";
40 const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
41 const access = resolveUsageAccess({
42 connectionPhase: presentation.connection.phase,
43 session: AsyncResult.getOrElse(sessionResult, () => null),
44 hasSessionError: sessionResult._tag === "Failure",
45 });
46 if (!access.canReadDiagnostics) {
47 statuses.push({
48 environmentId,
49 label: presentation.entry.target.label,
50 isConnected,
51 ...access,
52 summary: null,
53 });
54 continue;
55 }
56 const result = get(
57 serverEnvironment.usageSummary({
58 environmentId,
59 input: usageSummaryInput(
60 input,
61 get(serverEnvironment.usageModelFilterAtom(environmentId)),
62 ),
63 }),
64 );
65 const summary = AsyncResult.getOrElse(result, () => null);
66 statuses.push({
67 environmentId,
68 label: presentation.entry.target.label,
69 isPending: result.waiting,
70 canReadDiagnostics: true,
71 isConnected,
72 error: result._tag === "Failure" ? "This environment could not report usage." : null,
73 summary,
74 });
75 }
76 return statuses;
77 }).pipe(Atom.withLabel(`web-usage:window:${windowKey}`)),
78);
79
80export interface UsageView {
81 readonly merged: MergedUsage;
82 readonly environments: readonly EnvironmentUsageStatus[];
83 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
84 readonly isPending: boolean;
85 readonly shown: { readonly window: UsageSummaryInput; readonly merged: MergedUsage } | null;
86 readonly isPartial: boolean;
87 readonly refresh: (input?: UsageSummaryInput) => Promise<void>;
88}
89
90export function mergeAnsweredUsage(
91 environments: readonly EnvironmentUsageStatus[],
92 keepBucket?: (bucket: UsageBucket) => boolean,
93): MergedUsage {
94 const answered: EnvironmentUsage[] = environments.flatMap(({ environmentId, label, summary }) =>
95 summary === null
96 ? []
97 : [
98 {
99 environmentId,
100 label,
101 summary:
102 keepBucket === undefined
103 ? summary
104 : { ...summary, buckets: summary.buckets.filter(keepBucket) },
105 },
106 ],
107 );
108 return mergeUsage(answered, USAGE_CONTRACT_VERSION);
109}
110
111const NO_HIDDEN_PROVIDERS: ReadonlySet<UsageProviderKind> = new Set();
112
113function withoutProviders(
114 environments: readonly EnvironmentUsageStatus[],
115 hiddenProviders: ReadonlySet<UsageProviderKind>,
116): readonly EnvironmentUsageStatus[] {
117 if (hiddenProviders.size === 0) return environments;
118 return environments.map((environment) =>
119 environment.summary === null
120 ? environment
121 : {
122 ...environment,
123 summary: {
124 ...environment.summary,
125 buckets: environment.summary.buckets.filter(
126 (bucket) => !hiddenProviders.has(bucket.provider),
127 ),
128 sources: environment.summary.sources.filter(
129 (source) => !hiddenProviders.has(source.fingerprint.provider),
130 ),
131 },
132 },
133 );
134}
135
136function deriveSelection(
137 environments: readonly EnvironmentUsageStatus[],
138 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null,
139 hiddenProviders: ReadonlySet<UsageProviderKind>,
140) {
141 const selectedEnvironments =
142 selectedEnvironmentIds === null
143 ? environments
144 : environments.filter((environment) => selectedEnvironmentIds.has(environment.environmentId));
145 return {
146 environments,
147 selectedEnvironmentIds,
148 hiddenProviders,
149 selectedEnvironments,
150 merged: mergeAnsweredUsage(withoutProviders(selectedEnvironments, hiddenProviders)),
151 };
152}
153
154export function useUsage(
155 input: UsageSummaryInput,
156 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
157 hiddenProviders: ReadonlySet<UsageProviderKind> = NO_HIDDEN_PROVIDERS,
158): UsageView {
159 const windowKey = JSON.stringify({
160 sinceDay: input.sinceDay,
161 untilDay: input.untilDay,
162 timeZone: input.timeZone,
163 resolution: input.resolution,
164 sinceTime: input.sinceTime,
165 untilTime: input.untilTime,
166 });
167 const atom = usageByWindowAtom(windowKey);
168 const environments = useAtomValue(atom);
169 // Identity-based render sync needs a derivation retained by inputs across renders.
170 const [derived, setDerived] = useState(() =>
171 deriveSelection(environments, selectedEnvironmentIds, hiddenProviders),
172 );
173 let current = derived;
174 if (
175 derived.environments !== environments ||
176 derived.selectedEnvironmentIds !== selectedEnvironmentIds ||
177 derived.hiddenProviders !== hiddenProviders
178 ) {
179 current = deriveSelection(environments, selectedEnvironmentIds, hiddenProviders);
180 setDerived(current);
181 }
182 const { selectedEnvironments, merged } = current;
183
184 const refresh = (nextInput?: UsageSummaryInput) =>
185 refreshUsage({
186 registry: appAtomRegistry,
187 server: serverEnvironment,
188 presentations: environmentPresentations,
189 environmentIds: selectedEnvironments
190 .filter(
191 (environment) =>
192 environment.canReadDiagnostics &&
193 readEnvironmentScope(environment.environmentId, AuthDiagnosticsReadScope),
194 )
195 .map(({ environmentId }) => environmentId),
196 input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),
197 });
198
199 const answeredCount = selectedEnvironments.filter(
200 (environment) => environment.summary !== null,
201 ).length;
202 const stillReporting = selectedEnvironments.filter(
203 (environment) => environment.summary === null && environment.error === null,
204 ).length;
205 const isPending = answeredCount === 0 && stillReporting > 0;
206
207 const [lastAnswered, setLastAnswered] = useState<
208 | (NonNullable<UsageView["shown"]> & {
209 readonly selection: typeof selectedEnvironmentIds;
210 readonly hidden: typeof hiddenProviders;
211 })
212 | null
213 >(null);
214 if (
215 answeredCount > 0 &&
216 (lastAnswered?.merged !== merged ||
217 lastAnswered.window !== input ||
218 lastAnswered.selection !== selectedEnvironmentIds ||
219 lastAnswered.hidden !== hiddenProviders)
220 ) {
221 setLastAnswered({
222 window: input,
223 merged,
224 selection: selectedEnvironmentIds,
225 hidden: hiddenProviders,
226 });
227 }
228 const kept =
229 lastAnswered?.selection === selectedEnvironmentIds && lastAnswered.hidden === hiddenProviders
230 ? lastAnswered
231 : null;
232 const shown =
233 answeredCount > 0
234 ? { window: input, merged }
235 : (kept ?? (isPending ? null : { window: input, merged }));
236
237 return {
238 merged,
239 environments,
240 selectedEnvironments,
241 isPending,
242 shown,
243 isPartial: answeredCount > 0 && stillReporting > 0,
244 refresh,
245 };
246}