mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 00:15:09 +03:00
feat(dashboard): persist one overview time range (#7277)
Consolidate the six overview range selectors into a single translated action-bar control beside Xray Metrics. Persist the validated selection per browser origin and panel base path with a safe 2m fallback, including unavailable storage. Restore the preference before history fetching and retain live status sampling while viewing longer ranges. Avoid overlapping delayed live-history seeds, track sampled scope epochs, use separate scoped/unscoped boundaries and reject stale responses. Cover scope transitions, clock skew bounds, storage failures and range propagation. Update English and Persian documentation without changing schema or backend API contracts. Validation: all 12 CI jobs and Docs CI passed on 2d3992766b277974f2cb4b4b44af1a6a456653dd; frontend 265 files / 2,330 tests, including 12 global-range, 11 ranged-history and 8 container-history cases. Browser restart and responsive/RTL checks reported by author, not independently rerun. Persistence is browser-local; arbitrary clock skew cannot guarantee complete live history. Closes #7276
This commit is contained in:
@@ -4,8 +4,6 @@ import { Card, theme } from 'antd';
|
||||
|
||||
import { Sparkline } from '@/components/viz';
|
||||
import type { Status } from '@/models/status';
|
||||
import OverviewRangeSelect from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface ConnectionsCardProps {
|
||||
status: Status;
|
||||
@@ -13,8 +11,6 @@ interface ConnectionsCardProps {
|
||||
udp: number[];
|
||||
labels: string[];
|
||||
isMobile: boolean;
|
||||
range: OverviewRange;
|
||||
onRangeChange: (range: OverviewRange) => void;
|
||||
}
|
||||
|
||||
export default function ConnectionsCard({
|
||||
@@ -23,8 +19,6 @@ export default function ConnectionsCard({
|
||||
udp,
|
||||
labels,
|
||||
isMobile,
|
||||
range,
|
||||
onRangeChange,
|
||||
}: ConnectionsCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
@@ -49,9 +43,6 @@ export default function ConnectionsCard({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ov-range-toolbar">
|
||||
<OverviewRangeSelect value={range} onChange={onRangeChange} />
|
||||
</div>
|
||||
<div className="ov-conn-legend">
|
||||
<div className="ov-legend-label">
|
||||
<span className="ov-swatch" style={{ background: accent }} />
|
||||
|
||||
@@ -133,6 +133,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ov-bar-range {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.ov-bar-sep {
|
||||
width: 1px;
|
||||
height: 20px;
|
||||
@@ -284,12 +290,13 @@
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.ov-range-toolbar {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 14px;
|
||||
right: var(--ov-pad);
|
||||
display: flex;
|
||||
.ov-range-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--ov-label);
|
||||
}
|
||||
|
||||
.ov-range-select {
|
||||
|
||||
@@ -30,6 +30,7 @@ import ThroughputCard from './ThroughputCard';
|
||||
import ConnectionsCard from './ConnectionsCard';
|
||||
import SystemStrip from './SystemStrip';
|
||||
import { mean, peak, useOverviewHistory } from './useOverviewHistory';
|
||||
import { OVERVIEW_RANGES } from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
import type { PanelUpdateInfo } from './PanelUpdateModal';
|
||||
const JsonEditor = lazy(() => import('@/components/form/JsonEditor'));
|
||||
@@ -52,6 +53,15 @@ function metricFoot(label: string, value: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function readHistoryRange(key: string): OverviewRange {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
return OVERVIEW_RANGES.find((range) => String(range) === saved) ?? 2;
|
||||
} catch {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
export default function IndexPage() {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, antdThemeConfig } = useTheme();
|
||||
@@ -86,7 +96,16 @@ export default function IndexPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadingTip, setLoadingTip] = useState(t('loading'));
|
||||
|
||||
const [historyRange, setHistoryRange] = useState<OverviewRange>(2);
|
||||
const historyRangeKey = '3x-ui:overview-range:' + (basePath || '/');
|
||||
const [historyRange, setHistoryRange] = useState(() => readHistoryRange(historyRangeKey));
|
||||
const changeHistoryRange = (range: OverviewRange) => {
|
||||
setHistoryRange(range);
|
||||
try {
|
||||
localStorage.setItem(historyRangeKey, String(range));
|
||||
} catch {
|
||||
// A blocked browser store should still allow changes for this visit.
|
||||
}
|
||||
};
|
||||
const history = useOverviewHistory(status, fetched && !fetchError, historyRange);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -213,6 +232,8 @@ export default function IndexPage() {
|
||||
panelVersion={displayVersion}
|
||||
latestVersion={panelUpdateInfo.latestVersion}
|
||||
updateAvailable={panelUpdateInfo.updateAvailable}
|
||||
historyRange={historyRange}
|
||||
onHistoryRangeChange={changeHistoryRange}
|
||||
onStopXray={stopXray}
|
||||
onRestartXray={restartXray}
|
||||
onOpenLogs={() => setLogsOpen(true)}
|
||||
@@ -259,8 +280,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.cpu}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<VitalTile
|
||||
icon={<DatabaseOutlined aria-hidden />}
|
||||
@@ -278,8 +297,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.mem}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<VitalTile
|
||||
icon={<SwapOutlined aria-hidden />}
|
||||
@@ -298,8 +315,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.swap}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<VitalTile
|
||||
icon={<HddOutlined aria-hidden />}
|
||||
@@ -317,8 +332,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.diskUsage}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -329,8 +342,6 @@ export default function IndexPage() {
|
||||
down={history.series.netDown}
|
||||
labels={history.labels}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<ConnectionsCard
|
||||
status={status}
|
||||
@@ -338,8 +349,6 @@ export default function IndexPage() {
|
||||
udp={history.series.udpCount}
|
||||
labels={history.labels}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { formatPanelVersion } from '@/lib/panel-version';
|
||||
import { activateOnKey } from '@/utils/a11y';
|
||||
import type { Status } from '@/models/status';
|
||||
import OverviewRangeSelect, { type OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface OverviewActionBarProps {
|
||||
status: Status;
|
||||
@@ -27,6 +28,8 @@ interface OverviewActionBarProps {
|
||||
panelVersion: string;
|
||||
latestVersion: string;
|
||||
updateAvailable: boolean;
|
||||
historyRange: OverviewRange;
|
||||
onHistoryRangeChange: (range: OverviewRange) => void;
|
||||
onStopXray: () => void | Promise<void>;
|
||||
onRestartXray: () => void;
|
||||
onOpenLogs: () => void;
|
||||
@@ -64,6 +67,8 @@ export default function OverviewActionBar({
|
||||
panelVersion,
|
||||
latestVersion,
|
||||
updateAvailable,
|
||||
historyRange,
|
||||
onHistoryRangeChange,
|
||||
onStopXray,
|
||||
onRestartXray,
|
||||
onOpenLogs,
|
||||
@@ -158,12 +163,6 @@ export default function OverviewActionBar({
|
||||
text: t('pages.index.systemHistoryTitle'),
|
||||
onClick: onOpenSystemHistory,
|
||||
},
|
||||
{
|
||||
key: 'metrics',
|
||||
icon: <ArrowUpOutlined aria-hidden />,
|
||||
text: t('pages.index.xrayMetricsTitle'),
|
||||
onClick: onOpenXrayMetrics,
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
@@ -241,6 +240,18 @@ export default function OverviewActionBar({
|
||||
))}
|
||||
</Fragment>
|
||||
))}
|
||||
<div className="ov-bar-range">
|
||||
<Button
|
||||
type="text"
|
||||
size={size}
|
||||
icon={<ArrowUpOutlined aria-hidden />}
|
||||
aria-label={t('pages.index.xrayMetricsTitle')}
|
||||
onClick={onOpenXrayMetrics}
|
||||
>
|
||||
{isMobile ? undefined : t('pages.index.xrayMetricsTitle')}
|
||||
</Button>
|
||||
<OverviewRangeSelect value={historyRange} onChange={onHistoryRangeChange} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -9,26 +9,27 @@ interface OverviewRangeSelectProps {
|
||||
onChange: (value: OverviewRange) => void;
|
||||
}
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: 2, label: '2m' },
|
||||
{ value: 5, label: '5m' },
|
||||
{ value: 30, label: '30m' },
|
||||
{ value: 60, label: '1h' },
|
||||
{ value: 360, label: '6h' },
|
||||
{ value: 720, label: '12h' },
|
||||
];
|
||||
const OPTIONS = OVERVIEW_RANGES.map((value) => ({
|
||||
value,
|
||||
label: value < 60 ? String(value) + 'm' : String(value / 60) + 'h',
|
||||
}));
|
||||
|
||||
export default function OverviewRangeSelect({ value, onChange }: OverviewRangeSelectProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const label = t('pages.index.timeRange');
|
||||
return (
|
||||
<Select
|
||||
aria-label={t('pages.index.timeRange')}
|
||||
className="ov-range-select"
|
||||
size="small"
|
||||
value={value}
|
||||
options={OPTIONS}
|
||||
onChange={(next: number) => onChange(next as OverviewRange)}
|
||||
/>
|
||||
<span className="ov-range-control">
|
||||
<span aria-hidden>{label}</span>
|
||||
<Select<OverviewRange>
|
||||
aria-label={label}
|
||||
className="ov-range-select"
|
||||
size="small"
|
||||
value={value}
|
||||
options={OPTIONS}
|
||||
virtual={false}
|
||||
onChange={(next) => onChange(next)}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,8 +7,6 @@ import { SizeFormatter } from '@/utils';
|
||||
import { Sparkline } from '@/components/viz';
|
||||
import type { Status } from '@/models/status';
|
||||
import { mean, peak } from './useOverviewHistory';
|
||||
import OverviewRangeSelect from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface ThroughputCardProps {
|
||||
status: Status;
|
||||
@@ -16,8 +14,6 @@ interface ThroughputCardProps {
|
||||
down: number[];
|
||||
labels: string[];
|
||||
isMobile: boolean;
|
||||
range: OverviewRange;
|
||||
onRangeChange: (range: OverviewRange) => void;
|
||||
}
|
||||
|
||||
export default function ThroughputCard({
|
||||
@@ -26,8 +22,6 @@ export default function ThroughputCard({
|
||||
down,
|
||||
labels,
|
||||
isMobile,
|
||||
range,
|
||||
onRangeChange,
|
||||
}: ThroughputCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
@@ -83,9 +77,6 @@ export default function ThroughputCard({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ov-range-toolbar">
|
||||
<OverviewRangeSelect value={range} onChange={onRangeChange} />
|
||||
</div>
|
||||
<div className="ov-wide-chart">
|
||||
<Sparkline
|
||||
data={available ? up : []}
|
||||
|
||||
@@ -4,8 +4,6 @@ import { Card, theme } from 'antd';
|
||||
|
||||
import { Sparkline } from '@/components/viz';
|
||||
import { mean, peak } from './useOverviewHistory';
|
||||
import OverviewRangeSelect from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface VitalTileProps {
|
||||
available?: boolean;
|
||||
@@ -18,12 +16,8 @@ interface VitalTileProps {
|
||||
footRight: ReactNode;
|
||||
data: number[];
|
||||
isMobile: boolean;
|
||||
range?: OverviewRange;
|
||||
onRangeChange?: (range: OverviewRange) => void;
|
||||
}
|
||||
|
||||
const ignoreRangeChange = () => undefined;
|
||||
|
||||
export default function VitalTile({
|
||||
available = true,
|
||||
icon,
|
||||
@@ -35,8 +29,6 @@ export default function VitalTile({
|
||||
footRight,
|
||||
data,
|
||||
isMobile,
|
||||
range = 2,
|
||||
onRangeChange = ignoreRangeChange,
|
||||
}: VitalTileProps) {
|
||||
const { token } = theme.useToken();
|
||||
const labelId = useId();
|
||||
@@ -74,9 +66,6 @@ export default function VitalTile({
|
||||
<span dir="auto">{available ? footRight : '—'}</span>
|
||||
</div>
|
||||
|
||||
<div className="ov-range-toolbar">
|
||||
<OverviewRangeSelect value={range} onChange={onRangeChange} />
|
||||
</div>
|
||||
<div className="ov-tile-chart">
|
||||
<Sparkline
|
||||
data={data}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { HttpUtil, TimeFormatter } from '@/utils';
|
||||
import type { Status } from '@/models/status';
|
||||
@@ -81,25 +81,35 @@ export function peak(values: number[]): number {
|
||||
|
||||
/* the seed bucket must be in the backend's allowedHistoryBuckets whitelist;
|
||||
2s is the smallest and matches the status poll cadence */
|
||||
function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
const [trend, setTrend] = useState<HistoryWindow>(emptyWindow);
|
||||
interface LiveHistoryWindow extends HistoryWindow {
|
||||
scopeEpoch: number;
|
||||
scopeSeeded: boolean;
|
||||
unscopedSeeded: boolean;
|
||||
scopeSampledAt?: number;
|
||||
}
|
||||
|
||||
const seededUnscoped = useRef(false);
|
||||
const seedState = useRef<{ scope: string; complete: boolean } | null>(null);
|
||||
function seedTimesBefore(times: Iterable<number>, firstSample: number, windowStart: number) {
|
||||
return [...new Set(times)]
|
||||
.filter((t) => t >= windowStart && t + SEED_BUCKET_SECONDS <= firstSample)
|
||||
.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function useLiveTrend(status: Status, hasData: boolean, enabled: boolean): OverviewHistory {
|
||||
const [trend, setTrend] = useState<LiveHistoryWindow>(() => ({
|
||||
...emptyWindow(),
|
||||
scopeEpoch: 0,
|
||||
scopeSeeded: false,
|
||||
unscopedSeeded: false,
|
||||
}));
|
||||
const { scopeEpoch, scopeSeeded, unscopedSeeded } = trend;
|
||||
const scope = status.resourceScope;
|
||||
|
||||
useEffect(() => {
|
||||
// The placeholder has no resource scope. Wait for the first real status,
|
||||
// then seed each scope once even if polling temporarily loses data.
|
||||
if (
|
||||
!hasData ||
|
||||
(seedState.current?.scope === status.resourceScope && seedState.current.complete)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
seedState.current = { scope: status.resourceScope, complete: false };
|
||||
if (!enabled || !hasData || scopeSeeded) return;
|
||||
let cancelled = false;
|
||||
const seedUnscoped = !seededUnscoped.current;
|
||||
const keys = seedUnscoped ? SERIES_KEYS : (['cpu', 'swap'] as const);
|
||||
const keys = unscopedSeeded ? (['cpu', 'swap'] as const) : SERIES_KEYS;
|
||||
|
||||
const seed = async () => {
|
||||
const responses = new Map<OverviewSeriesKey, HistoryPoint[]>();
|
||||
@@ -114,35 +124,45 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
}),
|
||||
);
|
||||
if (cancelled || responses.size === 0) return;
|
||||
seedState.current = { scope: status.resourceScope, complete: true };
|
||||
seededUnscoped.current = true;
|
||||
|
||||
let axis: HistoryPoint[] = [];
|
||||
for (const points of responses.values()) {
|
||||
if (points.length > axis.length) axis = points;
|
||||
}
|
||||
axis = tailWindow(axis);
|
||||
if (axis.length === 0) return;
|
||||
|
||||
const seedTimes = axis.map((p) => Number(p.t) || 0);
|
||||
const seedSeries = emptySeries();
|
||||
for (const key of SERIES_KEYS) {
|
||||
const byTs = new Map<number, number>();
|
||||
for (const p of responses.get(key) ?? []) byTs.set(Number(p.t) || 0, Number(p.v) || 0);
|
||||
seedSeries[key] =
|
||||
status.resourceScope && (key === 'cpu' || key === 'swap')
|
||||
? seedTimes.flatMap((ts) => (byTs.has(ts) ? [byTs.get(ts)!] : []))
|
||||
: seedTimes.map((ts) => byTs.get(ts) ?? 0);
|
||||
}
|
||||
|
||||
const axisTimes = axis.map((p) => Number(p.t));
|
||||
setTrend((prev) => {
|
||||
const merged = emptyWindow();
|
||||
merged.times = seedUnscoped ? tailWindow(seedTimes.concat(prev.times)) : prev.times;
|
||||
for (const key of SERIES_KEYS) {
|
||||
merged.series[key] =
|
||||
seedUnscoped || key === 'cpu' || key === 'swap'
|
||||
? tailWindow(seedSeries[key].concat(prev.series[key]))
|
||||
: prev.series[key];
|
||||
if (prev.scopeEpoch !== scopeEpoch) return prev;
|
||||
// With no server timestamp on live samples, only join buckets inside the browser's window.
|
||||
const windowStart =
|
||||
prev.times[prev.times.length - 1] - OVERVIEW_WINDOW * LIVE_BUCKET_SECONDS;
|
||||
const unscopedTimes = unscopedSeeded
|
||||
? []
|
||||
: seedTimesBefore(axisTimes, prev.times[0], windowStart);
|
||||
const firstScopedSample = prev.scopeSampledAt ?? prev.times[0];
|
||||
const merged = {
|
||||
...prev,
|
||||
scopeSeeded: true,
|
||||
unscopedSeeded: true,
|
||||
times: unscopedTimes.length ? tailWindow(unscopedTimes.concat(prev.times)) : prev.times,
|
||||
series: { ...prev.series },
|
||||
};
|
||||
for (const key of keys) {
|
||||
const scoped = key === 'cpu' || key === 'swap';
|
||||
const byTime = new Map(
|
||||
(responses.get(key) ?? []).map((p) => [Number(p.t), Number(p.v) || 0]),
|
||||
);
|
||||
const seedTimes = scoped
|
||||
? seedTimesBefore(
|
||||
scope ? byTime.keys() : [...axisTimes, ...byTime.keys()],
|
||||
firstScopedSample,
|
||||
windowStart,
|
||||
)
|
||||
: unscopedTimes;
|
||||
if (seedTimes.length) {
|
||||
merged.series[key] = tailWindow(
|
||||
seedTimes.map((t) => byTime.get(t) ?? 0).concat(prev.series[key]),
|
||||
);
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
@@ -152,7 +172,7 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hasData, status.resourceScope]);
|
||||
}, [enabled, hasData, scope, scopeEpoch, scopeSeeded, unscopedSeeded]);
|
||||
|
||||
// Each polled status is appended during render; an effect would show the
|
||||
// chart one sample behind the numbers beside it.
|
||||
@@ -160,10 +180,17 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
if (hasData && status !== sampledStatus) {
|
||||
setSampledStatus(status);
|
||||
setTrend((prev) => {
|
||||
const scopeChanged = sampledStatus && sampledStatus.resourceScope !== status.resourceScope;
|
||||
const sampledAt = Math.floor(Date.now() / 1000);
|
||||
const scopeChanged = sampledStatus !== null && sampledStatus.resourceScope !== scope;
|
||||
const point = sampleOf(status);
|
||||
const next = emptyWindow();
|
||||
next.times = tailWindow(prev.times.concat(Math.floor(Date.now() / 1000)));
|
||||
const next = {
|
||||
...prev,
|
||||
series: emptySeries(),
|
||||
scopeEpoch: prev.scopeEpoch + Number(scopeChanged),
|
||||
scopeSeeded: prev.scopeSeeded && !scopeChanged,
|
||||
scopeSampledAt: scopeChanged ? sampledAt : (prev.scopeSampledAt ?? sampledAt),
|
||||
};
|
||||
next.times = tailWindow(prev.times.concat(sampledAt));
|
||||
for (const key of SERIES_KEYS) {
|
||||
const scoped = key === 'cpu' || key === 'swap';
|
||||
const previous = scoped && scopeChanged ? [] : prev.series[key];
|
||||
@@ -270,7 +297,7 @@ export function useOverviewHistory(
|
||||
hasData: boolean,
|
||||
bucketSeconds: number = LIVE_BUCKET_SECONDS,
|
||||
): OverviewHistory {
|
||||
const live = useLiveTrend(status, hasData);
|
||||
const live = useLiveTrend(status, hasData, bucketSeconds === LIVE_BUCKET_SECONDS);
|
||||
const ranged = useRangedHistory(
|
||||
status,
|
||||
hasData && bucketSeconds !== LIVE_BUCKET_SECONDS,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
import { Status } from '@/models/status';
|
||||
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
|
||||
@@ -12,8 +12,11 @@ vi.mock('@/utils', async (importOriginal) => {
|
||||
|
||||
beforeEach(() => {
|
||||
get.mockReset();
|
||||
vi.spyOn(Date, 'now').mockReturnValue(10_000);
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('keeps missing samples out of trends and resets a changed metric scope', async () => {
|
||||
get.mockImplementation(async (path: string) => ({
|
||||
success: true,
|
||||
@@ -37,6 +40,7 @@ it('keeps missing samples out of trends and resets a changed metric scope', asyn
|
||||
expect(result.current.series.cpu).toEqual([10, 20]);
|
||||
rerender({ status: new Status({ cpu: 50 }) });
|
||||
expect(result.current.series.cpu).toEqual([50]);
|
||||
await act(async () => undefined);
|
||||
});
|
||||
|
||||
it('ignores a legacy seed that resolves after the scope changes', async () => {
|
||||
|
||||
@@ -39,8 +39,6 @@ describe('network traffic status', () => {
|
||||
down={[200]}
|
||||
labels={['12:00']}
|
||||
isMobile={false}
|
||||
range={2}
|
||||
onRangeChange={() => undefined}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
import IndexPage from '@/pages/index/IndexPage';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
const { get, chart } = vi.hoisted(() => ({ get: vi.fn(), chart: vi.fn() }));
|
||||
|
||||
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
|
||||
vi.mock('@/components/sponsor/SponsorSlot', () => ({ default: () => null }));
|
||||
vi.mock('@/components/viz', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('@/components/viz')>();
|
||||
return {
|
||||
...original,
|
||||
Sparkline: ({ data, data2 }: { data: number[]; data2?: number[] }) => {
|
||||
chart(data, data2);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock('@/api/queries/useStatusQuery', async () => {
|
||||
const { Status } = await import('@/models/status');
|
||||
const status = new Status({ cpu: 12, mem: { current: 10, total: 100 } });
|
||||
return { useStatusQuery: () => ({ status, fetched: true, fetchError: '', refresh: vi.fn() }) };
|
||||
});
|
||||
vi.mock('@/utils', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('@/utils')>();
|
||||
return { ...original, HttpUtil: { get, post: vi.fn().mockResolvedValue({ success: false }) } };
|
||||
});
|
||||
|
||||
const key = '3x-ui:overview-range:/test/';
|
||||
const rangeControl = () => screen.getByRole('combobox', { name: 'Time range' });
|
||||
const historyRequests = () =>
|
||||
get.mock.calls
|
||||
.map(([path]) => String(path))
|
||||
.filter((path) => /\/(overviewHistory|history)\//.test(path));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('X_UI_BASE_PATH', '/test/');
|
||||
window.localStorage.clear();
|
||||
get.mockReset();
|
||||
chart.mockClear();
|
||||
get.mockImplementation(async (path: string) => {
|
||||
if (path.includes('/overviewHistory/')) {
|
||||
const range = Number(path.split('/').at(-1));
|
||||
return {
|
||||
success: true,
|
||||
obj: Object.fromEntries(
|
||||
['cpu', 'mem', 'swap', 'diskUsage', 'netUp', 'netDown', 'tcpCount', 'udpCount'].map(
|
||||
(metric, i) => [metric, [{ t: 1, v: range + i }]],
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { success: true, obj: [] };
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('uses one action-bar selector to update all chart summaries and save the range', async () => {
|
||||
renderWithProviders(<IndexPage />);
|
||||
const control = rangeControl();
|
||||
const metrics = screen.getByRole('button', { name: 'Xray Metrics' });
|
||||
expect(metrics.closest('.ov-bar')?.contains(control)).toBe(true);
|
||||
|
||||
fireEvent.mouseDown(control);
|
||||
fireEvent.click(await screen.findByRole('option', { name: '30m' }));
|
||||
await waitFor(() => expect(window.localStorage.getItem(key)).toBe('30'));
|
||||
expect(
|
||||
await within(screen.getByRole('group', { name: 'CPU' })).findAllByText('30%'),
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
await within(screen.getByRole('group', { name: 'RAM' })).findAllByText('31%'),
|
||||
).toHaveLength(2);
|
||||
expect(historyRequests()).toContain('/panel/api/server/overviewHistory/30');
|
||||
for (const value of [30, 31, 32, 33]) {
|
||||
expect(chart).toHaveBeenCalledWith([value], undefined);
|
||||
}
|
||||
expect(chart).toHaveBeenCalledWith([34], [35]);
|
||||
expect(chart).toHaveBeenCalledWith([36], [37]);
|
||||
});
|
||||
|
||||
it.each([5, 30, 60, 360, 720])(
|
||||
'restores %im on mount without querying the default history window',
|
||||
async (range) => {
|
||||
window.localStorage.setItem(key, String(range));
|
||||
const first = renderWithProviders(<IndexPage />);
|
||||
await waitFor(() =>
|
||||
expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
|
||||
);
|
||||
first.unmount();
|
||||
get.mockClear();
|
||||
renderWithProviders(<IndexPage />);
|
||||
await waitFor(() =>
|
||||
expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([null, '2', '90', 'bad'])('uses the live range for %s', async (saved) => {
|
||||
if (saved !== null) window.localStorage.setItem(key, saved);
|
||||
window.localStorage.setItem('3x-ui:overview-range:/another-panel/', '720');
|
||||
renderWithProviders(<IndexPage />);
|
||||
expect(rangeControl()).toBeTruthy();
|
||||
await waitFor(() => expect(historyRequests()).toContain('/panel/api/server/history/cpu/2'));
|
||||
expect(historyRequests().some((path) => path.includes('/overviewHistory/'))).toBe(false);
|
||||
});
|
||||
|
||||
it('renders even when storage is blocked', async () => {
|
||||
vi.spyOn(Storage.prototype, 'getItem').mockImplementation((name) => {
|
||||
if (name === key) throw new DOMException('Storage blocked', 'SecurityError');
|
||||
return null;
|
||||
});
|
||||
renderWithProviders(<IndexPage />);
|
||||
expect(rangeControl()).toBeTruthy();
|
||||
await waitFor(() => expect(historyRequests()).toContain('/panel/api/server/history/cpu/2'));
|
||||
});
|
||||
|
||||
it('applies a new range and updates its charts when saving the preference is blocked', async () => {
|
||||
window.localStorage.setItem(key, '30');
|
||||
const originalSetItem = Storage.prototype.setItem;
|
||||
const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
|
||||
this: Storage,
|
||||
name,
|
||||
value,
|
||||
) {
|
||||
if (name === key) throw new DOMException('Storage blocked', 'QuotaExceededError');
|
||||
originalSetItem.call(this, name, value);
|
||||
});
|
||||
renderWithProviders(<IndexPage />);
|
||||
await waitFor(() => expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/30']));
|
||||
|
||||
fireEvent.mouseDown(rangeControl());
|
||||
fireEvent.click(await screen.findByRole('option', { name: '1h' }));
|
||||
|
||||
expect(setItem).toHaveBeenCalledWith(key, '60');
|
||||
expect(window.localStorage.getItem(key)).toBe('30');
|
||||
expect(
|
||||
await within(screen.getByRole('group', { name: 'CPU' })).findAllByText('60%'),
|
||||
).toHaveLength(2);
|
||||
expect(historyRequests()).toEqual([
|
||||
'/panel/api/server/overviewHistory/30',
|
||||
'/panel/api/server/overviewHistory/60',
|
||||
]);
|
||||
});
|
||||
@@ -2,7 +2,8 @@ import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
import { Status } from '@/models/status';
|
||||
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
|
||||
import { mean, peak, useOverviewHistory } from '@/pages/index/useOverviewHistory';
|
||||
import { TimeFormatter } from '@/utils';
|
||||
|
||||
const { get } = vi.hoisted(() => ({ get: vi.fn() }));
|
||||
vi.mock('@/utils', async (importOriginal) => {
|
||||
@@ -110,7 +111,232 @@ it('keeps sampling the live trend while a longer range is shown', async () => {
|
||||
);
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([90]));
|
||||
rerender({ status: new Status({ cpu: 12 }), bucket: 720 });
|
||||
rerender({ status: new Status({ cpu: 13 }), bucket: 2 });
|
||||
await act(async () => rerender({ status: new Status({ cpu: 13 }), bucket: 2 }));
|
||||
|
||||
expect(result.current.series.cpu).toEqual([11, 12, 13]);
|
||||
});
|
||||
|
||||
it('only seeds buckets older than the live samples collected while a longer range was open', async () => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
|
||||
try {
|
||||
get.mockImplementation(async (path: string) => ({
|
||||
success: true,
|
||||
obj: ranged(path)
|
||||
? rollups(90)
|
||||
: [
|
||||
{ t: 96, v: 20 },
|
||||
{ t: 98, v: 30 },
|
||||
{ t: 100, v: 91 },
|
||||
{ t: 102, v: 92 },
|
||||
{ t: 104, v: 93 },
|
||||
],
|
||||
}));
|
||||
const { result, rerender } = renderHook(
|
||||
({ status, bucket }) => useOverviewHistory(status, true, bucket),
|
||||
{ initialProps: { status: new Status({ cpu: 11 }), bucket: 60 } },
|
||||
);
|
||||
now.mockReturnValue(103_000);
|
||||
rerender({ status: new Status({ cpu: 12 }), bucket: 60 });
|
||||
now.mockReturnValue(105_000);
|
||||
rerender({ status: new Status({ cpu: 13 }), bucket: 2 });
|
||||
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([20, 30, 11, 12, 13]));
|
||||
expect(result.current.labels).toHaveLength(5);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('seeds a changed resource scope only up to its first status sample', async () => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
|
||||
try {
|
||||
get.mockResolvedValue({
|
||||
success: true,
|
||||
obj: [{ t: 98, v: 20 }],
|
||||
});
|
||||
const { result, rerender } = renderHook(({ status }) => useOverviewHistory(status, true, 2), {
|
||||
initialProps: { status: new Status({ cpu: 11, resourceScope: 'host' }) },
|
||||
});
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([20, 11]));
|
||||
|
||||
now.mockReturnValue(111_000);
|
||||
get.mockClear();
|
||||
get.mockResolvedValue({
|
||||
success: true,
|
||||
obj: [
|
||||
{ t: 108, v: 30 },
|
||||
{ t: 110, v: 99 },
|
||||
],
|
||||
});
|
||||
rerender({ status: new Status({ cpu: 12, resourceScope: 'container' }) });
|
||||
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([30, 12]));
|
||||
expect(get.mock.calls.map(([path]) => path)).toEqual([
|
||||
'/panel/api/server/history/cpu/2',
|
||||
'/panel/api/server/history/swap/2',
|
||||
]);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
const liveRequests = () =>
|
||||
get.mock.calls.map(([path]) => String(path)).filter((path) => path.includes('/history/'));
|
||||
|
||||
function sample(resourceScope: string, cpu: number, swap: number, up: number) {
|
||||
return new Status({
|
||||
resourceScope,
|
||||
cpu,
|
||||
swap: { current: swap, total: 100 },
|
||||
netIO: { up, down: 0 },
|
||||
});
|
||||
}
|
||||
|
||||
it('reseeds CPU and SWAP after sampling A → B → A while the live seed is disabled', async () => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
|
||||
try {
|
||||
get.mockResolvedValue({ success: true, obj: [{ t: 98, v: 7 }] });
|
||||
const { result, rerender } = renderHook(
|
||||
({ status, bucket }) => useOverviewHistory(status, true, bucket),
|
||||
{ initialProps: { status: sample('host', 11, 15, 8), bucket: 2 } },
|
||||
);
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([7, 11]));
|
||||
get.mockClear();
|
||||
|
||||
get.mockImplementation(async (path: string) => ({
|
||||
success: true,
|
||||
obj: ranged(path)
|
||||
? rollups(90)
|
||||
: [
|
||||
{ t: 104, v: path.includes('/cpu/') ? 24 : 32 },
|
||||
{ t: 108, v: 99 },
|
||||
],
|
||||
}));
|
||||
now.mockReturnValue(105_000);
|
||||
rerender({ status: sample('container', 41, 42, 9), bucket: 30 });
|
||||
now.mockReturnValue(109_000);
|
||||
const host = sample('host', 20, 36, 10);
|
||||
rerender({ status: host, bucket: 30 });
|
||||
expect(liveRequests()).toEqual([]);
|
||||
|
||||
rerender({ status: host, bucket: 2 });
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([24, 20]));
|
||||
expect(result.current.series.swap).toEqual([32, 36]);
|
||||
expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
|
||||
expect(result.current.labels).toHaveLength(4);
|
||||
expect(liveRequests()).toEqual([
|
||||
'/panel/api/server/history/cpu/2',
|
||||
'/panel/api/server/history/swap/2',
|
||||
]);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('seeds the first live visit from separate CPU/SWAP and unscoped cutoffs', async () => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
|
||||
try {
|
||||
get.mockImplementation(async (path: string) => ({
|
||||
success: true,
|
||||
obj: ranged(path)
|
||||
? rollups(90)
|
||||
: [
|
||||
{ t: 104, v: 88 },
|
||||
{ t: 98, v: 7 },
|
||||
{ t: 102, v: 24 },
|
||||
{ t: 100, v: 20 },
|
||||
{ t: 104, v: 28 },
|
||||
{ t: 106, v: 99 },
|
||||
{ t: 108, v: 99 },
|
||||
],
|
||||
}));
|
||||
const { result, rerender } = renderHook(
|
||||
({ status, bucket }) => useOverviewHistory(status, true, bucket),
|
||||
{ initialProps: { status: sample('host', 11, 15, 8), bucket: 30 } },
|
||||
);
|
||||
now.mockReturnValue(107_000);
|
||||
rerender({ status: sample('container', 30, 40, 9), bucket: 30 });
|
||||
expect(liveRequests()).toEqual([]);
|
||||
|
||||
now.mockReturnValue(109_000);
|
||||
rerender({ status: sample('container', 41, 43, 10), bucket: 2 });
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([7, 20, 24, 28, 30, 41]));
|
||||
expect(result.current.series.swap).toEqual([7, 20, 24, 28, 40, 43]);
|
||||
expect(mean(result.current.series.cpu)).toBe(25);
|
||||
expect(peak(result.current.series.swap)).toBe(43);
|
||||
expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
|
||||
expect(result.current.labels).toEqual([98, 101, 107, 109].map(TimeFormatter.formatClock));
|
||||
expect(liveRequests()).toHaveLength(metricKeys.length);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('discards late live and ranged responses through rapid range and scope changes', async () => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
|
||||
try {
|
||||
let releaseLive!: (msg: { success: boolean; obj: { t: number; v: number }[] }) => void;
|
||||
const oldLive = new Promise<{ success: boolean; obj: { t: number; v: number }[] }>(
|
||||
(resolve) => {
|
||||
releaseLive = resolve;
|
||||
},
|
||||
);
|
||||
let releaseRanged!: (msg: { success: boolean; obj: Rollups }) => void;
|
||||
const oldRanged = new Promise<{ success: boolean; obj: Rollups }>((resolve) => {
|
||||
releaseRanged = resolve;
|
||||
});
|
||||
get.mockReturnValue(oldLive);
|
||||
const { result, rerender } = renderHook(
|
||||
({ status, bucket }) => useOverviewHistory(status, true, bucket),
|
||||
{ initialProps: { status: sample('host', 11, 15, 8), bucket: 2 } },
|
||||
);
|
||||
|
||||
now.mockReturnValue(105_000);
|
||||
get.mockClear();
|
||||
get.mockReturnValue(oldRanged);
|
||||
rerender({ status: sample('container', 90, 91, 9), bucket: 30 });
|
||||
now.mockReturnValue(107_000);
|
||||
get.mockResolvedValue({ success: true, obj: rollups(44) });
|
||||
const host = sample('host', 20, 36, 10);
|
||||
rerender({ status: host, bucket: 60 });
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([44]));
|
||||
expect(liveRequests()).toEqual([]);
|
||||
|
||||
await act(async () => releaseRanged({ success: true, obj: rollups(99) }));
|
||||
expect(result.current.series.cpu).toEqual([44]);
|
||||
|
||||
get.mockResolvedValue({ success: true, obj: [{ t: 98, v: 7 }] });
|
||||
rerender({ status: host, bucket: 2 });
|
||||
await waitFor(() => expect(result.current.series.cpu).toEqual([7, 20]));
|
||||
await act(async () => releaseLive({ success: true, obj: [{ t: 96, v: 99 }] }));
|
||||
expect(result.current.series.cpu).toEqual([7, 20]);
|
||||
expect(result.current.series.swap).toEqual([7, 36]);
|
||||
expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
|
||||
expect(result.current.labels).toHaveLength(4);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['ahead', 2_300],
|
||||
['behind', 1_700],
|
||||
] as const)(
|
||||
'keeps live history ordered and bounded when the server clock is far %s',
|
||||
async (_, serverTime) => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(2_001_000);
|
||||
try {
|
||||
get.mockResolvedValue({ success: true, obj: [{ t: serverTime, v: 99 }] });
|
||||
const sampledHost = sample('host', 20, 36, 10);
|
||||
const { result } = renderHook(() => useOverviewHistory(sampledHost, true));
|
||||
await act(async () => undefined);
|
||||
expect(liveRequests()).toHaveLength(metricKeys.length);
|
||||
expect(result.current.series.cpu).toEqual([20]);
|
||||
expect(result.current.series.swap).toEqual([36]);
|
||||
expect(result.current.series.netUp).toEqual([10]);
|
||||
expect(result.current.labels).toEqual([TimeFormatter.formatClock(2_001)]);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -25,6 +25,8 @@ function renderBar(
|
||||
panelVersion="v3.10.1"
|
||||
latestVersion="v3.10.1"
|
||||
updateAvailable={false}
|
||||
historyRange={2}
|
||||
onHistoryRangeChange={() => undefined}
|
||||
onStopXray={onStopXray}
|
||||
onRestartXray={onRestartXray}
|
||||
onOpenLogs={noop}
|
||||
|
||||
@@ -21,6 +21,8 @@ describe('OverviewActionBar update tag', () => {
|
||||
panelVersion="v3.10.1"
|
||||
latestVersion="v3.10.2"
|
||||
updateAvailable
|
||||
historyRange={2}
|
||||
onHistoryRangeChange={() => undefined}
|
||||
onStopXray={noop}
|
||||
onRestartXray={noop}
|
||||
onOpenLogs={noop}
|
||||
|
||||
Reference in New Issue
Block a user