File size: 34,991 Bytes
ea775bd | 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 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 | import { useQuery } from "@tanstack/react-query";
import { Activity, AlertTriangle, Clock3, Layers, Link2, ShieldCheck, Waypoints } from "lucide-react";
import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Bar, BarChart, CartesianGrid, ComposedChart, Line, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { Badge } from "../../components/ui/Badge";
import { Card } from "../../components/ui/Card";
import { Select } from "../../components/ui/Select";
import { useI18n } from "../../i18n";
import { getCurrentLocale, isEnglishLocale } from "../../i18n/locale";
import { apiRequest } from "../../lib/api-client";
import { formatApiErrorMessage } from "../../lib/error-message";
import type {
HistoryAccessLatencyResponse,
HistoryLeaseLifetimeResponse,
HistoryRequestsItem,
HistoryResponse,
LatencyBucket,
RealtimeLeasesResponse,
SnapshotNodeLatencyDistribution,
SnapshotPlatformNodePool,
TimeWindow,
} from "../dashboard/types";
import type { Platform } from "./types";
type RangeKey = "1h" | "6h" | "24h";
type RangeOption = {
key: RangeKey;
label: string;
ms: number;
};
type PlatformHistoryBundle = {
requests: HistoryResponse<HistoryRequestsItem>;
accessLatency: HistoryAccessLatencyResponse;
leaseLifetime: HistoryLeaseLifetimeResponse;
};
type PlatformSnapshotBundle = {
nodePool: SnapshotPlatformNodePool;
nodeLatency: SnapshotNodeLatencyDistribution;
};
type TrendLineDefinition = {
dataKey: string;
name: string;
color: string;
};
type TrendLineChartProps = {
data: Array<Record<string, number | string>>;
lines: TrendLineDefinition[];
yTickFormatter?: (value: number) => string;
tooltipValueFormatter?: (value: number) => string;
emptyText: string;
};
type HistogramBarPoint = {
lower_ms: number;
upper_ms: number;
label: string;
count: number;
};
type LatencyHistogramProps = {
buckets: LatencyBucket[];
emptyText: string;
};
const RANGE_OPTIONS: RangeOption[] = [
{ key: "1h", label: "最近 1 小时", ms: 60 * 60 * 1000 },
{ key: "6h", label: "最近 6 小时", ms: 6 * 60 * 60 * 1000 },
{ key: "24h", label: "最近 24 小时", ms: 24 * 60 * 60 * 1000 },
];
const DEFAULT_REALTIME_REFRESH_MS = 15_000;
const MIN_REALTIME_REFRESH_MS = 1_000;
const DEFAULT_HISTORY_REFRESH_MS = 60_000;
const MIN_HISTORY_REFRESH_MS = 15_000;
const MAX_HISTORY_REFRESH_MS = 300_000;
const SNAPSHOT_REFRESH_MS = 5_000;
const MAX_TREND_POINTS = 360;
const MAX_HISTOGRAM_BUCKETS = 120;
const METRICS_BASE = "/api/v1/metrics";
const EMPTY_REALTIME_ITEMS: RealtimeLeasesResponse["items"] = [];
const EMPTY_HISTORY_REQUEST_ITEMS: HistoryResponse<HistoryRequestsItem>["items"] = [];
const EMPTY_ACCESS_LATENCY_ITEMS: HistoryAccessLatencyResponse["items"] = [];
const EMPTY_LEASE_LIFETIME_ITEMS: HistoryLeaseLifetimeResponse["items"] = [];
function toNumber(raw: unknown): number {
const value = Number(raw);
if (!Number.isFinite(value)) {
return 0;
}
return value;
}
function toString(raw: unknown): string {
return typeof raw === "string" ? raw : "";
}
function numberLocale(): string {
return isEnglishLocale(getCurrentLocale()) ? "en-US" : "zh-CN";
}
function formatCount(value: number): string {
return new Intl.NumberFormat(numberLocale()).format(Math.round(value));
}
function formatPercent(value: number): string {
return `${(value * 100).toFixed(1)}%`;
}
function formatShortNumber(value: number): string {
const abs = Math.abs(value);
if (abs >= 1_000_000_000) {
return `${(value / 1_000_000_000).toFixed(1)}G`;
}
if (abs >= 1_000_000) {
return `${(value / 1_000_000).toFixed(1)}M`;
}
if (abs >= 1_000) {
return `${(value / 1_000).toFixed(1)}K`;
}
return `${Math.round(value)}`;
}
function formatLatency(value: number): string {
if (!Number.isFinite(value) || value < 0) {
return "0ms";
}
if (value >= 1000) {
const seconds = value / 1000;
return `${seconds >= 10 ? seconds.toFixed(0) : seconds.toFixed(1)}s`;
}
return `${Math.round(value)}ms`;
}
function formatLeaseDuration(value: number): string {
if (!Number.isFinite(value) || value <= 0) {
return "0ms";
}
if (value < 1000) {
return `${Math.round(value)}ms`;
}
const english = isEnglishLocale(getCurrentLocale());
const wholeSeconds = Math.floor(value / 1000);
const days = Math.floor(wholeSeconds / 86_400);
const hours = Math.floor((wholeSeconds % 86_400) / 3_600);
const minutes = Math.floor((wholeSeconds % 3_600) / 60);
const seconds = wholeSeconds % 60;
if (english) {
if (days > 0) {
return `${days}d ${hours}h`;
}
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
if (minutes > 0) {
return `${minutes}m ${seconds}s`;
}
return `${seconds}s`;
}
if (days > 0) {
return `${days} 天 ${hours} 小时`;
}
if (hours > 0) {
return `${hours} 小时 ${minutes} 分钟`;
}
if (minutes > 0) {
return `${minutes} 分钟 ${seconds} 秒`;
}
return `${seconds} 秒`;
}
function formatClock(iso: string): string {
if (!iso) {
return "--";
}
const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return "--";
}
return new Intl.DateTimeFormat(numberLocale(), {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
}).format(date);
}
function parseTimestamp(input: string, fallback: number): number {
if (!input) {
return fallback;
}
const value = Date.parse(input);
if (Number.isNaN(value)) {
return fallback;
}
return value;
}
function sortTimeSeriesByTimestamp<T>(items: T[], getTimestamp: (item: T) => string): T[] {
return items
.map((item, index) => ({
item,
index,
sortKey: parseTimestamp(getTimestamp(item), index),
}))
.sort((left, right) => {
if (left.sortKey === right.sortKey) {
return left.index - right.index;
}
return left.sortKey - right.sortKey;
})
.map((entry) => entry.item);
}
function buildUniformSampleIndices(pointCount: number, maxPoints: number): number[] {
if (pointCount <= 0 || maxPoints <= 0) {
return [];
}
const capped = Math.min(pointCount, maxPoints);
if (capped === pointCount) {
return Array.from({ length: pointCount }, (_, index) => index);
}
if (capped === 1) {
return [0];
}
if (capped === 2) {
return [0, pointCount - 1];
}
const middleCount = capped - 2;
const span = pointCount - 2;
const selected = new Set<number>([0, pointCount - 1]);
for (let i = 0; i < middleCount; i += 1) {
const index = 1 + Math.floor((i * span) / middleCount);
selected.add(Math.min(pointCount - 2, index));
}
return Array.from(selected).sort((a, b) => a - b);
}
function downsampleArray<T>(items: T[], maxPoints: number): T[] {
if (items.length <= maxPoints) {
return items;
}
const indices = buildUniformSampleIndices(items.length, maxPoints);
return indices.map((index) => items[index] ?? items[items.length - 1]);
}
function sum(values: number[]): number {
return values.reduce((acc, value) => acc + value, 0);
}
function successRate(total: number, success: number): number {
if (total <= 0) {
return 0;
}
return success / total;
}
function latestValue(values: number[]): number {
if (!values.length) {
return 0;
}
return values[values.length - 1] ?? 0;
}
function normalizePositiveSeconds(seconds: number | undefined): number | null {
if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
return null;
}
return seconds;
}
function realtimeRefreshMs(stepSeconds: number | undefined): number {
const step = normalizePositiveSeconds(stepSeconds);
if (step === null) {
return DEFAULT_REALTIME_REFRESH_MS;
}
return Math.max(MIN_REALTIME_REFRESH_MS, Math.round(step * 1000));
}
function historyRefreshMs(bucketSeconds: Array<number | undefined>): number {
const buckets = bucketSeconds.map(normalizePositiveSeconds).filter((value): value is number => value !== null);
if (!buckets.length) {
return DEFAULT_HISTORY_REFRESH_MS;
}
const intervalMs = Math.round(Math.min(...buckets) * 1000);
return Math.min(MAX_HISTORY_REFRESH_MS, Math.max(MIN_HISTORY_REFRESH_MS, intervalMs));
}
function getTimeWindow(rangeKey: RangeKey): TimeWindow {
const option = RANGE_OPTIONS.find((item) => item.key === rangeKey) ?? RANGE_OPTIONS[1];
const to = new Date();
const from = new Date(to.getTime() - option.ms);
return {
from: from.toISOString(),
to: to.toISOString(),
};
}
function withWindow(path: string, window: TimeWindow, params?: Record<string, string>): string {
const query = new URLSearchParams({
from: window.from,
to: window.to,
...(params ?? {}),
});
return `${path}?${query.toString()}`;
}
function normalizeRealtimeLeasesResponse(raw: RealtimeLeasesResponse): RealtimeLeasesResponse {
return {
platform_id: toString(raw.platform_id),
step_seconds: toNumber(raw.step_seconds),
items: Array.isArray(raw.items)
? raw.items.map((item) => ({
ts: toString(item.ts),
active_leases: toNumber(item.active_leases),
}))
: [],
};
}
function normalizeHistoryRequestsResponse(raw: HistoryResponse<HistoryRequestsItem>): HistoryResponse<HistoryRequestsItem> {
return {
bucket_seconds: toNumber(raw.bucket_seconds),
items: Array.isArray(raw.items)
? raw.items.map((item) => ({
bucket_start: toString(item.bucket_start),
bucket_end: toString(item.bucket_end),
total_requests: toNumber(item.total_requests),
success_requests: toNumber(item.success_requests),
success_rate: toNumber(item.success_rate),
}))
: [],
};
}
function normalizeHistoryAccessLatencyResponse(raw: HistoryAccessLatencyResponse): HistoryAccessLatencyResponse {
return {
bucket_seconds: toNumber(raw.bucket_seconds),
bin_width_ms: toNumber(raw.bin_width_ms),
overflow_ms: toNumber(raw.overflow_ms),
items: Array.isArray(raw.items)
? raw.items.map((item) => ({
bucket_start: toString(item.bucket_start),
bucket_end: toString(item.bucket_end),
sample_count: toNumber(item.sample_count),
buckets: Array.isArray(item.buckets)
? item.buckets.map((bucket) => ({
le_ms: toNumber(bucket.le_ms),
count: toNumber(bucket.count),
}))
: [],
overflow_count: toNumber(item.overflow_count),
}))
: [],
};
}
function normalizeHistoryLeaseLifetimeResponse(raw: HistoryLeaseLifetimeResponse): HistoryLeaseLifetimeResponse {
return {
platform_id: toString(raw.platform_id),
bucket_seconds: toNumber(raw.bucket_seconds),
items: Array.isArray(raw.items)
? raw.items.map((item) => ({
bucket_start: toString(item.bucket_start),
bucket_end: toString(item.bucket_end),
sample_count: toNumber(item.sample_count),
p1_ms: toNumber(item.p1_ms),
p5_ms: toNumber(item.p5_ms),
p50_ms: toNumber(item.p50_ms),
}))
: [],
};
}
function normalizePlatformNodePoolSnapshot(raw: SnapshotPlatformNodePool): SnapshotPlatformNodePool {
return {
generated_at: toString(raw.generated_at),
platform_id: toString(raw.platform_id),
routable_node_count: toNumber(raw.routable_node_count),
egress_ip_count: toNumber(raw.egress_ip_count),
};
}
function normalizeNodeLatencySnapshot(raw: SnapshotNodeLatencyDistribution): SnapshotNodeLatencyDistribution {
return {
generated_at: toString(raw.generated_at),
scope: raw.scope === "platform" ? "platform" : "global",
platform_id: raw.platform_id ? toString(raw.platform_id) : undefined,
bin_width_ms: toNumber(raw.bin_width_ms),
overflow_ms: toNumber(raw.overflow_ms),
sample_count: toNumber(raw.sample_count),
buckets: Array.isArray(raw.buckets)
? raw.buckets.map((bucket) => ({
le_ms: toNumber(bucket.le_ms),
count: toNumber(bucket.count),
}))
: [],
overflow_count: toNumber(raw.overflow_count),
};
}
async function fetchPlatformRealtimeLeases(platformId: string, window: TimeWindow): Promise<RealtimeLeasesResponse> {
const data = await apiRequest<RealtimeLeasesResponse>(
withWindow(`${METRICS_BASE}/realtime/leases`, window, { platform_id: platformId }),
);
return normalizeRealtimeLeasesResponse(data);
}
async function fetchPlatformHistoryRequests(
platformId: string,
window: TimeWindow,
): Promise<HistoryResponse<HistoryRequestsItem>> {
const data = await apiRequest<HistoryResponse<HistoryRequestsItem>>(
withWindow(`${METRICS_BASE}/history/requests`, window, { platform_id: platformId }),
);
return normalizeHistoryRequestsResponse(data);
}
async function fetchPlatformHistoryAccessLatency(
platformId: string,
window: TimeWindow,
): Promise<HistoryAccessLatencyResponse> {
const data = await apiRequest<HistoryAccessLatencyResponse>(
withWindow(`${METRICS_BASE}/history/access-latency`, window, { platform_id: platformId }),
);
return normalizeHistoryAccessLatencyResponse(data);
}
async function fetchPlatformHistoryLeaseLifetime(
platformId: string,
window: TimeWindow,
): Promise<HistoryLeaseLifetimeResponse> {
const data = await apiRequest<HistoryLeaseLifetimeResponse>(
withWindow(`${METRICS_BASE}/history/lease-lifetime`, window, { platform_id: platformId }),
);
return normalizeHistoryLeaseLifetimeResponse(data);
}
async function fetchPlatformSnapshotNodePool(platformId: string): Promise<SnapshotPlatformNodePool> {
const query = new URLSearchParams({ platform_id: platformId });
const data = await apiRequest<SnapshotPlatformNodePool>(`${METRICS_BASE}/snapshots/platform-node-pool?${query.toString()}`);
return normalizePlatformNodePoolSnapshot(data);
}
async function fetchPlatformSnapshotNodeLatency(platformId: string): Promise<SnapshotNodeLatencyDistribution> {
const query = new URLSearchParams({ platform_id: platformId });
const data = await apiRequest<SnapshotNodeLatencyDistribution>(
`${METRICS_BASE}/snapshots/node-latency-distribution?${query.toString()}`,
);
return normalizeNodeLatencySnapshot(data);
}
type TrendTooltipContentProps = {
active?: boolean;
payload?: any[];
label?: string;
lines: TrendLineDefinition[];
valueFormatter: (value: number) => string;
};
function TrendTooltipContent({ active, payload, label, lines, valueFormatter }: TrendTooltipContentProps) {
if (!active || !payload?.length) {
return null;
}
return (
<div className="trend-tooltip">
<p className="trend-tooltip-time">{label ?? "--"}</p>
<div className="trend-tooltip-list">
{lines.map((line) => {
const entry = payload.find((item) => item.dataKey === line.dataKey);
const value = Number(entry?.value ?? 0);
const safeValue = Number.isFinite(value) ? value : 0;
return (
<p key={line.dataKey} className="trend-tooltip-row">
<span>
<i style={{ background: line.color }} />
{line.name}
</span>
<b>{valueFormatter(safeValue)}</b>
</p>
);
})}
</div>
</div>
);
}
function HistogramTooltipContent({ active, payload }: any) {
const { t } = useI18n();
if (!active || !payload?.length) {
return null;
}
const point = payload[0]?.payload as HistogramBarPoint | undefined;
const count = Number(payload[0]?.value ?? point?.count ?? 0);
const safeCount = Number.isFinite(count) ? count : 0;
const lowerBound = typeof point?.lower_ms === "number" && Number.isFinite(point.lower_ms) ? point.lower_ms : 0;
const upperBound = typeof point?.upper_ms === "number" && Number.isFinite(point.upper_ms) ? point.upper_ms : 0;
return (
<div className="histogram-tooltip">
<p className="histogram-tooltip-title">{`${formatCount(lowerBound)}~${formatCount(upperBound)} ms`}</p>
<p className="histogram-tooltip-value">{t("节点数 {{count}}", { count: formatCount(safeCount) })}</p>
</div>
);
}
function EmptyChart({ text }: { text: string }) {
return (
<div className="empty-box dashboard-empty">
<AlertTriangle size={14} />
<p>{text}</p>
</div>
);
}
function TrendLineChart({ data, lines, yTickFormatter, tooltipValueFormatter, emptyText }: TrendLineChartProps) {
if (!data.length || !lines.length) {
return <EmptyChart text={emptyText} />;
}
const formatYAxis = yTickFormatter ?? formatShortNumber;
const formatTooltip = tooltipValueFormatter ?? formatYAxis;
return (
<div className="trend-chart">
<div className="trend-svg">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={data} margin={{ top: 6, right: 8, bottom: 4, left: 8 }}>
<CartesianGrid stroke="rgba(65, 87, 121, 0.16)" strokeDasharray="2 4" vertical={false} />
<XAxis
dataKey="label"
interval="preserveStartEnd"
minTickGap={18}
tickMargin={4}
axisLine={false}
tickLine={false}
tick={{ fill: "#607191", fontSize: 11, fontWeight: 600 }}
/>
<YAxis
width="auto"
tickMargin={4}
axisLine={false}
tickLine={false}
tick={{ fill: "#657691", fontSize: 11, fontWeight: 600 }}
tickFormatter={(value) => formatYAxis(toNumber(value))}
domain={[0, "auto"]}
/>
<Tooltip
cursor={{ stroke: "rgba(15, 94, 216, 0.34)", strokeWidth: 1 }}
wrapperStyle={{ outline: "none" }}
content={<TrendTooltipContent lines={lines} valueFormatter={formatTooltip} />}
/>
{lines.map((line) => (
<Line
key={line.dataKey}
type="monotone"
dataKey={line.dataKey}
name={line.name}
stroke={line.color}
strokeWidth={1.8}
dot={false}
activeDot={{ r: 3, stroke: "#ffffff", strokeWidth: 1, fill: line.color }}
isAnimationActive={false}
connectNulls
/>
))}
</ComposedChart>
</ResponsiveContainer>
</div>
</div>
);
}
function compressHistogram(buckets: LatencyBucket[], limit = MAX_HISTOGRAM_BUCKETS): LatencyBucket[] {
if (buckets.length <= limit) {
return buckets;
}
const chunkSize = Math.ceil(buckets.length / limit);
const grouped: LatencyBucket[] = [];
for (let index = 0; index < buckets.length; index += chunkSize) {
const chunk = buckets.slice(index, index + chunkSize);
const total = chunk.reduce((acc, item) => acc + item.count, 0);
grouped.push({
le_ms: chunk[chunk.length - 1]?.le_ms ?? 0,
count: total,
});
}
return grouped;
}
function toHistogramBarPoints(buckets: LatencyBucket[]): HistogramBarPoint[] {
const compact = compressHistogram(buckets);
const inferredStep = compact.length >= 2 ? Math.max(1, compact[1].le_ms - compact[0].le_ms) : 0;
const isLegacyUpperInclusive = compact.length > 0 && inferredStep > 0 && compact[0].le_ms === inferredStep;
return compact.reduce<{ points: HistogramBarPoint[]; previousUpper: number }>(
(acc, bucket) => {
const lower = Math.max(0, acc.previousUpper + 1);
const rawUpper = isLegacyUpperInclusive ? bucket.le_ms - 1 : bucket.le_ms;
const upperInclusive = Math.max(lower, rawUpper);
return {
previousUpper: upperInclusive,
points: [
...acc.points,
{
lower_ms: lower,
upper_ms: upperInclusive,
label: `${lower}`,
count: Math.max(0, bucket.count),
},
],
};
},
{ points: [], previousUpper: -1 },
).points;
}
function LatencyHistogram({ buckets, emptyText }: LatencyHistogramProps) {
if (!buckets.length) {
return <EmptyChart text={emptyText} />;
}
const data = toHistogramBarPoints(buckets);
if (!data.length) {
return <EmptyChart text={emptyText} />;
}
return (
<div className="histogram-chart">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 6, right: 8, bottom: 4, left: 8 }}>
<CartesianGrid stroke="rgba(65, 87, 121, 0.16)" strokeDasharray="2 4" vertical={false} />
<XAxis
dataKey="label"
interval="preserveStartEnd"
minTickGap={14}
tickMargin={4}
axisLine={false}
tickLine={false}
tick={{ fill: "#607191", fontSize: 11, fontWeight: 600 }}
tickFormatter={(value) => formatLatency(toNumber(value))}
/>
<YAxis
width="auto"
allowDecimals={false}
tickMargin={4}
axisLine={false}
tickLine={false}
tick={{ fill: "#607191", fontSize: 11, fontWeight: 600 }}
tickFormatter={(value) => formatShortNumber(toNumber(value))}
/>
<Tooltip
cursor={{ fill: "rgba(15, 94, 216, 0.08)" }}
wrapperStyle={{ outline: "none" }}
content={<HistogramTooltipContent />}
/>
<Bar
dataKey="count"
fill="rgba(16, 118, 255, 0.86)"
radius={[5, 5, 0, 0]}
maxBarSize={28}
isAnimationActive={false}
/>
</BarChart>
</ResponsiveContainer>
</div>
);
}
export function PlatformMonitorPanel({ platform }: { platform: Platform }) {
const { locale, t } = useI18n();
const [rangeKey, setRangeKey] = useState<RangeKey>("6h");
const realtimeQuery = useQuery({
queryKey: ["platform-monitor", "realtime-leases", platform.id, rangeKey],
queryFn: async () => {
const window = getTimeWindow(rangeKey);
return fetchPlatformRealtimeLeases(platform.id, window);
},
refetchInterval: (query) => {
const data = query.state.data as RealtimeLeasesResponse | undefined;
return realtimeRefreshMs(data?.step_seconds);
},
placeholderData: (previous) => previous,
});
const historyQuery = useQuery({
queryKey: ["platform-monitor", "history", platform.id, rangeKey],
queryFn: async () => {
const window = getTimeWindow(rangeKey);
const [requests, accessLatency, leaseLifetime] = await Promise.all([
fetchPlatformHistoryRequests(platform.id, window),
fetchPlatformHistoryAccessLatency(platform.id, window),
fetchPlatformHistoryLeaseLifetime(platform.id, window),
]);
return {
requests,
accessLatency,
leaseLifetime,
} satisfies PlatformHistoryBundle;
},
refetchInterval: (query) => {
const data = query.state.data as PlatformHistoryBundle | undefined;
return historyRefreshMs([
data?.requests.bucket_seconds,
data?.accessLatency.bucket_seconds,
data?.leaseLifetime.bucket_seconds,
]);
},
placeholderData: (previous) => previous,
});
const snapshotQuery = useQuery({
queryKey: ["platform-monitor", "snapshots", platform.id],
queryFn: async () => {
const [nodePool, nodeLatency] = await Promise.all([
fetchPlatformSnapshotNodePool(platform.id),
fetchPlatformSnapshotNodeLatency(platform.id),
]);
return {
nodePool,
nodeLatency,
} satisfies PlatformSnapshotBundle;
},
refetchInterval: SNAPSHOT_REFRESH_MS,
placeholderData: (previous) => previous,
});
const monitorError = realtimeQuery.error ?? historyQuery.error ?? snapshotQuery.error;
const isInitialLoading =
!realtimeQuery.data &&
!historyQuery.data &&
!snapshotQuery.data &&
(realtimeQuery.isLoading || historyQuery.isLoading || snapshotQuery.isLoading);
const realtimeItems = realtimeQuery.data?.items ?? EMPTY_REALTIME_ITEMS;
const sortedRealtimeItems = useMemo(
() => sortTimeSeriesByTimestamp(realtimeItems, (item) => item.ts),
[realtimeItems],
);
const requestsItems = historyQuery.data?.requests.items ?? EMPTY_HISTORY_REQUEST_ITEMS;
const sortedRequestsItems = useMemo(
() => sortTimeSeriesByTimestamp(requestsItems, (item) => item.bucket_start),
[requestsItems],
);
const accessLatencyItems = historyQuery.data?.accessLatency.items ?? EMPTY_ACCESS_LATENCY_ITEMS;
const sortedAccessLatencyItems = useMemo(
() => sortTimeSeriesByTimestamp(accessLatencyItems, (item) => item.bucket_start),
[accessLatencyItems],
);
const leaseLifetimeItems = historyQuery.data?.leaseLifetime.items ?? EMPTY_LEASE_LIFETIME_ITEMS;
const sortedLeaseLifetimeItems = useMemo(
() => sortTimeSeriesByTimestamp(leaseLifetimeItems, (item) => item.bucket_start),
[leaseLifetimeItems],
);
const latestActiveLeases = latestValue(sortedRealtimeItems.map((item) => item.active_leases));
const totalRequests = sum(sortedRequestsItems.map((item) => item.total_requests));
const successRequests = sum(sortedRequestsItems.map((item) => item.success_requests));
const requestSuccessRatio = successRate(totalRequests, successRequests);
const latestLeaseLifetime = sortedLeaseLifetimeItems[sortedLeaseLifetimeItems.length - 1];
const latestP50LeaseMs = latestLeaseLifetime?.p50_ms ?? 0;
const latestAccessLatency = sortedAccessLatencyItems[sortedAccessLatencyItems.length - 1];
const snapshotNodePool = snapshotQuery.data?.nodePool;
const snapshotLatency = snapshotQuery.data?.nodeLatency;
const leaseTrendData = useMemo(() => {
return downsampleArray(sortedRealtimeItems, MAX_TREND_POINTS).map((item) => ({
label: formatClock(item.ts),
active_leases: item.active_leases,
}));
}, [sortedRealtimeItems, locale]);
const requestTrendData = useMemo(() => {
return downsampleArray(sortedRequestsItems, MAX_TREND_POINTS).map((item) => ({
label: formatClock(item.bucket_start),
total_requests: item.total_requests,
success_requests: item.success_requests,
}));
}, [sortedRequestsItems, locale]);
const leaseLifetimeTrendData = useMemo(() => {
return downsampleArray(sortedLeaseLifetimeItems, MAX_TREND_POINTS).map((item) => ({
label: formatClock(item.bucket_start),
p1_ms: item.p1_ms,
p5_ms: item.p5_ms,
p50_ms: item.p50_ms,
}));
}, [sortedLeaseLifetimeItems, locale]);
return (
<section className="platform-drawer-section platform-monitor-section">
<div className="platform-drawer-section-head platform-monitor-head">
<div>
<h4>{t("平台监控")}</h4>
<p>{t("查看当前平台的租约、请求成功率、延迟和节点情况。")}</p>
</div>
<label className="platform-monitor-range" htmlFor="platform-monitor-range">
<span>{t("时间范围")}</span>
<Select
id="platform-monitor-range"
value={rangeKey}
onChange={(event) => setRangeKey(event.target.value as RangeKey)}
>
{RANGE_OPTIONS.map((option) => (
<option key={option.key} value={option.key}>
{t(option.label)}
</option>
))}
</Select>
</label>
</div>
{monitorError ? (
<div className="callout callout-error">
<AlertTriangle size={14} />
<span>{formatApiErrorMessage(monitorError, t)}</span>
</div>
) : null}
<div className="platform-monitor-kpi-grid">
<Card className="platform-monitor-kpi-card">
<div className="dashboard-kpi-icon lease">
<Layers size={18} />
</div>
<div>
<p className="platform-monitor-kpi-label">{t("活跃租约")}</p>
<p className="platform-monitor-kpi-value">{formatCount(latestActiveLeases)}</p>
<p className="platform-monitor-kpi-sub">{t("当前实时值")}</p>
</div>
</Card>
<Card className="platform-monitor-kpi-card">
<div className="dashboard-kpi-icon shield">
<ShieldCheck size={18} />
</div>
<div>
<p className="platform-monitor-kpi-label">{t("请求成功率")}</p>
<p className="platform-monitor-kpi-value">{formatPercent(requestSuccessRatio)}</p>
<p className="platform-monitor-kpi-sub">
{t("成功")} {formatCount(successRequests)} / {t("总计")} {formatCount(totalRequests)}
</p>
</div>
</Card>
<Card className="platform-monitor-kpi-card">
<div className="dashboard-kpi-icon gauge">
<Waypoints size={18} />
</div>
<div>
<p className="platform-monitor-kpi-label">{t("可路由节点")}</p>
<p className="platform-monitor-kpi-value">{formatCount(snapshotNodePool?.routable_node_count ?? 0)}</p>
<p className="platform-monitor-kpi-sub">{t("出口 IP")} {formatCount(snapshotNodePool?.egress_ip_count ?? 0)}</p>
</div>
<Link to={`/nodes?platform_id=${encodeURIComponent(platform.id)}`} className="platform-monitor-kpi-link">
<Link2 size={14} />
<span>{t("可路由节点")}</span>
</Link>
</Card>
<Card className="platform-monitor-kpi-card">
<div className="dashboard-kpi-icon waves">
<Clock3 size={18} />
</div>
<div>
<p className="platform-monitor-kpi-label">{t("租约 P50 存活时长")}</p>
<p className="platform-monitor-kpi-value">{formatLeaseDuration(latestP50LeaseMs)}</p>
<p className="platform-monitor-kpi-sub">{t("历史租约时长统计")}</p>
</div>
</Card>
</div>
<div className="platform-monitor-grid">
<Card className="dashboard-panel">
<div className="dashboard-panel-header">
<h3>{t("活跃租约趋势")}</h3>
<p>{t("平台实时租约数量")}</p>
</div>
<TrendLineChart
data={leaseTrendData}
emptyText={t("暂无租约实时数据")}
yTickFormatter={formatShortNumber}
lines={[{ dataKey: "active_leases", name: t("活跃租约"), color: "#2068f6" }]}
/>
</Card>
<Card className="dashboard-panel">
<div className="dashboard-panel-header">
<h3>{t("请求统计")}</h3>
<p>{t("总请求数 / 成功请求数")}</p>
</div>
<TrendLineChart
data={requestTrendData}
emptyText={t("暂无请求统计数据")}
yTickFormatter={formatShortNumber}
lines={[
{ dataKey: "total_requests", name: t("总请求数"), color: "#2467e4" },
{ dataKey: "success_requests", name: t("成功请求数"), color: "#0f9d8b" },
]}
/>
<div className="dashboard-summary-inline">
<span>{t("总请求")} {formatCount(totalRequests)}</span>
<span>{t("成功请求")} {formatCount(successRequests)}</span>
</div>
</Card>
<Card className="dashboard-panel">
<div className="dashboard-panel-header">
<h3>{t("租约存活分位趋势")}</h3>
<p>P1 / P5 / P50</p>
</div>
<TrendLineChart
data={leaseLifetimeTrendData}
emptyText={t("暂无租约生命周期数据")}
yTickFormatter={formatLatency}
tooltipValueFormatter={formatLeaseDuration}
lines={[
{ dataKey: "p1_ms", name: "P1", color: "#2d63d8" },
{ dataKey: "p5_ms", name: "P5", color: "#0f9d8b" },
{ dataKey: "p50_ms", name: "P50", color: "#f18f01" },
]}
/>
</Card>
<Card className="dashboard-panel">
<div className="dashboard-panel-header">
<h3>{t("平台节点快照")}</h3>
<p>{t("当前平台节点池与延迟样本")}</p>
</div>
<div className="platform-monitor-snapshot-list">
<div>
<span>{t("可路由节点数")}</span>
<p>{formatCount(snapshotNodePool?.routable_node_count ?? 0)}</p>
</div>
<div>
<span>{t("出口 IP 数")}</span>
<p>{formatCount(snapshotNodePool?.egress_ip_count ?? 0)}</p>
</div>
<div>
<span>{t("延迟样本数")}</span>
<p>{formatCount(snapshotLatency?.sample_count ?? 0)}</p>
</div>
<div>
<span>{t("快照更新时间")}</span>
<p>{snapshotLatency?.generated_at ? formatClock(snapshotLatency.generated_at) : "--"}</p>
</div>
</div>
</Card>
<Card className="dashboard-panel platform-monitor-span-2">
<div className="dashboard-panel-header">
<h3>{t("访问延迟分布(历史最新桶)")}</h3>
<p>{t("历史访问延迟分布")}</p>
</div>
<LatencyHistogram buckets={latestAccessLatency?.buckets ?? []} emptyText={t("暂无访问延迟分布数据")} />
<div className="dashboard-summary-inline">
<span>{t("时间")} {latestAccessLatency ? formatClock(latestAccessLatency.bucket_end) : "--"}</span>
<span>{t("样本")} {formatCount(latestAccessLatency?.sample_count ?? 0)}</span>
<span>{t("溢出")} {formatCount(latestAccessLatency?.overflow_count ?? 0)}</span>
</div>
</Card>
<Card className="dashboard-panel platform-monitor-span-2">
<div className="dashboard-panel-header">
<h3>{t("节点延迟分布(实时快照)")}</h3>
<p>{t("实时节点延迟分布快照")}</p>
</div>
<LatencyHistogram buckets={snapshotLatency?.buckets ?? []} emptyText={t("暂无节点延迟快照数据")} />
<div className="dashboard-summary-inline">
<span>{t("样本")} {formatCount(snapshotLatency?.sample_count ?? 0)}</span>
<span>{t("溢出")} {formatCount(snapshotLatency?.overflow_count ?? 0)}</span>
<span>{t("分桶")} {formatCount(snapshotLatency?.bin_width_ms ?? 0)}ms</span>
</div>
</Card>
</div>
{isInitialLoading ? (
<div className="callout callout-warning">
<Activity size={14} />
<span>{t("平台监控数据加载中...")}</span>
</div>
) : null}
{(realtimeQuery.isFetching || historyQuery.isFetching || snapshotQuery.isFetching) && !isInitialLoading ? (
<div className="platform-monitor-refreshing">
<Badge variant="warning">{t("监控数据刷新中")}</Badge>
</div>
) : null}
</section>
);
}
|