Spaces:
Runtime error
Runtime error
File size: 17,055 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | "use client";
import { useTranslations } from "next-intl";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useProviderNodeMap, resolveProviderName } from "@/lib/display/useProviderNodeMap";
import {
CartesianGrid,
Legend,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import Card from "@/shared/components/Card";
import ProviderIcon from "@/shared/components/ProviderIcon";
import TimeRangeSelector from "@/shared/components/analytics/TimeRangeSelector";
import type {
ProviderUtilizationPoint,
ProviderUtilizationResponse,
UtilizationTimeRange,
} from "@/shared/types/utilization";
const RANGE_LABELS: Record<UtilizationTimeRange, string> = {
"1h": "Last hour",
"24h": "Last 24 hours",
"7d": "Last 7 days",
"30d": "Last 30 days",
};
const PROVIDER_COLORS = [
"var(--color-primary)",
"var(--color-accent)",
"var(--color-success)",
"var(--color-warning)",
"var(--color-error)",
"var(--color-text-muted)",
];
function formatTimestamp(value: string, range: UtilizationTimeRange) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return value;
}
if (range === "1h" || range === "24h") {
return new Intl.DateTimeFormat(undefined, {
hour: "2-digit",
minute: "2-digit",
}).format(date);
}
return new Intl.DateTimeFormat(undefined, {
month: "short",
day: "numeric",
}).format(date);
}
function formatTooltipTimestamp(value: string, range: UtilizationTimeRange) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return value;
}
return new Intl.DateTimeFormat(undefined, {
month: "short",
day: "numeric",
hour: range === "1h" || range === "24h" ? "2-digit" : undefined,
minute: range === "1h" || range === "24h" ? "2-digit" : undefined,
}).format(date);
}
function formatPercent(value: number) {
return `${Math.round(value)}%`;
}
function getLatestPoints(points: ProviderUtilizationPoint[]) {
const latestByProvider = new Map<string, ProviderUtilizationPoint>();
for (const point of points) {
const current = latestByProvider.get(point.provider);
if (!current || new Date(point.timestamp).getTime() > new Date(current.timestamp).getTime()) {
latestByProvider.set(point.provider, point);
}
}
return Array.from(latestByProvider.values()).sort((a, b) => b.remainingPct - a.remainingPct);
}
export default function ProviderUtilizationTab() {
const t = useTranslations("analytics");
const nodeMap = useProviderNodeMap();
const [range, setRange] = useState<UtilizationTimeRange>("24h");
const [aggregateBy, setAggregateBy] = useState<"provider" | "connection">("provider");
const [data, setData] = useState<ProviderUtilizationResponse | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchUtilization = useCallback(
async (
selectedRange: UtilizationTimeRange,
selectedAggregate: "provider" | "connection",
signal?: AbortSignal
) => {
setLoading(true);
try {
const response = await fetch(
`/api/usage/utilization?range=${selectedRange}&aggregateBy=${selectedAggregate}`,
{
signal,
cache: "no-store",
}
);
if (!response.ok) {
throw new Error("Failed to fetch utilization data");
}
const json = (await response.json()) as ProviderUtilizationResponse;
setData(json);
setError(null);
} catch (fetchError) {
if (fetchError instanceof DOMException && fetchError.name === "AbortError") {
return;
}
setError(
fetchError instanceof Error ? fetchError.message : "Failed to fetch utilization data"
);
setData(null);
} finally {
if (!signal?.aborted) {
setLoading(false);
}
}
},
[]
);
useEffect(() => {
const controller = new AbortController();
fetchUtilization(range, aggregateBy, controller.signal);
return () => controller.abort();
}, [fetchUtilization, range, aggregateBy]);
const providerColors = useMemo(() => {
const colors = new Map<string, string>();
for (const [index, provider] of (data?.providers ?? []).entries()) {
colors.set(provider, PROVIDER_COLORS[index % PROVIDER_COLORS.length]);
}
return colors;
}, [data?.providers]);
const chartData = useMemo(() => {
if (!data?.data.length) {
return [];
}
const byTimestamp = new Map<string, Record<string, number | string>>();
for (const point of data.data) {
const entry = byTimestamp.get(point.timestamp) ?? {
timestamp: point.timestamp,
label: formatTimestamp(point.timestamp, data.timeRange),
};
entry[point.provider] = Number(point.remainingPct.toFixed(2));
byTimestamp.set(point.timestamp, entry);
}
return Array.from(byTimestamp.entries())
.sort(([left], [right]) => new Date(left).getTime() - new Date(right).getTime())
.map(([, value]) => value);
}, [data]);
const latestPoints = useMemo(() => getLatestPoints(data?.data ?? []), [data?.data]);
const hasData = Boolean(data?.data.length);
const [retrying, setRetrying] = useState(false);
const handleRetry = useCallback(() => {
setRetrying(true);
setError(null);
fetchUtilization(range, aggregateBy).finally(() => setRetrying(false));
}, [range, aggregateBy, fetchUtilization]);
return (
<div className="flex flex-col gap-6">
<Card
title={t("providerUtilizationTitle")}
subtitle={RANGE_LABELS[range]}
icon="monitoring"
action={
<div className="flex items-center gap-4">
<div className="flex rounded-lg border border-border/50 bg-black/5 p-1 dark:bg-white/5">
<button
onClick={() => setAggregateBy("provider")}
className={`flex items-center gap-2 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${
aggregateBy === "provider"
? "bg-surface text-text-main shadow-sm"
: "text-text-muted hover:text-text-main"
}`}
>
<span className="material-symbols-outlined text-[14px]">dns</span>
Global View
</button>
<button
onClick={() => setAggregateBy("connection")}
className={`flex items-center gap-2 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${
aggregateBy === "connection"
? "bg-surface text-text-main shadow-sm"
: "text-text-muted hover:text-text-main"
}`}
>
<span className="material-symbols-outlined text-[14px]">account_tree</span>
Account Split
</button>
</div>
<TimeRangeSelector value={range} onChange={setRange} />
</div>
}
className="overflow-hidden"
>
{loading && !hasData ? (
<div className="flex min-h-80 items-center justify-center text-sm text-text-muted">
<span className="material-symbols-outlined mr-2 animate-spin text-[18px]">
progress_activity
</span>
Loading utilization data…
</div>
) : error ? (
<div className="flex min-h-80 flex-col items-center justify-center gap-4 text-center">
<span className="material-symbols-outlined text-[32px] text-error">error</span>
<div className="flex flex-col gap-1">
<p className="text-sm font-medium text-text-main">
{t("providerUtilizationFailedToLoad")}
</p>
<p className="text-sm text-text-muted">{error}</p>
</div>
<button
type="button"
onClick={handleRetry}
disabled={retrying}
className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed"
>
{retrying ? (
<>
<span className="material-symbols-outlined animate-spin text-[18px]">
progress_activity
</span>
Retrying…
</>
) : (
<>
<span className="material-symbols-outlined text-[18px]">refresh</span>
Retry
</>
)}
</button>
</div>
) : !hasData ? (
<div className="flex min-h-80 flex-col items-center justify-center gap-4 text-center">
<span className="material-symbols-outlined text-[40px] text-text-muted/70">
timeline
</span>
<div className="flex flex-col gap-2">
<p className="text-sm font-medium text-text-main">{t("providerUtilizationNoData")}</p>
<p className="max-w-md text-sm text-text-muted">
Provider quota snapshots will appear here after utilization data is collected.
</p>
</div>
<div className="rounded-lg border border-black/5 bg-black/[0.02] p-4 dark:border-white/5 dark:bg-white/[0.02]">
<p className="text-xs font-medium text-text-main">
{t("providerUtilizationGettingStarted")}
</p>
<ul className="mt-2 text-left text-xs text-text-muted">
<li className="flex items-start gap-2">
<span className="material-symbols-outlined text-[14px] text-primary">
check_circle
</span>
<span>
Connect providers via OAuth or API keys in <strong>Providers</strong>
</span>
</li>
<li className="mt-1 flex items-start gap-2">
<span className="material-symbols-outlined text-[14px] text-primary">
check_circle
</span>
<span>
Enable quota tracking by using the provider in a combo or direct request
</span>
</li>
<li className="mt-1 flex items-start gap-2">
<span className="material-symbols-outlined text-[14px] text-primary">
check_circle
</span>
<span>Data will appear automatically as quota snapshots are collected</span>
</li>
</ul>
</div>
</div>
) : (
<div className="flex flex-col gap-5">
<div className="h-80 w-full rounded-xl border border-black/5 bg-black/[0.02] px-3 py-4 dark:border-white/5 dark:bg-white/[0.02]">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={chartData} margin={{ top: 8, right: 16, bottom: 0, left: 0 }}>
<CartesianGrid
stroke="var(--color-border)"
strokeDasharray="3 3"
vertical={false}
/>
<XAxis
dataKey="timestamp"
tickFormatter={(value) => formatTimestamp(String(value), range)}
tick={{ fill: "var(--color-text-muted)", fontSize: 12 }}
axisLine={{ stroke: "var(--color-border)" }}
tickLine={{ stroke: "var(--color-border)" }}
minTickGap={24}
/>
<YAxis
domain={[0, 100]}
tickFormatter={formatPercent}
tick={{ fill: "var(--color-text-muted)", fontSize: 12 }}
axisLine={{ stroke: "var(--color-border)" }}
tickLine={{ stroke: "var(--color-border)" }}
width={44}
/>
<Tooltip
labelFormatter={(value) => formatTooltipTimestamp(String(value), range)}
formatter={(value: number, name: string) => [formatPercent(value), name]}
contentStyle={{
backgroundColor: "var(--color-surface)",
borderColor: "var(--color-border)",
borderRadius: 12,
color: "var(--color-text-main)",
boxShadow: "var(--shadow-soft)",
}}
itemStyle={{ color: "var(--color-text-main)" }}
labelStyle={{ color: "var(--color-text-main)", fontWeight: 600 }}
/>
<Legend />
{data?.providers.map((provider) => (
<Line
key={provider}
type="monotone"
dataKey={provider}
name={resolveProviderName(provider, nodeMap)}
stroke={providerColors.get(provider) ?? "var(--color-primary)"}
strokeWidth={2.5}
dot={false}
activeDot={{ r: 4, strokeWidth: 0 }}
connectNulls
/>
))}
</LineChart>
</ResponsiveContainer>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
{latestPoints.map((point) => {
const isLow = point.remainingPct <= 20;
return (
<Card.Section key={point.provider} className="flex h-full flex-col gap-4">
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-3">
<div className="flex h-11 w-11 items-center justify-center rounded-xl border border-black/5 bg-surface text-text-main dark:border-white/5">
<ProviderIcon providerId={point.provider} size={22} />
</div>
<div>
<p className="text-sm font-semibold text-text-main">
{resolveProviderName(point.provider, nodeMap)}
</p>
<p className="text-xs text-text-muted">
{t("providerUtilizationLatestSnapshot")}
</p>
</div>
</div>
<span
className={`inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium ${
point.isExhausted
? "bg-error/10 text-error"
: isLow
? "bg-warning/10 text-warning"
: "bg-success/10 text-success"
}`}
>
{point.isExhausted ? "Exhausted" : isLow ? "Low" : "Healthy"}
</span>
</div>
<div className="flex items-end justify-between gap-3">
<div>
<p className="text-3xl font-bold text-text-main">
{point.remainingPct.toFixed(point.remainingPct < 10 ? 1 : 0)}%
</p>
<p className="mt-1 text-xs text-text-muted">
{t("providerUtilizationRemainingCapacity")}
</p>
</div>
<div className="text-right text-xs text-text-muted">
<p>{formatTooltipTimestamp(point.timestamp, range)}</p>
<p className="mt-1 uppercase tracking-[0.14em]">{point.windowKey}</p>
</div>
</div>
<div className="flex flex-col gap-2">
<div className="h-2 overflow-hidden rounded-full bg-black/5 dark:bg-white/5">
<div
className={`h-full rounded-full transition-all ${
point.isExhausted ? "bg-error" : isLow ? "bg-warning" : "bg-primary"
}`}
style={{ width: `${Math.max(point.remainingPct, 0)}%` }}
/>
</div>
<div className="flex items-center justify-between text-xs text-text-muted">
<span>0%</span>
<span>Remaining quota</span>
<span>100%</span>
</div>
</div>
</Card.Section>
);
})}
</div>
</div>
)}
</Card>
</div>
);
}
|