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

usage.ts

256 lines8.4 KB

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