mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 00:15:09 +03:00
perf(frontend): reuse inbound client rollups (#7288)
Cache online-independent client rollups by inbound row identity, reuse unchanged per-GUID online sets, and update only affected online overlays. Defer email popover rendering until opened and cooperatively schedule large-list rollups. Keep the table mounted during structural refresh and detail hydration, withholding mismatched-generation counts and guarding delete-all confirmations. Preserve search, node filters and selection, and use the current cache for subscribed WebSocket updates. Retain #7289's unavailable, pending, idle, legacy and partial-report attribution semantics. Validated on the reviewed head: all 12 CI jobs passed, including 2,338 frontend tests, ten identity regressions, the synthetic 120,000-membership Chromium story, PostgreSQL online attribution regressions, race checks, and Xray/node E2E. Includes test-only stabilization of existing relay and Telegram assertions. Production latency improvement has not been independently measured against main. Fixes #7281.
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
import { useState } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect } from 'storybook/test';
|
||||
|
||||
import { keys } from '@/api/queryKeys';
|
||||
|
||||
import { useInbounds } from './useInbounds';
|
||||
|
||||
const meta = { title: 'Inbounds/Client rollup performance' } satisfies Meta;
|
||||
export default meta;
|
||||
|
||||
function Rollups() {
|
||||
const { dbInbounds, clientCount, applyTrafficEvent } = useInbounds();
|
||||
const [input, setInput] = useState('');
|
||||
return (
|
||||
<>
|
||||
<label>
|
||||
Filter
|
||||
<input value={input} onChange={(event) => setInput(event.target.value)} />
|
||||
</label>
|
||||
<p role="status">
|
||||
{clientCount[30]
|
||||
? 'Rollups ready'
|
||||
: dbInbounds.length
|
||||
? 'Calculating rollups'
|
||||
: 'Waiting for inbounds'}
|
||||
</p>
|
||||
<button
|
||||
onClick={() =>
|
||||
applyTrafficEvent({
|
||||
onlineByGuid: { node: ['client-3999@example.test'] },
|
||||
activeInbounds: { node: ['in-30'] },
|
||||
})
|
||||
}
|
||||
>
|
||||
Apply online update
|
||||
</button>
|
||||
<div>Last inbound online: {clientCount[30]?.online.length ?? '…'}</div>
|
||||
<div>First inbound online: {clientCount[1]?.online.length ?? '…'}</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Fixture() {
|
||||
const [queryClient] = useState(() => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(keys.settings.defaults(), {});
|
||||
client.setQueryData(keys.inbounds.slim(), []);
|
||||
client.setQueryData(keys.clients.onlines(), []);
|
||||
client.setQueryData(keys.clients.onlinesByGuid(), {});
|
||||
client.setQueryData(keys.clients.activeInbounds(), {});
|
||||
client.setQueryData(keys.clients.lastOnline(), {});
|
||||
return client;
|
||||
});
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<button
|
||||
onClick={() => {
|
||||
const clients = Array.from({ length: 4_000 }, (_, i) => ({
|
||||
email: 'client-' + i + '@example.test',
|
||||
enable: true,
|
||||
comment: 'shared client',
|
||||
}));
|
||||
const settings = JSON.stringify({ clients });
|
||||
queryClient.setQueryData(
|
||||
keys.inbounds.slim(),
|
||||
Array.from({ length: 30 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
protocol: 'vless',
|
||||
enable: true,
|
||||
settings,
|
||||
originNodeGuid: 'node',
|
||||
tag: 'in-' + (i + 1),
|
||||
clientStats: clients.map(({ email }) => ({
|
||||
email,
|
||||
up: 1,
|
||||
down: 2,
|
||||
total: 0,
|
||||
expiryTime: 0,
|
||||
enable: true,
|
||||
})),
|
||||
})),
|
||||
);
|
||||
}}
|
||||
>
|
||||
Load 120,000 memberships
|
||||
</button>
|
||||
<Rollups />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export const LargeDeployment: StoryObj<typeof meta> = {
|
||||
render: () => <Fixture />,
|
||||
play: async ({ canvas, userEvent }) => {
|
||||
const start = performance.now();
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Load 120,000 memberships' }));
|
||||
await userEvent.type(canvas.getByRole('textbox', { name: 'Filter' }), 'a');
|
||||
const responsiveAt = performance.now();
|
||||
await canvas.findByText('Rollups ready');
|
||||
const readyAt = performance.now();
|
||||
const updateAt = performance.now();
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Apply online update' }));
|
||||
await canvas.findByText('Last inbound online: 1');
|
||||
await expect(canvas.getByText('First inbound online: 0')).toBeVisible();
|
||||
await expect(canvas.getByRole('textbox', { name: 'Filter' })).toHaveValue('a');
|
||||
console.info('120,000 memberships (ms)', {
|
||||
input: Math.round(responsiveAt - start),
|
||||
initial: Math.round(readyAt - start),
|
||||
update: Math.round(performance.now() - updateAt),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -89,6 +89,7 @@ export default function InboundsPage() {
|
||||
fetchError,
|
||||
dbInbounds,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
onlineClients,
|
||||
lastOnlineMap,
|
||||
inboundSpeed,
|
||||
@@ -558,7 +559,8 @@ export default function InboundsPage() {
|
||||
|
||||
const confirmDelAllClients = useCallback(
|
||||
(dbInbound: DBInbound) => {
|
||||
const count = clientCount[dbInbound.id]?.clients || 0;
|
||||
const count = clientCount[dbInbound.id]?.clients;
|
||||
if (count === undefined || count === 0) return;
|
||||
modal.confirm({
|
||||
title: t('pages.inbounds.delAllClientsConfirmTitle', { remark: dbInbound.remark, count }),
|
||||
content: t('pages.inbounds.delAllClientsConfirmContent'),
|
||||
@@ -796,6 +798,7 @@ export default function InboundsPage() {
|
||||
<InboundList
|
||||
dbInbounds={dbInbounds}
|
||||
clientCount={clientCount}
|
||||
clientCountsPending={clientCountsPending}
|
||||
onlineClients={onlineClients}
|
||||
lastOnlineMap={lastOnlineMap}
|
||||
inboundSpeed={inboundSpeed}
|
||||
|
||||
@@ -50,6 +50,7 @@ function HostRemarksSuffix({ remarks }: { remarks: string[] }) {
|
||||
export default function InboundList({
|
||||
dbInbounds,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
lastOnlineMap: _lastOnlineMap,
|
||||
inboundSpeed,
|
||||
expireDiff,
|
||||
@@ -173,6 +174,7 @@ export default function InboundList({
|
||||
nodesById,
|
||||
hostRemarksByInboundId,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
inboundSpeed,
|
||||
subEnable,
|
||||
expireDiff,
|
||||
|
||||
@@ -69,6 +69,7 @@ export type GeneralAction = 'import' | 'export' | 'subs' | 'resetInbounds';
|
||||
export interface InboundListProps {
|
||||
dbInbounds: DBInboundRecord[];
|
||||
clientCount: Record<number, ClientCountEntry>;
|
||||
clientCountsPending: boolean;
|
||||
onlineClients: string[];
|
||||
lastOnlineMap: Record<string, number>;
|
||||
inboundSpeed: Record<number, InboundSpeedEntry>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, type ReactElement } from 'react';
|
||||
import { useMemo, useState, type ReactElement } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { onlineStatusLabel } from './onlineStatusLabel';
|
||||
import { Popover, Switch, Tag, Tooltip, type TableColumnType } from 'antd';
|
||||
@@ -28,6 +28,49 @@ import {
|
||||
} from './helpers';
|
||||
import type { ClientCountEntry, DBInboundRecord, InboundSpeedEntry, RowAction } from './types';
|
||||
|
||||
function ClientEmailBadge({
|
||||
emails,
|
||||
title,
|
||||
color,
|
||||
suffix,
|
||||
}: {
|
||||
emails: string[];
|
||||
title: string;
|
||||
color?: string;
|
||||
suffix?: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const badge = (
|
||||
<Tag
|
||||
color={color}
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{emails.length}
|
||||
{suffix && ` ${suffix}`}
|
||||
</Tag>
|
||||
);
|
||||
if (!emails.length) return badge;
|
||||
return (
|
||||
<Popover
|
||||
title={title}
|
||||
onOpenChange={setOpen}
|
||||
destroyOnHidden
|
||||
content={
|
||||
open ? (
|
||||
<div className="client-email-list">
|
||||
{emails.map((email) => (
|
||||
<div key={email}>{email}</div>
|
||||
))}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{badge}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
interface UseInboundColumnsParams {
|
||||
hasAnyRemark: boolean;
|
||||
hasAnySubSortIndex: boolean;
|
||||
@@ -35,6 +78,7 @@ interface UseInboundColumnsParams {
|
||||
nodesById: Map<number, NodeRecord>;
|
||||
hostRemarksByInboundId: Map<number, string[]>;
|
||||
clientCount: Record<number, ClientCountEntry>;
|
||||
clientCountsPending: boolean;
|
||||
inboundSpeed: Record<number, InboundSpeedEntry>;
|
||||
subEnable: boolean;
|
||||
expireDiff: number;
|
||||
@@ -50,6 +94,7 @@ export function useInboundColumns({
|
||||
nodesById,
|
||||
hostRemarksByInboundId,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
inboundSpeed,
|
||||
subEnable,
|
||||
expireDiff,
|
||||
@@ -70,7 +115,9 @@ export function useInboundColumns({
|
||||
};
|
||||
|
||||
const clientTotal = (record: DBInboundRecord) =>
|
||||
(clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0;
|
||||
clientCountsPending
|
||||
? 0
|
||||
: ((clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0);
|
||||
|
||||
const speedTotal = (record: DBInboundRecord) => {
|
||||
const speed = inboundSpeed[record.id];
|
||||
@@ -290,8 +337,11 @@ export function useInboundColumns({
|
||||
width: 200,
|
||||
sorter: (a, b) => clientTotal(a) - clientTotal(b),
|
||||
render: (_, record) => {
|
||||
if (clientCountsPending) return t('loading');
|
||||
const cc = clientCount[record.id] || fallbackClientCount(record);
|
||||
if (!cc) return null;
|
||||
const onlineScope =
|
||||
cc.onlineAttribution === 'node' ? `(${t('pages.inbounds.node')})` : undefined;
|
||||
return (
|
||||
<>
|
||||
<Tag
|
||||
@@ -300,72 +350,12 @@ export function useInboundColumns({
|
||||
>
|
||||
<TeamOutlined aria-hidden /> {cc.clients}
|
||||
</Tag>
|
||||
{cc.active.length > 0 ? (
|
||||
<Popover
|
||||
title={t('subscription.active')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.active.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
color="green"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{cc.active.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
) : (
|
||||
<Tag
|
||||
color="green"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
0
|
||||
</Tag>
|
||||
)}
|
||||
<ClientEmailBadge emails={cc.active} color="green" title={t('subscription.active')} />
|
||||
{cc.deactive.length > 0 && (
|
||||
<Popover
|
||||
title={t('disabled')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.deactive.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{cc.deactive.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
<ClientEmailBadge emails={cc.deactive} title={t('disabled')} />
|
||||
)}
|
||||
{cc.depleted.length > 0 && (
|
||||
<Popover
|
||||
title={t('depleted')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.depleted.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
color="red"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{cc.depleted.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
<ClientEmailBadge emails={cc.depleted} color="red" title={t('depleted')} />
|
||||
)}
|
||||
{cc.onlineAttribution && cc.online.length === 0 && (
|
||||
<Tag className="client-count-tag" style={{ margin: 0, padding: '0 2px' }}>
|
||||
@@ -373,29 +363,12 @@ export function useInboundColumns({
|
||||
</Tag>
|
||||
)}
|
||||
{cc.online.length > 0 && (
|
||||
<Popover
|
||||
title={
|
||||
cc.onlineAttribution === 'node'
|
||||
? `${t('online')} (${t('pages.inbounds.node')})`
|
||||
: t('online')
|
||||
}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.online.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
color="blue"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, padding: '0 2px' }}
|
||||
>
|
||||
{cc.online.length}
|
||||
{cc.onlineAttribution === 'node' && ` (${t('pages.inbounds.node')})`}
|
||||
</Tag>
|
||||
</Popover>
|
||||
<ClientEmailBadge
|
||||
emails={cc.online}
|
||||
color="blue"
|
||||
title={`${t('online')}${onlineScope ? ` ${onlineScope}` : ''}`}
|
||||
suffix={onlineScope}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
@@ -488,6 +461,7 @@ export function useInboundColumns({
|
||||
nodesById,
|
||||
hostRemarksByInboundId,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
inboundSpeed,
|
||||
subEnable,
|
||||
expireDiff,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
@@ -58,6 +58,15 @@ interface ClientRollup {
|
||||
comments: Map<string, string>;
|
||||
}
|
||||
|
||||
interface CachedClientRollup {
|
||||
base: ClientRollup;
|
||||
refreshAt: number;
|
||||
online?: { emails?: Set<string>; result: ClientRollup };
|
||||
}
|
||||
|
||||
const EMPTY_ONLINE: string[] = [];
|
||||
const EMPTY_ROLLUPS: Record<number, ClientRollup> = {};
|
||||
|
||||
const TRACKED_PROTOCOLS: readonly string[] = [
|
||||
Protocols.VMESS,
|
||||
Protocols.VLESS,
|
||||
@@ -124,27 +133,37 @@ function toActiveInboundMap(
|
||||
data: Record<string, string[] | null>,
|
||||
): Map<string, Set<string> | null> {
|
||||
const map = new Map<string, Set<string> | null>();
|
||||
for (const [key, tags] of Object.entries(data)) {
|
||||
if (tags === null) map.set(key, null);
|
||||
else if (Array.isArray(tags)) map.set(key, new Set(tags));
|
||||
for (const [guid, tags] of Object.entries(data)) {
|
||||
if (tags === null) map.set(guid, null);
|
||||
else if (Array.isArray(tags)) map.set(guid, new Set(tags));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// Most pushes repeat the previous online sets; handing back a new Map anyway
|
||||
// re-ran the client rollup over every inbound on each traffic event.
|
||||
function sameGuidSets(
|
||||
a: ReadonlyMap<string, Set<string> | null>,
|
||||
b: ReadonlyMap<string, Set<string> | null>,
|
||||
): boolean {
|
||||
if (a.size !== b.size) return false;
|
||||
for (const [key, set] of b) {
|
||||
const prev = a.get(key);
|
||||
if (prev === set) continue;
|
||||
if (!prev || !set || prev.size !== set.size) return false;
|
||||
for (const value of set) if (!prev.has(value)) return false;
|
||||
function reuseGuidSets<T extends Set<string> | null>(
|
||||
previous: Map<string, T>,
|
||||
next: Map<string, T>,
|
||||
): Map<string, T> {
|
||||
let changed = previous.size !== next.size;
|
||||
for (const [guid, set] of next) {
|
||||
const prior = previous.get(guid);
|
||||
if (prior === set) continue;
|
||||
let same = !!prior && !!set && prior.size === set.size;
|
||||
if (same && prior && set) {
|
||||
for (const value of set) {
|
||||
if (!prior.has(value)) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (same && prior) {
|
||||
next.set(guid, prior);
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return changed ? next : previous;
|
||||
}
|
||||
|
||||
async function fetchLastOnlineMap(): Promise<Record<string, number>> {
|
||||
@@ -237,6 +256,7 @@ export function useInbounds() {
|
||||
// dbInbounds mirrors the slim query data wrapped as DBInbound instances. The
|
||||
// WS handlers rebuild only the rows they touch, so no refetch is needed.
|
||||
const [dbInbounds, setDbInbounds] = useState<DBInboundInstance[]>([]);
|
||||
const [inboundGeneration, setInboundGeneration] = useState(0);
|
||||
const dbInboundsRef = useRef<DBInboundInstance[]>([]);
|
||||
useEffect(() => {
|
||||
dbInboundsRef.current = dbInbounds;
|
||||
@@ -265,10 +285,7 @@ export function useInbounds() {
|
||||
const [lastOnlineMap, setLastOnlineMap] = useState<Record<string, number>>({});
|
||||
|
||||
const rollupClients = useCallback(
|
||||
(
|
||||
dbInbound: DBInboundInstance,
|
||||
inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] },
|
||||
): ClientRollup => {
|
||||
(dbInbound: DBInboundInstance, now: number): CachedClientRollup => {
|
||||
const clientStats = Array.isArray((dbInbound as { clientStats?: unknown }).clientStats)
|
||||
? (
|
||||
dbInbound as unknown as {
|
||||
@@ -282,37 +299,16 @@ export function useInbounds() {
|
||||
}
|
||||
).clientStats
|
||||
: [];
|
||||
const clients = inbound?.clients || [];
|
||||
const settings = coerceInboundJsonField(dbInbound.settings) as {
|
||||
clients?: { email?: string; enable?: boolean; comment?: string }[];
|
||||
};
|
||||
const clients = Array.isArray(settings.clients) ? settings.clients : [];
|
||||
const active: string[] = [];
|
||||
const deactive: string[] = [];
|
||||
const depleted: string[] = [];
|
||||
const expiring: string[] = [];
|
||||
const online: string[] = [];
|
||||
const comments = new Map<string, string>();
|
||||
const now = Date.now();
|
||||
|
||||
// Attribution key: the GUID of the node that physically hosts this
|
||||
// inbound. Local inbounds carry the panel's own GUID (filled server-side);
|
||||
// a node-managed inbound carries its origin node's GUID, or falls back to
|
||||
// the master-local synthetic id for an old-build node without one (#4983).
|
||||
const guid =
|
||||
dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
|
||||
const nodeOnline = onlineByGuid.get(guid);
|
||||
const activeForNode = activeByGuid.get(guid);
|
||||
let onlineAttribution: ClientRollup['onlineAttribution'] = onlinePending
|
||||
? 'pending'
|
||||
: 'unavailable';
|
||||
let inboundActive = false;
|
||||
if (!dbInbound.enable) {
|
||||
onlineAttribution = 'inbound';
|
||||
} else if (activeForNode === null) {
|
||||
onlineAttribution = nodeOnline === undefined ? 'unsupported' : 'node';
|
||||
inboundActive = true;
|
||||
} else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) {
|
||||
inboundActive = activeForNode.has(dbInbound.tag);
|
||||
// A partial report only vouches for the listed sidecar inbounds.
|
||||
if (inboundActive || !activeForNode.has('\0')) onlineAttribution = 'inbound';
|
||||
}
|
||||
let refreshAt = Infinity;
|
||||
|
||||
if (dbInbound.enable) {
|
||||
const statsByEmail = new Map<
|
||||
@@ -333,17 +329,20 @@ export function useInbounds() {
|
||||
depleted.push(client.email);
|
||||
continue;
|
||||
}
|
||||
if (stats && stats.expiryTime > now) refreshAt = Math.min(refreshAt, stats.expiryTime);
|
||||
if (!client.enable) {
|
||||
deactive.push(client.email);
|
||||
continue;
|
||||
}
|
||||
active.push(client.email);
|
||||
if (inboundActive && nodeOnline?.has(client.email)) online.push(client.email);
|
||||
if (stats) {
|
||||
const expiringSoon =
|
||||
(stats.expiryTime > 0 && stats.expiryTime - now < expireDiff) ||
|
||||
(stats.total > 0 && stats.total - (stats.up + stats.down) < trafficDiff);
|
||||
if (expiringSoon) expiring.push(client.email);
|
||||
if (stats.expiryTime > now && !expiringSoon && expireDiff > 0) {
|
||||
refreshAt = Math.min(refreshAt, Math.floor(stats.expiryTime - expireDiff) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -353,39 +352,148 @@ export function useInbounds() {
|
||||
}
|
||||
|
||||
return {
|
||||
clients: clients.length,
|
||||
active,
|
||||
deactive,
|
||||
depleted,
|
||||
expiring,
|
||||
online,
|
||||
onlineAttribution,
|
||||
comments,
|
||||
base: {
|
||||
clients: clients.length,
|
||||
active,
|
||||
deactive,
|
||||
depleted,
|
||||
expiring,
|
||||
online: EMPTY_ONLINE,
|
||||
onlineAttribution: 'inbound',
|
||||
comments,
|
||||
},
|
||||
refreshAt,
|
||||
};
|
||||
},
|
||||
[onlineByGuid, activeByGuid, onlinePending, expireDiff, trafficDiff],
|
||||
[expireDiff, trafficDiff],
|
||||
);
|
||||
|
||||
// Every write to a DBInbound row also replaces the dbInbounds array, so this
|
||||
// recomputes on both a refetch and a WS-merged stats update.
|
||||
const clientCount = useMemo(() => {
|
||||
const rollupCache = useMemo(
|
||||
() => ({ rows: new WeakMap<DBInboundInstance, CachedClientRollup>(), compute: rollupClients }),
|
||||
[rollupClients],
|
||||
);
|
||||
|
||||
// The WebSocket subscription keeps the callback installed at mount.
|
||||
const rollupCacheRef = useRef(rollupCache);
|
||||
useLayoutEffect(() => {
|
||||
rollupCacheRef.current = rollupCache;
|
||||
}, [rollupCache]);
|
||||
|
||||
const rollupForInbound = useCallback(
|
||||
(dbInbound: DBInboundInstance, now = Date.now()) => {
|
||||
if (!TRACKED_PROTOCOLS.includes(dbInbound.protocol)) return undefined;
|
||||
let rollup = rollupCache.rows.get(dbInbound);
|
||||
if (rollup === undefined || now >= rollup.refreshAt) {
|
||||
rollup = rollupCache.compute(dbInbound, now);
|
||||
rollupCache.rows.set(dbInbound, rollup);
|
||||
}
|
||||
|
||||
// Scope the report to the node that physically hosts this inbound.
|
||||
const guid =
|
||||
dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
|
||||
const nodeOnline = onlineByGuid.get(guid);
|
||||
const activeForNode = activeByGuid.get(guid);
|
||||
let attribution: ClientRollup['onlineAttribution'] = onlinePending
|
||||
? 'pending'
|
||||
: 'unavailable';
|
||||
let inboundActive = false;
|
||||
if (!dbInbound.enable) {
|
||||
attribution = 'inbound';
|
||||
} else if (activeForNode === null) {
|
||||
attribution = nodeOnline === undefined ? 'unsupported' : 'node';
|
||||
inboundActive = true;
|
||||
} else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) {
|
||||
inboundActive = activeForNode.has(dbInbound.tag);
|
||||
// A partial report only vouches for the listed sidecar inbounds.
|
||||
if (inboundActive || !activeForNode.has('\0')) attribution = 'inbound';
|
||||
}
|
||||
|
||||
const emails = inboundActive && nodeOnline?.size ? nodeOnline : undefined;
|
||||
const cached = rollup.online;
|
||||
if (cached && cached.emails === emails && cached.result.onlineAttribution === attribution) {
|
||||
return cached.result;
|
||||
}
|
||||
|
||||
const matched = emails
|
||||
? rollup.base.active.filter((email) => emails.has(email))
|
||||
: EMPTY_ONLINE;
|
||||
const result =
|
||||
matched.length || attribution !== rollup.base.onlineAttribution
|
||||
? { ...rollup.base, online: matched, onlineAttribution: attribution }
|
||||
: rollup.base;
|
||||
rollup.online = { emails, result };
|
||||
return result;
|
||||
},
|
||||
[rollupCache, activeByGuid, onlineByGuid, onlinePending],
|
||||
);
|
||||
|
||||
const largeList = useMemo(
|
||||
() =>
|
||||
dbInbounds.reduce((size, row) => {
|
||||
const settings = row.settings;
|
||||
const objectClients =
|
||||
settings && typeof settings === 'object' && !Array.isArray(settings)
|
||||
? settings.clients
|
||||
: undefined;
|
||||
return (
|
||||
size +
|
||||
(typeof settings === 'string' ? settings.length : 0) +
|
||||
(Array.isArray(objectClients) ? objectClients.length * 64 : 0) +
|
||||
(Array.isArray(row.clientStats) ? row.clientStats.length * 100 : 0)
|
||||
);
|
||||
}, 0) >
|
||||
256 * 1024,
|
||||
[dbInbounds],
|
||||
);
|
||||
const [scheduled, setScheduled] = useState<{
|
||||
generation: number;
|
||||
counts: Record<number, ClientRollup>;
|
||||
}>();
|
||||
useEffect(() => {
|
||||
if (!largeList) return;
|
||||
const counts: Record<number, ClientRollup> = {};
|
||||
for (const dbInbound of dbInbounds) {
|
||||
const protocol = dbInbound.protocol;
|
||||
if (!TRACKED_PROTOCOLS.includes(protocol)) continue;
|
||||
const settings = coerceInboundJsonField(dbInbound.settings) as {
|
||||
clients?: Array<{ email?: string; enable?: boolean; comment?: string }>;
|
||||
};
|
||||
counts[dbInbound.id] = rollupClients(dbInbound, { clients: settings.clients });
|
||||
const now = Date.now();
|
||||
let index = 0;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
function computeSlice() {
|
||||
const end = performance.now() + 8;
|
||||
do {
|
||||
const row = dbInbounds[index++];
|
||||
const rollup = rollupForInbound(row, now);
|
||||
if (rollup) counts[row.id] = rollup;
|
||||
} while (index < dbInbounds.length && performance.now() < end);
|
||||
if (index < dbInbounds.length) {
|
||||
timer = setTimeout(computeSlice, 0);
|
||||
} else {
|
||||
setScheduled({ generation: inboundGeneration, counts });
|
||||
}
|
||||
}
|
||||
timer = setTimeout(computeSlice, 0);
|
||||
return () => clearTimeout(timer);
|
||||
}, [largeList, dbInbounds, inboundGeneration, rollupForInbound]);
|
||||
|
||||
const syncCounts = useMemo(() => {
|
||||
if (largeList) return EMPTY_ROLLUPS;
|
||||
const counts: Record<number, ClientRollup> = {};
|
||||
for (const row of dbInbounds) {
|
||||
const rollup = rollupForInbound(row);
|
||||
if (rollup) counts[row.id] = rollup;
|
||||
}
|
||||
return counts;
|
||||
}, [dbInbounds, rollupClients]);
|
||||
}, [largeList, dbInbounds, rollupForInbound]);
|
||||
// Online and counter updates can reuse the last rollup while the next slice
|
||||
// runs, but a refetch or hydration may have changed the client membership.
|
||||
const rollupsReady = !largeList || scheduled?.generation === inboundGeneration;
|
||||
const clientCount = largeList
|
||||
? ((rollupsReady ? scheduled?.counts : undefined) ?? EMPTY_ROLLUPS)
|
||||
: syncCounts;
|
||||
|
||||
// Adopting fetched data during render (rather than in an effect) keeps the
|
||||
// list from painting one frame of the previous data after a refetch.
|
||||
const [syncedSlim, setSyncedSlim] = useState<unknown>();
|
||||
if (slimQuery.data && slimQuery.data !== syncedSlim) {
|
||||
setSyncedSlim(slimQuery.data);
|
||||
setInboundGeneration((generation) => generation + 1);
|
||||
setDbInbounds(
|
||||
(slimQuery.data as { protocol: string; id: number }[]).map(
|
||||
(row) => new DBInbound(row) as DBInboundInstance,
|
||||
@@ -450,6 +558,7 @@ export function useInbounds() {
|
||||
const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`);
|
||||
if (!validated.obj) return null;
|
||||
const dbInbound = new DBInbound(validated.obj) as DBInboundInstance;
|
||||
setInboundGeneration((generation) => generation + 1);
|
||||
setDbInbounds((prev) => {
|
||||
const next = prev.map((row) =>
|
||||
(row as unknown as { id: number }).id === id ? dbInbound : row,
|
||||
@@ -475,11 +584,11 @@ export function useInbounds() {
|
||||
}
|
||||
if (p.onlineByGuid && typeof p.onlineByGuid === 'object') {
|
||||
const next = toGuidOnlineMap(p.onlineByGuid);
|
||||
setOnlineByGuid((prev) => (sameGuidSets(prev, next) ? prev : next));
|
||||
setOnlineByGuid((prev) => reuseGuidSets(prev, next));
|
||||
}
|
||||
if (p.activeInbounds && typeof p.activeInbounds === 'object') {
|
||||
const next = toActiveInboundMap(p.activeInbounds);
|
||||
setActiveByGuid((prev) => (sameGuidSets(prev, next) ? prev : next));
|
||||
setActiveByGuid((prev) => reuseGuidSets(prev, next));
|
||||
}
|
||||
if (p.lastOnlineMap && typeof p.lastOnlineMap === 'object') {
|
||||
setLastOnlineMap((prev) => ({ ...prev, ...p.lastOnlineMap! }));
|
||||
@@ -611,6 +720,11 @@ export function useInbounds() {
|
||||
if (typeof upd.enable === 'boolean') row.enable = upd.enable;
|
||||
}
|
||||
if (statsTouched && nextStats) row.clientStats = nextStats;
|
||||
if (!statsTouched && ib.enable === row.enable) {
|
||||
const cache = rollupCacheRef.current.rows;
|
||||
const cached = cache.get(ib);
|
||||
if (cached) cache.set(row, cached);
|
||||
}
|
||||
return row;
|
||||
});
|
||||
|
||||
@@ -635,6 +749,7 @@ export function useInbounds() {
|
||||
fetchError,
|
||||
dbInbounds,
|
||||
clientCount,
|
||||
clientCountsPending: !rollupsReady,
|
||||
onlineClients,
|
||||
lastOnlineMap,
|
||||
inboundSpeed,
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { useLayoutEffect, type ReactNode } from 'react';
|
||||
import { act, fireEvent, renderHook, screen, waitFor, within } from '@testing-library/react';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { getSharedWebSocketClient } from '@/api/websocket';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import InboundsPage from '@/pages/inbounds/InboundsPage';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import { useInbounds } from '@/pages/inbounds/useInbounds';
|
||||
|
||||
import { makeTestQueryClient } from './test-utils';
|
||||
import { makeTestQueryClient, renderWithProviders } from './test-utils';
|
||||
|
||||
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
|
||||
vi.mock('@/pages/inbounds/form/InboundFormModal', () => ({ default: () => null }));
|
||||
|
||||
function seedInbounds() {
|
||||
const rows = [1, 2].map((id) => ({
|
||||
id,
|
||||
protocol: 'vless',
|
||||
tag: `in-${id}`,
|
||||
originNodeGuid: `node-${id}`,
|
||||
enable: true,
|
||||
up: 10,
|
||||
down: 20,
|
||||
@@ -72,6 +80,7 @@ describe('inbound websocket merges keep unchanged state', () => {
|
||||
it('still rebuilds exactly the rows whose numbers moved', async () => {
|
||||
const { result } = await renderInbounds();
|
||||
const before = result.current.dbInbounds;
|
||||
const countsBefore = result.current.clientCount;
|
||||
|
||||
act(() =>
|
||||
result.current.applyClientStatsEvent({
|
||||
@@ -86,8 +95,10 @@ describe('inbound websocket merges keep unchanged state', () => {
|
||||
const [first, second] = result.current.dbInbounds;
|
||||
expect(first).not.toBe(before[0]);
|
||||
expect(first.up).toBe(99);
|
||||
expect(result.current.clientCount[1]).toBe(countsBefore[1]);
|
||||
expect(second).not.toBe(before[1]);
|
||||
expect(second.clientStats?.[0]?.up).toBe(5);
|
||||
expect(result.current.clientCount[2]).not.toBe(countsBefore[2]);
|
||||
});
|
||||
|
||||
it('keeps the client rollup when a traffic push repeats the same online sets', async () => {
|
||||
@@ -107,6 +118,230 @@ describe('inbound websocket merges keep unchanged state', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('reuses unaffected rollups and client metadata on large online updates', async () => {
|
||||
const { queryClient, rows, wrapper } = seedInbounds();
|
||||
const clients = Array.from({ length: 4000 }, (_, i) => ({
|
||||
email: `client-${i}@x`,
|
||||
enable: true,
|
||||
comment: 'shared subscription',
|
||||
}));
|
||||
const settings = JSON.stringify({ clients });
|
||||
queryClient.setQueryData(
|
||||
keys.inbounds.slim(),
|
||||
Array.from({ length: 30 }, (_, i) => ({
|
||||
...rows[i % 2],
|
||||
id: i + 1,
|
||||
tag: `large-${i + 1}`,
|
||||
settings,
|
||||
})),
|
||||
);
|
||||
const { result } = renderHook(() => useInbounds(), { wrapper });
|
||||
await waitFor(() => expect(result.current.clientCount[30]?.clients).toBe(4000));
|
||||
const before = result.current.clientCount;
|
||||
act(() =>
|
||||
result.current.applyTrafficEvent({
|
||||
onlineByGuid: { 'node-1': [clients[0].email], 'node-2': [clients[1].email] },
|
||||
activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[0].email]));
|
||||
const initial = result.current.clientCount;
|
||||
expect(initial[1].active).toBe(before[1].active);
|
||||
expect(initial[1].online).toEqual([clients[0].email]);
|
||||
|
||||
act(() =>
|
||||
result.current.applyTrafficEvent({
|
||||
onlineByGuid: { 'node-1': [clients[2].email], 'node-2': [clients[1].email] },
|
||||
activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[2].email]));
|
||||
expect(result.current.clientCount[1].active).toBe(initial[1].active);
|
||||
for (let id = 2; id <= 30; id++) {
|
||||
expect(result.current.clientCount[id]).toBe(initial[id]);
|
||||
}
|
||||
});
|
||||
|
||||
it('loads inbounds whose clientStats is null in the slim response', () => {
|
||||
const { rows, queryClient, wrapper } = seedInbounds();
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [
|
||||
{ ...rows[0], protocol: 'mixed', settings: '{}', clientStats: null },
|
||||
{ ...rows[1], settings: '{"clients":[]}', clientStats: null },
|
||||
]);
|
||||
const { result } = renderHook(() => useInbounds(), { wrapper });
|
||||
expect(result.current.fetched).toBe(true);
|
||||
expect(result.current.dbInbounds.map((row) => row.id)).toEqual([1, 2]);
|
||||
expect(result.current.clientCount[1]).toBeUndefined();
|
||||
expect(result.current.clientCount[2].clients).toBe(0);
|
||||
});
|
||||
|
||||
it('withholds large inbound rollups until they match the refetched structure', async () => {
|
||||
const { queryClient, rows, wrapper } = seedInbounds();
|
||||
const withClients = (count: number, remark: string) => ({
|
||||
...rows[0],
|
||||
remark,
|
||||
settings: JSON.stringify({
|
||||
clients: Array.from({ length: count }, (_, i) => ({
|
||||
email: `member-${i}@example.test`,
|
||||
enable: true,
|
||||
})),
|
||||
}),
|
||||
});
|
||||
const seed = withClients(7000, 'initial');
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [seed]);
|
||||
const displayed: { remark: string; fetched: boolean; pending: boolean; count?: number }[] = [];
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const data = useInbounds();
|
||||
useLayoutEffect(() => {
|
||||
const row = data.dbInbounds[0];
|
||||
if (row)
|
||||
displayed.push({
|
||||
remark: row.remark,
|
||||
fetched: data.fetched,
|
||||
pending: data.clientCountsPending,
|
||||
count: data.clientCount[row.id]?.clients,
|
||||
});
|
||||
});
|
||||
return data;
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(7000));
|
||||
for (const [count, remark] of [
|
||||
[8000, 'large refetch'],
|
||||
[1, 'small refetch'],
|
||||
[9000, 'large again'],
|
||||
] as const) {
|
||||
act(() => queryClient.setQueryData(keys.inbounds.slim(), [withClients(count, remark)]));
|
||||
await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(count));
|
||||
expect(displayed.filter((view) => view.remark === remark)).toEqual(
|
||||
expect.arrayContaining([{ remark, fetched: true, pending: false, count }]),
|
||||
);
|
||||
for (const view of displayed.filter((view) => view.remark === remark)) {
|
||||
expect(view.fetched).toBe(true);
|
||||
expect(view.count).toBe(view.pending ? undefined : count);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the search, node filter and selection through large-list refetch and detail hydration', async () => {
|
||||
const { queryClient, rows } = seedInbounds();
|
||||
const clients = (count: number) =>
|
||||
JSON.stringify({
|
||||
clients: Array.from({ length: count }, (_, i) => ({
|
||||
email: `member-${i}@example.test`,
|
||||
enable: true,
|
||||
})),
|
||||
});
|
||||
const local = { ...rows[0], remark: 'Kept local', settings: clients(7000) };
|
||||
const remote = { ...rows[1], remark: 'Kept remote', nodeId: 7 };
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [local, remote]);
|
||||
queryClient.setQueryDefaults(keys.nodes.list(), { staleTime: Infinity });
|
||||
queryClient.setQueryData(keys.nodes.list(), [
|
||||
{ id: 7, name: 'Remote', enable: true, status: 'online' },
|
||||
]);
|
||||
queryClient.setQueryData(keys.hosts.list(), []);
|
||||
const get = vi.mocked(HttpUtil.get);
|
||||
const fallback = get.getMockImplementation();
|
||||
get.mockImplementation(async (url, ...args) =>
|
||||
url === '/panel/api/inbounds/get/1'
|
||||
? new Msg(true, '', { ...local, remark: 'Kept hydrated', settings: clients(9000) })
|
||||
: ((await fallback?.(url, ...args)) ?? new Msg(true, '', [])),
|
||||
);
|
||||
|
||||
const view = renderWithProviders(
|
||||
<MemoryRouter>
|
||||
<InboundsPage />
|
||||
</MemoryRouter>,
|
||||
{ queryClient },
|
||||
);
|
||||
try {
|
||||
await screen.findAllByText('7000');
|
||||
const search = screen.getByRole('textbox', { name: 'Search' });
|
||||
fireEvent.change(search, { target: { value: 'Kept' } });
|
||||
fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Nodes' }));
|
||||
fireEvent.click(await screen.findByText('Local (this panel)'));
|
||||
const row = () => screen.getByRole('row', { name: /Kept (local|refetched|hydrated)/ });
|
||||
fireEvent.click(within(row()).getByRole('checkbox'));
|
||||
const expectContext = () => {
|
||||
expect(screen.getByRole('textbox', { name: 'Search' })).toBe(search);
|
||||
expect((search as HTMLInputElement).value).toBe('Kept');
|
||||
expect(screen.queryByText('Kept remote')).toBeNull();
|
||||
expect((within(row()).getByRole('checkbox') as HTMLInputElement).checked).toBe(true);
|
||||
};
|
||||
expectContext();
|
||||
|
||||
act(() =>
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [
|
||||
{ ...local, remark: 'Kept refetched', settings: clients(8000) },
|
||||
remote,
|
||||
]),
|
||||
);
|
||||
await screen.findAllByText('8000');
|
||||
expectContext();
|
||||
|
||||
fireEvent.click(within(row()).getByRole('button', { name: 'Edit' }));
|
||||
await screen.findAllByText('9000');
|
||||
expectContext();
|
||||
} finally {
|
||||
view.unmount();
|
||||
getSharedWebSocketClient().disconnect();
|
||||
if (fallback) get.mockImplementation(fallback);
|
||||
}
|
||||
});
|
||||
|
||||
it('reuses the current rollup cache for subscribed websocket updates after defaults change', async () => {
|
||||
const { queryClient, wrapper } = seedInbounds();
|
||||
const sockets: EventTarget[] = [];
|
||||
class FixtureSocket extends EventTarget {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
readyState = FixtureSocket.CONNECTING;
|
||||
constructor() {
|
||||
super();
|
||||
sockets.push(this);
|
||||
}
|
||||
close() {}
|
||||
}
|
||||
const socketClient = getSharedWebSocketClient();
|
||||
socketClient.disconnect();
|
||||
vi.stubGlobal('WebSocket', FixtureSocket);
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const data = useInbounds();
|
||||
useWebSocket({ client_stats: data.applyClientStatsEvent });
|
||||
return data;
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
try {
|
||||
await waitFor(() => expect(result.current.clientCount[1]?.clients).toBe(1));
|
||||
act(() => queryClient.setQueryData(keys.settings.defaults(), { expireDiff: 3 }));
|
||||
await waitFor(() => expect(result.current.expireDiff).toBe(3 * 86400000));
|
||||
const afterDefaults = result.current.clientCount[1];
|
||||
const [socket] = sockets;
|
||||
if (!socket) throw new Error('WebSocket was not connected');
|
||||
act(() =>
|
||||
socket.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({
|
||||
type: 'client_stats',
|
||||
payload: { inbounds: [{ id: 1, up: 99 }] },
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(result.current.dbInbounds[0].up).toBe(99);
|
||||
expect(result.current.clientCount[1]).toBe(afterDefaults);
|
||||
} finally {
|
||||
unmount();
|
||||
socketClient.disconnect();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not attribute shared online clients without matching inbound activity', async () => {
|
||||
const { rows, queryClient, wrapper } = seedInbounds();
|
||||
queryClient.setQueryData(
|
||||
|
||||
Reference in New Issue
Block a user