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

usageFormat.ts

345 lines11.3 KB

1// @effect-diagnostics globalDate:off -- Usage windows are calendar days in the viewer's zone, derived from wall-clock "now" via Intl.
2import {
3 UsageDay,
4 type UsageResolution,
5 type UsageSource,
6 type UsageSummaryInput,
7} from "@t3tools/contracts";
8​
9import { sourceIdentity } from "./usageMerge.ts";
10​
11const CURRENCY = new Intl.NumberFormat("en-US", {
12 style: "currency",
13 currency: "USD",
14 minimumFractionDigits: 2,
15 maximumFractionDigits: 2,
16});
17​
18const INTEGER = new Intl.NumberFormat("en-US");
19​
20// Clients pass their UI locale; English (and the server, which passes none) keeps en-US.
21function formatLocale(locale: string | undefined): string {
22 return locale === undefined || locale === "en" ? "en-US" : locale;
24​
25const numberFormatters = new Map<string, Intl.NumberFormat>();
26​
27function numberFormatter(locale: string, currency: boolean): Intl.NumberFormat {
28 if (locale === "en-US") return currency ? CURRENCY : INTEGER;
29 const key = `${locale}:${currency}`;
30 let formatter = numberFormatters.get(key);
31 if (formatter === undefined) {
32 formatter = currency
33 ? new Intl.NumberFormat(locale, {
34 style: "currency",
35 currency: "USD",
36 minimumFractionDigits: 2,
37 maximumFractionDigits: 2,
38 })
39 : new Intl.NumberFormat(locale);
40 numberFormatters.set(key, formatter);
41 }
42 return formatter;
44​
45export function formatMalformedUsageWarning(count: number): string {
46 return `${count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`;
48​
49export function usageSourceMessages(
50 sources: readonly UsageSource[],
51 malformedWarning: (count: number) => string = formatMalformedUsageWarning,
52): readonly string[] {
53 const sourceKey = sourceIdentity(sources.map((source) => source.fingerprint));
54 const messages = new Set<string>();
55 const malformedBySource = new Map<string, number>();
56 for (const source of sources) {
57 if (
58 source.status !== "partial" &&
59 source.status !== "failed" &&
60 source.fingerprint.provider !== "cursor" &&
61 !(source.status === "missing" && source.malformedRecords > 0)
62 ) {
63 continue;
64 }
65 let message = source.message;
66 if (source.malformedRecords > 0) {
67 const key = sourceKey(source.fingerprint);
68 malformedBySource.set(
69 key,
70 Math.max(malformedBySource.get(key) ?? 0, source.malformedRecords),
71 );
72 // Servers also append this warning to message; retain any preceding read failure.
73 const warning = formatMalformedUsageWarning(source.malformedRecords);
74 if (message?.endsWith(warning)) message = message.slice(0, -warning.length).trim();
75 }
76 if (message) messages.add(message);
77 }
78 const malformedRecords = [...malformedBySource.values()].reduce(
79 (total, count) => total + count,
80 0,
81 );
82 if (malformedRecords > 0) messages.add(malformedWarning(malformedRecords));
83 return [...messages];
85​
86export function formatUsd(value: number, locale?: string): string {
87 return numberFormatter(formatLocale(locale), true).format(value);
89​
90export function formatCount(value: number, locale?: string): string {
91 return numberFormatter(formatLocale(locale), false).format(Math.round(value));
93​
94const TOKEN_SUFFIXES = ["K", "M", "B", "T"] as const;
95​
96export function formatTokens(value: number): string {
97 if (Math.abs(Math.round(value)) < 1e3) return INTEGER.format(Math.round(value));
98 let scaled = value / 1e3;
99 let unit = 0;
100 // Choose the unit after rounding, so 999,999 reads 1M rather than 1000K.
101 while (Math.abs(Number(trim(scaled))) >= 1e3 && unit < TOKEN_SUFFIXES.length - 1) {
102 scaled /= 1e3;
103 unit += 1;
104 }
105 return `${trim(scaled)}${TOKEN_SUFFIXES[unit]}`;
107​
108function trim(value: number): string {
109 const abs = Math.abs(value);
110 const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;
111 return value.toFixed(digits).replace(/\.0+$/, "");
113​
114export function formatPercent(share: number, digits = 1): string {
115 const percent = share * 100;
116 const smallest = 10 ** -digits;
117 if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`;
118 // A share short of the whole must not round up to 100%, as a nonzero one must not read 0%.
119 const largest = 100 - smallest;
120 if (percent < 100 && percent > largest) return `>${largest.toFixed(digits)}%`;
121 return `${percent.toFixed(digits)}%`;
123​
124export function formatDayShort(day: string, locale?: string): string {
125 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
126 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
127 const intlLocale = formatLocale(locale);
128 if (intlLocale !== "en-US") {
129 const date = new Date(Date.UTC(year, month - 1, dayOfMonth));
130 return Number.isNaN(date.getTime())
131 ? day
132 : dateTimeFormatter(intlLocale, { timeZone: "UTC", month: "short", day: "numeric" }).format(
133 date,
134 );
135 }
136 const MONTHS = [
137 "Jan",
138 "Feb",
139 "Mar",
140 "Apr",
141 "May",
142 "Jun",
143 "Jul",
144 "Aug",
145 "Sep",
146 "Oct",
147 "Nov",
148 "Dec",
149 ];
150 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
152​
153export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] {
154 const days: string[] = [];
155 const start = Date.parse(`${sinceDay}T00:00:00Z`);
156 const end = Date.parse(`${untilDay}T00:00:00Z`);
157 if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days;
158​
159 for (let cursor = start; cursor <= end; cursor += 86_400_000) {
160 days.push(new Date(cursor).toISOString().slice(0, 10));
161 }
162 return days;
164​
165const HOUR_MS = 60 * 60 * 1000;
166​
167const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
168​
169function dateTimeFormatter(
170 locale: string,
171 options: Intl.DateTimeFormatOptions,
172): Intl.DateTimeFormat {
173 if (options.timeZone === undefined) return new Intl.DateTimeFormat(locale, options);
174 const key = JSON.stringify([locale, options]);
175 let formatter = dateTimeFormatters.get(key);
176 if (formatter === undefined) {
177 formatter = new Intl.DateTimeFormat(locale, options);
178 if (dateTimeFormatters.size >= 16) dateTimeFormatters.clear();
179 dateTimeFormatters.set(key, formatter);
180 }
181 return formatter;
183​
184export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
185 const starts: string[] = [];
186 const start = Date.parse(sinceTime);
187 const end = Date.parse(untilTime);
188 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
189​
190 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
191 starts.push(new Date(cursor).toISOString());
192 }
193 return starts;
195​
196function hourOptions(hour12: boolean): Intl.DateTimeFormatOptions {
197 return hour12 ? { hour: "numeric", hour12: true } : { hour: "2-digit", hourCycle: "h23" };
199​
200function formatHour(formatter: Intl.DateTimeFormat, date: Date, hour12: boolean): string {
201 if (hour12) return formatter.format(date);
202 // Rolling buckets can start between whole hours, but their labels always name the hour.
203 return formatter
204 .formatToParts(date)
205 .map((part) => (part.type === "hour" ? `${part.value}:00` : part.value))
206 .join("");
208​
209/**
210 * Repeated wall-clock hours during a fall-back transition include their short zone name so the
211 * two distinct buckets remain distinguishable.
212 */
213export function formatHourShort(
214 hourStart: string,
215 timeZone?: string,
216 hour12 = true,
217 locale?: string,
218): string {
219 const instant = new Date(hourStart);
220 if (Number.isNaN(instant.getTime())) return hourStart;
221 const options = timeZone === undefined ? {} : { timeZone };
222 const intlLocale = formatLocale(locale);
223 const hourFormat = dateTimeFormatter(intlLocale, {
224 ...options,
225 ...hourOptions(hour12),
226 });
227 const wallHourFormat = dateTimeFormatter("en-CA", {
228 ...options,
229 year: "numeric",
230 month: "2-digit",
231 day: "2-digit",
232 hour: "2-digit",
233 hourCycle: "h23",
234 });
235 const wallHour = wallHourFormat.format(instant);
236 const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(
237 (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,
238 );
239​
240 if (!isRepeatedHour) return formatHour(hourFormat, instant, hour12);
241 const zonedHourFormat = dateTimeFormatter(intlLocale, {
242 ...options,
243 ...hourOptions(hour12),
244 timeZoneName: "short",
245 });
246 return formatHour(zonedHourFormat, instant, hour12);
248​
249export function formatDateTimeShort(
250 instant: string,
251 timeZone?: string,
252 hour12 = true,
253 locale?: string,
254): string {
255 const date = new Date(instant);
256 if (Number.isNaN(date.getTime())) return instant;
257 const dateHourFormat = dateTimeFormatter(formatLocale(locale), {
258 ...(timeZone === undefined ? {} : { timeZone }),
259 month: "short",
260 day: "numeric",
261 ...hourOptions(hour12),
262 });
263 return formatHour(dateHourFormat, date, hour12);
265​
266export function formatRelativeHourShort(
267 hourStart: string,
268 relativeTo: string,
269 timeZone?: string,
270 hour12 = true,
271 relativeDay: (hour: string, daysAgo: 0 | 1) => string = (hour, daysAgo) =>
272 daysAgo === 0 ? `${hour} today` : `${hour} yesterday`,
273 locale?: string,
274): string {
275 const instant = new Date(hourStart);
276 const reference = new Date(relativeTo);
277 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
278 return formatDateTimeShort(hourStart, timeZone, hour12, locale);
279 }
280​
281 const dayFormat = dateTimeFormatter("en-CA", {
282 ...(timeZone === undefined ? {} : { timeZone }),
283 year: "numeric",
284 month: "2-digit",
285 day: "2-digit",
286 });
287 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
288 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
289 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
290 const hour = formatHourShort(hourStart, timeZone, hour12, locale);
291​
292 if (calendarDaysAgo === 0 || calendarDaysAgo === 1) return relativeDay(hour, calendarDaysAgo);
293 return formatDateTimeShort(hourStart, timeZone, hour12, locale);
295​
296export function makeWindow(
297 days: number,
298 now = new Date(),
299 resolution: UsageResolution = "day",
300): UsageSummaryInput {
301 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
302 let format: Intl.DateTimeFormat;
303 try {
304 format = new Intl.DateTimeFormat("en-CA", {
305 timeZone,
306 year: "numeric",
307 month: "2-digit",
308 day: "2-digit",
309 });
310 } catch {
311 timeZone = "UTC";
312 format = new Intl.DateTimeFormat("en-CA", {
313 timeZone: "UTC",
314 year: "numeric",
315 month: "2-digit",
316 day: "2-digit",
317 });
318 }
319 const untilDay = format.format(now);
320 if (resolution === "hour") {
321 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
322 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
323 const sinceTime = new Date(sinceTimeMs);
324 const untilTime = new Date(untilTimeMs);
325 return {
326 sinceDay: UsageDay.make(format.format(sinceTime)),
327 untilDay: UsageDay.make(format.format(untilTime)),
328 timeZone,
329 resolution,
330 sinceTime: sinceTime.toISOString(),
331 untilTime: untilTime.toISOString(),
332 };
333 }
334 // Use calendar arithmetic in UTC; fixed millisecond subtraction crosses DST days incorrectly.
335 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
336 .split("-")
337 .map((part) => Number.parseInt(part, 10));
338 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
339 return {
340 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
341 untilDay: UsageDay.make(untilDay),
342 timeZone,
343 resolution,
344 };