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

usage.ts

265 lines8.7 KB

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