Open History to see the last commit
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 );
37}
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[];
44}
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 }));
67}
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 */
74export function collectLimitSources(
75 presentations: ReadonlyMap<
76 EnvironmentId,
77 {
78 readonly entry: { readonly target: { readonly label: string } };
79 readonly serverConfig: {
80 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
81 } | null;
82 }
83 >,
84): ReadonlyArray<
85 UsageLimitSourceSnapshot & { readonly key: string; readonly environmentId: EnvironmentId }
86> {
87 const perEnvironment: Array<{
88 readonly environmentId: EnvironmentId;
89 readonly environmentLabel: string;
90 readonly sources: UsageLimitSourceSnapshots;
91 }> = [];
92 for (const [environmentId, presentation] of presentations) {
93 const sources = presentation.serverConfig?.usageLimitSources ?? [];
94 if (sources.length === 0) continue;
95 perEnvironment.push({
96 environmentId,
97 environmentLabel: presentation.entry.target.label,
98 sources,
99 });
100 }
101 const labelEnvironment = perEnvironment.length > 1;
102 return perEnvironment.flatMap(({ environmentId, environmentLabel, sources }) =>
103 sources.map((source) => ({
104 ...source,
105 environmentId,
106 key: `${environmentId}:${source.id}`,
107 label: labelEnvironment ? `${environmentLabel} · ${source.label}` : source.label,
108 })),
109 );
110}
111
112/** The instance's configured name, else the driver's, else its raw kind. */
113export function providerLimitsLabel(
114 provider: ServerProvider,
115 driverLabel: (driver: ServerProvider["driver"]) => string | undefined,
116): string {
117 return provider.displayName?.trim() || driverLabel(provider.driver) || String(provider.driver);
118}
119
120/** The one-line status under a provider heading when there are no bars to draw. */
121export function limitsNotice(limits: ServerProviderUsageLimits): string | null {
122 if (limits.unavailable?.reason === "unsupported") {
123 return limits.unavailable.message ?? "This account has no subscription limits.";
124 }
125 if (limits.unavailable?.reason === "probeFailed") {
126 return limits.unavailable.message ?? "Could not read limits.";
127 }
128 return limits.windows.length === 0 ? "No limits reported." : null;
129}
130
131export function resetMillis(window: ServerProviderUsageWindow): number | null {
132 if (window.resetsAt === undefined) return null;
133 const at = Date.parse(window.resetsAt);
134 return Number.isFinite(at) ? at : null;
135}
136
137/** Elapsed share of the window, 0..1, or null when its length or reset is unknown. */
138export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
139 const resetsAt = resetMillis(window);
140 if (resetsAt === null || window.windowDurationMins === undefined) return null;
141 const length = window.windowDurationMins * MINUTE;
142 if (length <= 0) return null;
143 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
144}
145
146export type LimitPace = "ahead" | "on" | "under";
147
148/**
149 * Usage against the clock. The bar is the whole window, so the elapsed share
150 * is also where even spending would have put the fill; within five points of
151 * it counts as on pace.
152 */
153export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
154 const elapsed = elapsedShare(window, now);
155 if (elapsed === null) return null;
156 const gap = window.usedPercent - elapsed * 100;
157 if (gap > 5) return "ahead";
158 if (gap < -5) return "under";
159 return "on";
160}
161
162/** `2h 13m`, `3d 4h`, `12m`. */
163export function formatDuration(ms: number): string {
164 const remaining = Math.max(0, ms);
165 const days = Math.floor(remaining / DAY);
166 const hours = Math.floor((remaining % DAY) / HOUR);
167 const minutes = Math.floor((remaining % HOUR) / MINUTE);
168 if (days > 0) return `${days}d ${hours}h`;
169 if (hours > 0) return `${hours}h ${minutes}m`;
170 return `${minutes}m`;
171}
172
173/** `resets in 2h 13m`, or null when the window has no reset. */
174export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
175 const resetsAt = resetMillis(window);
176 if (resetsAt === null) return null;
177 return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;
178}