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

usageLimits.ts

211 lines7.6 KB

1/**
2 * Selection and pace maths for the provider limits view, shared by web and
3 * mobile so both agree on which providers show, what "ahead of pace" means,
4 * and how a reset is phrased.
5 *
6 * @module usageLimits
7 */
8import {
9 type EnvironmentId,
10 isProviderAvailable,
11 type ServerProvider,
12 type ServerProviderUsageLimits,
13 type ServerProviderUsageWindow,
14 type UsageLimitSourceSnapshot,
15 type UsageLimitSourceSnapshots,
16} from "@t3tools/contracts";
17​
18const MINUTE = 60_000;
19const HOUR = 60 * MINUTE;
20const DAY = 24 * HOUR;
21​
22/**
23 * Providers that belong on the Limits view: enabled, installed, and one whose
24 * driver reports subscription usage at all. A driver with no notion of usage
25 * never sets `usageLimits`, so it has no row rather than an empty one.
26 */
27export function providersWithLimits(
28 providers: readonly ServerProvider[],
29): readonly ServerProvider[] {
30 return providers.filter(
31 (provider) =>
32 provider.enabled &&
33 provider.installed &&
34 isProviderAvailable(provider) &&
35 provider.usageLimits !== undefined,
36 );
38​
39export interface LimitsGroup {
40 readonly environmentId: EnvironmentId;
41 /** Null while only one environment is connected; there is nothing to tell apart. */
42 readonly environmentLabel: string | null;
43 readonly providers: readonly ServerProvider[];
45​
46/**
47 * One group per connected environment with a provider reporting limits.
48 * Provider snapshots come from the config stream every client already holds,
49 * so opening the view costs no extra request.
50 */
51export function collectLimitsGroups(
52 presentations: ReadonlyMap<
53 EnvironmentId,
54 {
55 readonly entry: { readonly target: { readonly label: string } };
56 readonly serverConfig: { readonly providers: readonly ServerProvider[] } | null;
57 }
58 >,
59): readonly LimitsGroup[] {
60 const groups: LimitsGroup[] = [];
61 for (const [environmentId, presentation] of presentations) {
62 const providers = providersWithLimits(presentation.serverConfig?.providers ?? []);
63 if (providers.length === 0) continue;
64 groups.push({ environmentId, environmentLabel: presentation.entry.target.label, providers });
65 }
66 return groups.length > 1 ? groups : groups.map((group) => ({ ...group, environmentLabel: null }));
68​
69/**
70 * Every usage-limit source across connected environments, keyed so two
71 * environments pointing at the same hub still get their own rows. The label
72 * carries the environment only when more than one environment has sources.
73 * A native provider with usable limits takes precedence over the same account
74 * in a source, even when it belongs to another connected environment.
75 */
76export function collectLimitSources(
77 presentations: ReadonlyMap<
78 EnvironmentId,
79 {
80 readonly entry: { readonly target: { readonly label: string } };
81 readonly serverConfig: {
82 readonly providers?: readonly ServerProvider[] | undefined;
83 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
84 } | null;
85 }
86 >,
87): ReadonlyArray<
88 UsageLimitSourceSnapshot & {
89 readonly key: string;
90 readonly environmentId: EnvironmentId;
91 readonly hiddenAccountCount: number;
92 }
93> {
94 const nativeAccounts = new Set<string>();
95 for (const presentation of presentations.values()) {
96 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
97 const key = accountKey(provider.driver, provider.auth.email);
98 if (
99 key !== null &&
100 provider.usageLimits?.windows.length &&
101 !provider.usageLimits.unavailable
102 ) {
103 nativeAccounts.add(key);
104 }
105 }
106 }
107 const perEnvironment: Array<{
108 readonly environmentId: EnvironmentId;
109 readonly environmentLabel: string;
110 readonly sources: UsageLimitSourceSnapshots;
111 }> = [];
112 for (const [environmentId, presentation] of presentations) {
113 const sources = presentation.serverConfig?.usageLimitSources ?? [];
114 if (sources.length === 0) continue;
115 perEnvironment.push({
116 environmentId,
117 environmentLabel: presentation.entry.target.label,
118 sources,
119 });
120 }
121 const labelEnvironment = perEnvironment.length > 1;
122 return perEnvironment.flatMap(({ environmentId, environmentLabel, sources }) =>
123 sources.map((source) => {
124 const accounts = source.accounts.filter((account) => {
125 const key = accountKey(account.driver, account.email);
126 return key === null || !nativeAccounts.has(key);
127 });
128 return {
129 ...source,
130 accounts,
131 hiddenAccountCount: source.accounts.length - accounts.length,
132 environmentId,
133 key: `${environmentId}:${source.id}`,
134 label: labelEnvironment ? `${environmentLabel} · ${source.label}` : source.label,
135 };
136 }),
137 );
139​
140function accountKey(driver: ServerProvider["driver"], email: string | undefined): string | null {
141 const normalizedEmail = email?.trim().toLowerCase();
142 return normalizedEmail ? `${driver}:${normalizedEmail}` : null;
144​
145/** The instance's configured name, else the driver's, else its raw kind. */
146export function providerLimitsLabel(
147 provider: ServerProvider,
148 driverLabel: (driver: ServerProvider["driver"]) => string | undefined,
149): string {
150 return provider.displayName?.trim() || driverLabel(provider.driver) || String(provider.driver);
152​
153/** The one-line status under a provider heading when there are no bars to draw. */
154export function limitsNotice(limits: ServerProviderUsageLimits): string | null {
155 if (limits.unavailable?.reason === "unsupported") {
156 return limits.unavailable.message ?? "This account has no subscription limits.";
157 }
158 if (limits.unavailable?.reason === "probeFailed") {
159 return limits.unavailable.message ?? "Could not read limits.";
160 }
161 return limits.windows.length === 0 ? "No limits reported." : null;
163​
164export function resetMillis(window: ServerProviderUsageWindow): number | null {
165 if (window.resetsAt === undefined) return null;
166 const at = Date.parse(window.resetsAt);
167 return Number.isFinite(at) ? at : null;
169​
170/** Elapsed share of the window, 0..1, or null when its length or reset is unknown. */
171export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
172 const resetsAt = resetMillis(window);
173 if (resetsAt === null || window.windowDurationMins === undefined) return null;
174 const length = window.windowDurationMins * MINUTE;
175 if (length <= 0) return null;
176 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
178​
179export type LimitPace = "ahead" | "on" | "under";
180​
181/**
182 * Usage against the clock. The bar is the whole window, so the elapsed share
183 * is also where even spending would have put the fill; within five points of
184 * it counts as on pace.
185 */
186export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
187 const elapsed = elapsedShare(window, now);
188 if (elapsed === null) return null;
189 const gap = window.usedPercent - elapsed * 100;
190 if (gap > 5) return "ahead";
191 if (gap < -5) return "under";
192 return "on";
194​
195/** `2h 13m`, `3d 4h`, `12m`. */
196export function formatDuration(ms: number): string {
197 const remaining = Math.max(0, ms);
198 const days = Math.floor(remaining / DAY);
199 const hours = Math.floor((remaining % DAY) / HOUR);
200 const minutes = Math.floor((remaining % HOUR) / MINUTE);
201 if (days > 0) return `${days}d ${hours}h`;
202 if (hours > 0) return `${hours}h ${minutes}m`;
203 return `${minutes}m`;
205​
206/** `resets in 2h 13m`, or null when the window has no reset. */
207export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
208 const resetsAt = resetMillis(window);
209 if (resetsAt === null) return null;
210 return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;