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

usage.ts

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