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

usage.ts

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