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

usageFormat.ts

297 lines9.7 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 type { UsageContractMismatch } 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​
20export function formatMalformedUsageWarning(count: number): string {
21 return `${count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`;
23​
24export function usageSourceMessages(sources: readonly UsageSource[]): readonly string[] {
25 const messages = new Set<string>();
26 const malformedBySource = new Map<string, number>();
27 for (const source of sources) {
28 if (
29 source.action ||
30 (source.status !== "partial" &&
31 source.status !== "failed" &&
32 source.fingerprint.provider !== "cursor" &&
33 !(source.status === "missing" && source.malformedRecords > 0))
34 ) {
35 continue;
36 }
37 let message = source.message;
38 if (source.malformedRecords > 0) {
39 const { hostId, provider, resolvedHomePath, volumeId } = source.fingerprint;
40 const key = JSON.stringify([hostId, provider, resolvedHomePath, volumeId]);
41 malformedBySource.set(
42 key,
43 Math.max(malformedBySource.get(key) ?? 0, source.malformedRecords),
44 );
45 // Servers also append this warning to message; retain any preceding read failure.
46 const warning = formatMalformedUsageWarning(source.malformedRecords);
47 if (message?.endsWith(warning)) message = message.slice(0, -warning.length).trim();
48 }
49 if (message) messages.add(message);
50 }
51 const malformedRecords = [...malformedBySource.values()].reduce(
52 (total, count) => total + count,
53 0,
54 );
55 if (malformedRecords > 0) messages.add(formatMalformedUsageWarning(malformedRecords));
56 return [...messages];
58​
59export function formatUsd(value: number): string {
60 return CURRENCY.format(value);
62​
63export function formatCount(value: number): string {
64 return INTEGER.format(Math.round(value));
66​
67export function formatTokens(value: number): string {
68 const abs = Math.abs(value);
69 if (abs >= 1e12) return `${trim(value / 1e12)}T`;
70 if (abs >= 1e9) return `${trim(value / 1e9)}B`;
71 if (abs >= 1e6) return `${trim(value / 1e6)}M`;
72 if (abs >= 1e3) return `${trim(value / 1e3)}K`;
73 return INTEGER.format(Math.round(value));
75​
76function trim(value: number): string {
77 const abs = Math.abs(value);
78 const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;
79 return value.toFixed(digits).replace(/\.0+$/, "");
81​
82export function formatPercent(share: number, digits = 1): string {
83 const percent = share * 100;
84 const smallest = 10 ** -digits;
85 if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`;
86 return `${percent.toFixed(digits)}%`;
88​
89export function formatUsageContractMismatch(
90 environmentLabel: string,
91 mismatch: Pick<UsageContractMismatch, "direction">,
92): string {
93 return mismatch.direction === "serverBehind"
94 ? `${environmentLabel} runs an older server version and is excluded from totals.`
95 : `This client is older than the server on ${environmentLabel}; its usage is excluded from totals.`;
97​
98export function formatDayShort(day: string): string {
99 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
100 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
101 const MONTHS = [
102 "Jan",
103 "Feb",
104 "Mar",
105 "Apr",
106 "May",
107 "Jun",
108 "Jul",
109 "Aug",
110 "Sep",
111 "Oct",
112 "Nov",
113 "Dec",
114 ];
115 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
117​
118export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] {
119 const days: string[] = [];
120 const start = Date.parse(`${sinceDay}T00:00:00Z`);
121 const end = Date.parse(`${untilDay}T00:00:00Z`);
122 if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days;
123​
124 for (let cursor = start; cursor <= end; cursor += 86_400_000) {
125 days.push(new Date(cursor).toISOString().slice(0, 10));
126 }
127 return days;
129​
130const HOUR_MS = 60 * 60 * 1000;
131​
132const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
133​
134function dateTimeFormatter(
135 locale: string,
136 options: Intl.DateTimeFormatOptions,
137): Intl.DateTimeFormat {
138 if (options.timeZone === undefined) return new Intl.DateTimeFormat(locale, options);
139 const key = JSON.stringify([locale, options]);
140 let formatter = dateTimeFormatters.get(key);
141 if (formatter === undefined) {
142 formatter = new Intl.DateTimeFormat(locale, options);
143 if (dateTimeFormatters.size >= 16) dateTimeFormatters.clear();
144 dateTimeFormatters.set(key, formatter);
145 }
146 return formatter;
148​
149export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
150 const starts: string[] = [];
151 const start = Date.parse(sinceTime);
152 const end = Date.parse(untilTime);
153 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
154​
155 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
156 starts.push(new Date(cursor).toISOString());
157 }
158 return starts;
160​
161function hourOptions(hour12: boolean): Intl.DateTimeFormatOptions {
162 return hour12 ? { hour: "numeric" } : { hour: "2-digit", hourCycle: "h23" };
164​
165function formatHour(formatter: Intl.DateTimeFormat, date: Date, hour12: boolean): string {
166 if (hour12) return formatter.format(date);
167 // Rolling buckets can start between whole hours, but their labels always name the hour.
168 return formatter
169 .formatToParts(date)
170 .map((part) => (part.type === "hour" ? `${part.value}:00` : part.value))
171 .join("");
173​
174/**
175 * Repeated wall-clock hours during a fall-back transition include their short zone name so the
176 * two distinct buckets remain distinguishable.
177 */
178export function formatHourShort(hourStart: string, timeZone?: string, hour12 = true): string {
179 const instant = new Date(hourStart);
180 if (Number.isNaN(instant.getTime())) return hourStart;
181 const options = timeZone === undefined ? {} : { timeZone };
182 const hourFormat = dateTimeFormatter("en-US", {
183 ...options,
184 ...hourOptions(hour12),
185 });
186 const wallHourFormat = dateTimeFormatter("en-CA", {
187 ...options,
188 year: "numeric",
189 month: "2-digit",
190 day: "2-digit",
191 hour: "2-digit",
192 hourCycle: "h23",
193 });
194 const wallHour = wallHourFormat.format(instant);
195 const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(
196 (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,
197 );
198​
199 if (!isRepeatedHour) return formatHour(hourFormat, instant, hour12);
200 const zonedHourFormat = dateTimeFormatter("en-US", {
201 ...options,
202 ...hourOptions(hour12),
203 timeZoneName: "short",
204 });
205 return formatHour(zonedHourFormat, instant, hour12);
207​
208export function formatDateTimeShort(instant: string, timeZone?: string, hour12 = true): string {
209 const date = new Date(instant);
210 if (Number.isNaN(date.getTime())) return instant;
211 const dateHourFormat = dateTimeFormatter("en-US", {
212 ...(timeZone === undefined ? {} : { timeZone }),
213 month: "short",
214 day: "numeric",
215 ...hourOptions(hour12),
216 });
217 return formatHour(dateHourFormat, date, hour12);
219​
220export function formatRelativeHourShort(
221 hourStart: string,
222 relativeTo: string,
223 timeZone?: string,
224 hour12 = true,
225): string {
226 const instant = new Date(hourStart);
227 const reference = new Date(relativeTo);
228 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
229 return formatDateTimeShort(hourStart, timeZone, hour12);
230 }
231​
232 const dayFormat = dateTimeFormatter("en-CA", {
233 ...(timeZone === undefined ? {} : { timeZone }),
234 year: "numeric",
235 month: "2-digit",
236 day: "2-digit",
237 });
238 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
239 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
240 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
241 const hour = formatHourShort(hourStart, timeZone, hour12);
242​
243 if (calendarDaysAgo === 0) return `${hour} today`;
244 if (calendarDaysAgo === 1) return `${hour} yesterday`;
245 return formatDateTimeShort(hourStart, timeZone, hour12);
247​
248export function makeWindow(
249 days: number,
250 now = new Date(),
251 resolution: UsageResolution = "day",
252): UsageSummaryInput {
253 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
254 let format: Intl.DateTimeFormat;
255 try {
256 format = new Intl.DateTimeFormat("en-CA", {
257 timeZone,
258 year: "numeric",
259 month: "2-digit",
260 day: "2-digit",
261 });
262 } catch {
263 timeZone = "UTC";
264 format = new Intl.DateTimeFormat("en-CA", {
265 timeZone: "UTC",
266 year: "numeric",
267 month: "2-digit",
268 day: "2-digit",
269 });
270 }
271 const untilDay = format.format(now);
272 if (resolution === "hour") {
273 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
274 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
275 const sinceTime = new Date(sinceTimeMs);
276 const untilTime = new Date(untilTimeMs);
277 return {
278 sinceDay: UsageDay.make(format.format(sinceTime)),
279 untilDay: UsageDay.make(format.format(untilTime)),
280 timeZone,
281 resolution,
282 sinceTime: sinceTime.toISOString(),
283 untilTime: untilTime.toISOString(),
284 };
285 }
286 // Use calendar arithmetic in UTC; fixed millisecond subtraction crosses DST days incorrectly.
287 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
288 .split("-")
289 .map((part) => Number.parseInt(part, 10));
290 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
291 return {
292 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
293 untilDay: UsageDay.make(untilDay),
294 timeZone,
295 resolution,
296 };