mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-06 01:44:45 +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:
@@ -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