From 678816c3ff4b82e40cce7f0be04a6793b84f8bab Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Tue, 1 Dec 2026 10:02:26 +0330 Subject: [PATCH 01/33] fix(hosts): reset form sessions and support address tag editing --- .../src/pages/hosts/HostAddressSelect.css | 42 ++++ .../src/pages/hosts/HostAddressSelect.tsx | 183 ++++++++++++++++++ frontend/src/pages/hosts/HostFormModal.tsx | 48 ++--- frontend/src/test/host-address-tags.test.tsx | 123 ++++++++++++ frontend/src/test/host-form-session.test.tsx | 143 ++++++++++++++ internal/web/translation/ar-EG.json | 6 + internal/web/translation/en-US.json | 6 + internal/web/translation/es-ES.json | 6 + internal/web/translation/fa-IR.json | 6 + internal/web/translation/id-ID.json | 6 + internal/web/translation/ja-JP.json | 6 + internal/web/translation/pt-BR.json | 6 + internal/web/translation/ru-RU.json | 6 + internal/web/translation/sk-SK.json | 6 + internal/web/translation/tr-TR.json | 6 + internal/web/translation/uk-UA.json | 6 + internal/web/translation/vi-VN.json | 6 + internal/web/translation/zh-CN.json | 6 + internal/web/translation/zh-TW.json | 6 + 19 files changed, 601 insertions(+), 22 deletions(-) create mode 100644 frontend/src/pages/hosts/HostAddressSelect.css create mode 100644 frontend/src/pages/hosts/HostAddressSelect.tsx create mode 100644 frontend/src/test/host-address-tags.test.tsx create mode 100644 frontend/src/test/host-form-session.test.tsx diff --git a/frontend/src/pages/hosts/HostAddressSelect.css b/frontend/src/pages/hosts/HostAddressSelect.css new file mode 100644 index 000000000..e6f29a6d3 --- /dev/null +++ b/frontend/src/pages/hosts/HostAddressSelect.css @@ -0,0 +1,42 @@ +.host-address-tag-actions { + display: inline-flex; + align-items: center; + gap: 4px; + max-width: 100%; +} + +.host-address-tag-button, +.host-address-tag-editor { + padding: 0 2px; + border: 0; + border-radius: 2px; + background: transparent; + color: inherit; + font: inherit; +} + +.host-address-tag-button { + cursor: pointer; +} + +.host-address-tag-button:first-child { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.host-address-tag-button:last-child { + flex-shrink: 0; +} + +.host-address-tag-button:focus-visible, +.host-address-tag-editor:focus { + outline: 2px solid var(--ant-color-primary); + outline-offset: -1px; +} + +.host-address-tag-editor { + width: 24ch; + max-width: 100%; +} diff --git a/frontend/src/pages/hosts/HostAddressSelect.tsx b/frontend/src/pages/hosts/HostAddressSelect.tsx new file mode 100644 index 000000000..15dc6cd97 --- /dev/null +++ b/frontend/src/pages/hosts/HostAddressSelect.tsx @@ -0,0 +1,183 @@ +import { useCallback, useLayoutEffect, useRef, useState } from 'react'; +import type { ClipboardEvent, ComponentPropsWithRef, KeyboardEvent, MouseEvent } from 'react'; +import { CopyOutlined } from '@ant-design/icons'; +import { Select, message } from 'antd'; +import { useTranslation } from 'react-i18next'; + +import { selectTagRender } from '@/components/form'; +import { ClipboardManager } from '@/utils'; +import './HostAddressSelect.css'; + +type Props = Pick< + ComponentPropsWithRef>, + 'aria-describedby' | 'aria-invalid' | 'id' | 'onBlur' | 'options' | 'ref' | 'value' +> & { + onChange?: (value: string[]) => void; + validateEdit: () => void; +}; + +const separators = /[\s,;]+/u; + +function keepFromSelect(event: MouseEvent) { + event.preventDefault(); + event.stopPropagation(); +} + +function keepActivationFromSelect(event: KeyboardEvent) { + if (event.key === 'Enter' || event.key === ' ') event.stopPropagation(); +} + +export default function HostAddressSelect({ value, onChange, validateEdit, ...props }: Props) { + const { t } = useTranslation(); + const addresses = value ?? []; + const [messageApi, messageContext] = message.useMessage(); + const [editing, setEditing] = useState<{ address: string; draft: string } | null>(null); + const [search, setSearch] = useState(''); + const [open, setOpen] = useState(false); + const editButtons = useRef(new Map()); + const focusAfterEdit = useRef(null); + + const focusEditor = useCallback((input: HTMLInputElement | null) => { + input?.focus(); + input?.select(); + }, []); + + useLayoutEffect(() => { + if (editing !== null || focusAfterEdit.current === null) return; + editButtons.current.get(focusAfterEdit.current)?.focus(); + focusAfterEdit.current = null; + }, [editing]); + + function startEdit(address: string) { + setOpen(false); + setSearch(''); + setEditing({ address, draft: address }); + } + + function finishEdit(address: string) { + focusAfterEdit.current = address; + setEditing(null); + } + + function editKeyDown(event: KeyboardEvent) { + if (event.key !== 'Tab') event.stopPropagation(); + if (!editing || event.nativeEvent.isComposing) return; + if (event.key === 'Escape') { + event.preventDefault(); + finishEdit(editing.address); + } + if (event.key !== 'Enter') return; + event.preventDefault(); + const next = editing.draft.trim(); + if (!next || separators.test(next)) { + messageApi.warning(t('pages.hosts.addressActions.single')); + return; + } + if (next !== editing.address) { + if (addresses.includes(next)) { + messageApi.warning(t('pages.hosts.addressActions.duplicate')); + return; + } + const index = addresses.indexOf(editing.address); + onChange?.(addresses.map((address, i) => (i === index ? next : address))); + validateEdit(); + } + finishEdit(next); + } + + function pasteAddresses(event: ClipboardEvent) { + const input = event.target; + if (!(input instanceof HTMLInputElement) || input.getAttribute('role') !== 'combobox') return; + const pasted = event.clipboardData.getData('text/plain'); + if (!pasted.trim()) return; + event.preventDefault(); + event.stopPropagation(); + const start = input.selectionStart ?? input.value.length; + const end = input.selectionEnd ?? start; + const text = input.value.slice(0, start) + pasted + input.value.slice(end); + const existing = new Set(addresses); + const additions = [...new Set(text.split(separators))].filter( + (address) => address && !existing.has(address), + ); + if (additions.length > 0) onChange?.([...addresses, ...additions]); + setSearch(''); + setOpen(false); + } + + async function copyAddress(address: string) { + if (await ClipboardManager.copyText(address)) messageApi.success(t('copied')); + else messageApi.error(t('somethingWentWrong')); + } + + return ( +
+ {messageContext} + + {...props} + mode="tags" + value={addresses} + onChange={onChange} + showSearch={{ searchValue: search, onSearch: setSearch }} + open={editing ? false : open} + onOpenChange={setOpen} + tokenSeparators={[',', ';', ' ', '\t', '\r', '\n']} + placeholder="cdn.example.com, cdn2.example.com:443" + tagRender={(tag) => { + if (tag.isMaxTag || tag.disabled) return selectTagRender(tag); + const address = String(tag.value); + const editLabel = t('pages.hosts.addressActions.edit', { address }); + return selectTagRender({ + ...tag, + label: + editing?.address === address ? ( + setEditing({ address, draft: event.target.value })} + onKeyDown={editKeyDown} + onMouseDown={(event) => event.stopPropagation()} + onBlur={() => setEditing(null)} + /> + ) : ( + + + + + ), + }); + }} + /> +
+ ); +} diff --git a/frontend/src/pages/hosts/HostFormModal.tsx b/frontend/src/pages/hosts/HostFormModal.tsx index d2237dbb1..4e863910f 100644 --- a/frontend/src/pages/hosts/HostFormModal.tsx +++ b/frontend/src/pages/hosts/HostFormModal.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useLayoutEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Alert, @@ -35,6 +35,7 @@ import { useNodesQuery } from '@/api/queries/useNodesQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery'; import { catTabLabel } from '@/pages/settings/catTabLabel'; import { withHostPort } from '@/lib/hosts/host-port'; +import HostAddressSelect from './HostAddressSelect'; import { HostFinalMaskForm, HostMuxForm, HostSockoptForm } from './json-forms'; type FormShape = Omit & { @@ -100,7 +101,16 @@ function defaultsFor(host: HostRecord | null): FormShape { }; } -export default function HostFormModal({ +export default function HostFormModal(props: HostFormModalProps) { + const key = props.open ? (props.mode === 'add' ? 'add' : `edit:${props.host?.groupId}`) : null; + const [session, setSession] = useState({ key, generation: 0 }); + if (key !== session.key) { + setSession({ key, generation: session.generation + (key === null ? 0 : 1) }); + } + return ; +} + +function HostFormSession({ open, mode, host, @@ -111,9 +121,17 @@ export default function HostFormModal({ }: HostFormModalProps) { const { t } = useTranslation(); const { isMobile } = useMediaQuery(); - const methods = useForm({ defaultValues: defaultsFor(host) }); + const methods = useForm({ defaultValues: defaultsFor(mode === 'edit' ? host : null) }); const [messageApi, messageContextHolder] = message.useMessage(); const [loading, setLoading] = useState(false); + const active = useRef(false); + + useLayoutEffect(() => { + active.current = open; + return () => { + active.current = false; + }; + }, [open]); const security = (useWatch({ control: methods.control, name: 'security' }) ?? 'same') as string; const fingerprint = (useWatch({ control: methods.control, name: 'fingerprint' }) ?? '') as string; @@ -130,18 +148,6 @@ export default function HostFormModal({ const watchedHosts = useWatch({ control: methods.control, name: 'hosts' }); const hasCidr = Boolean(watchedHosts?.some((h) => typeof h === 'string' && h.includes('/'))); - // React resets this during render rather than in an effect so the modal's - // first open frame already shows cleared fields. - const openHost = open ? host : null; - const [syncedHost, setSyncedHost] = useState(openHost); - if (openHost !== syncedHost) { - setSyncedHost(openHost); - if (open) { - methods.reset(defaultsFor(host)); - setLoading(false); - } - } - const { nodes } = useNodesQuery(); const inboundSelectOptions = useMemo( @@ -219,6 +225,7 @@ export default function HostFormModal({ setLoading(true); try { const res = await save(payload); + if (!active.current) return; if (res?.success) { messageApi.success( t(mode === 'add' ? 'pages.hosts.toasts.add' : 'pages.hosts.toasts.update'), @@ -230,7 +237,7 @@ export default function HostFormModal({ } catch (err) { console.error(err); } finally { - setLoading(false); + if (active.current) setLoading(false); } }; @@ -238,7 +245,7 @@ export default function HostFormModal({ void methods.handleSubmit(onFinish)(event)} onCancel={() => onOpenChange(false)} confirmLoading={loading} okText={t('save')} @@ -302,12 +309,9 @@ export default function HostFormModal({ tooltip={t('pages.hosts.hints.address')} rules={{ validate: rhfZodValidate(BulkAddHostSchema.shape.hosts) }} > - onChange(next as OverviewRange)} - /> + + {label} + + aria-label={label} + className="ov-range-select" + size="small" + value={value} + options={OPTIONS} + virtual={false} + onChange={(next) => onChange(next)} + /> + ); } diff --git a/frontend/src/pages/index/ThroughputCard.tsx b/frontend/src/pages/index/ThroughputCard.tsx index 29d9ee24c..76799461f 100644 --- a/frontend/src/pages/index/ThroughputCard.tsx +++ b/frontend/src/pages/index/ThroughputCard.tsx @@ -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({ -
- -
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({ {available ? footRight : '—'}
-
- -
(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, 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(() => ({ + ...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(); @@ -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(); - 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, diff --git a/frontend/src/test/container-history.test.tsx b/frontend/src/test/container-history.test.tsx index 45cdc0e72..bf7903fc3 100644 --- a/frontend/src/test/container-history.test.tsx +++ b/frontend/src/test/container-history.test.tsx @@ -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 () => { diff --git a/frontend/src/test/network-traffic-status.test.tsx b/frontend/src/test/network-traffic-status.test.tsx index 4136741ad..466b3c107 100644 --- a/frontend/src/test/network-traffic-status.test.tsx +++ b/frontend/src/test/network-traffic-status.test.tsx @@ -39,8 +39,6 @@ describe('network traffic status', () => { down={[200]} labels={['12:00']} isMobile={false} - range={2} - onRangeChange={() => undefined} />, ); expect( diff --git a/frontend/src/test/overview-global-range.test.tsx b/frontend/src/test/overview-global-range.test.tsx new file mode 100644 index 000000000..35e3722f9 --- /dev/null +++ b/frontend/src/test/overview-global-range.test.tsx @@ -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(); + 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(); + 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(); + 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(); + await waitFor(() => + expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]), + ); + first.unmount(); + get.mockClear(); + renderWithProviders(); + 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(); + 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(); + 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(); + 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', + ]); +}); diff --git a/frontend/src/test/overview-ranged-history.test.tsx b/frontend/src/test/overview-ranged-history.test.tsx index d3573bebd..a24b335b5 100644 --- a/frontend/src/test/overview-ranged-history.test.tsx +++ b/frontend/src/test/overview-ranged-history.test.tsx @@ -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(); + } + }, +); diff --git a/frontend/src/test/overview-stop-confirm.test.tsx b/frontend/src/test/overview-stop-confirm.test.tsx index 105a8f6c3..3f19fea48 100644 --- a/frontend/src/test/overview-stop-confirm.test.tsx +++ b/frontend/src/test/overview-stop-confirm.test.tsx @@ -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} diff --git a/frontend/src/test/overview-update-tag-keyboard.test.tsx b/frontend/src/test/overview-update-tag-keyboard.test.tsx index 93ee645e9..cf33af949 100644 --- a/frontend/src/test/overview-update-tag-keyboard.test.tsx +++ b/frontend/src/test/overview-update-tag-keyboard.test.tsx @@ -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} From 6f59a79bc28967135b9b000094661c6b6b87368c Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 01:42:49 +0330 Subject: [PATCH 07/33] perf(inbounds): cache slim settings by structural revision (#7287) Avoid repeatedly loading and decoding full inbound settings on the slim UI list path. Read scoped inbound metadata without Settings, reuse immutable projections keyed by database handle, inbound ID and structural revision, and fetch cold or changed rows in bounded batches. Preserve row-version consistency on misses, exclude deleted rows, and bound the LRU to 2,048 entries and 32 MiB of settings content. Existing SQLite/PostgreSQL revision triggers cover structural/direct SQL edits; counter-only changes retain cache reuse. Keep shared-client stats, fallback annotations, global traffic overlays and full-list/detail contracts intact. Add an exact-PASS PostgreSQL regression gate and a production-shaped benchmark with 30 inbounds, 7,100 clients and 115,000 actual membership rows. Validation: [final review](https://github.com/MHSanaei/3x-ui/pull/7287#issuecomment-7360333998), [CI 12/12](https://github.com/MHSanaei/3x-ui/actions/runs/46976935406), PostgreSQL 16 regression PASS, race, frontend 2,311 tests and four node-version pairings. Independent Lenovo SQLite/PG18 tests and [benchmark](https://github.com/MHSanaei/3x-ui/pull/7287#issuecomment-7359646826): stable JSON identical (39,246,921 bytes); warm p95 2670 -> 1031 ms, settings 46,122,401 -> 0 bytes, allocations -36.2%; concurrent structural edits p95 2673 -> 1148 ms, settings bytes -97.1%. Cold full reads remain and allocations increase 1.8%. Eight samples, same-binary baseline, synthetic topology, no production latency guarantee. The reviewed head is one commit behind main solely due to nonoverlapping #7277 dashboard/docs changes; both trees passed their own CI, but combined-tree CI remains to be verified after merge. No schema or wire-format change. Refs #7009 --- .github/workflows/ci.yml | 10 + internal/web/service/inbound.go | 8 +- internal/web/service/inbound_slim_cache.go | 120 ++++++++ .../inbound_slim_cache_benchmark_test.go | 132 +++++++++ ...nd_slim_cache_production_benchmark_test.go | 267 ++++++++++++++++++ .../web/service/inbound_slim_cache_test.go | 88 ++++++ 6 files changed, 619 insertions(+), 6 deletions(-) create mode 100644 internal/web/service/inbound_slim_cache.go create mode 100644 internal/web/service/inbound_slim_cache_benchmark_test.go create mode 100644 internal/web/service/inbound_slim_cache_production_benchmark_test.go create mode 100644 internal/web/service/inbound_slim_cache_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d00c7086..58ad65a3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -225,6 +225,16 @@ jobs: exit 1 fi + - name: PostgreSQL slim inbound cache regressions + run: | + set -o pipefail + go test ./internal/web/service -run '^TestSlimInboundListReusesOnlyTheMatchingSettingsRevision$' -count=1 -v | tee /tmp/postgres-slim-inbound-cache.log + passed=$(grep -c -- '^--- PASS: TestSlimInboundListReusesOnlyTheMatchingSettingsRevision ' /tmp/postgres-slim-inbound-cache.log || true) + if [ "$passed" -ne 1 ]; then + echo "expected the PostgreSQL slim inbound cache regression to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL node snapshot regressions run: | set -o pipefail diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 9097b5664..59bc2cabe 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -271,8 +271,7 @@ func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) { // for the edit/info/qr/export/clone flows that need it. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) { db := database.GetDB() - var inbounds []*model.Inbound - err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error + inbounds, err := loadSlimInboundRows(db, userId) if err == nil { err = attachClientStats(db, inbounds) } @@ -283,14 +282,11 @@ func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) { s.annotateLocalOriginGuid(inbounds) // Top up stats rows owned by sibling inbounds (multi-attached clients) // so the list's depleted/expiring badges see every client; the UUID/SubId - // enrichment stays skipped. Must run before slimming strips the settings. + // enrichment stays skipped. s.backfillClientStats(db, inbounds) // Slim feeds the panel UI only (masters poll the full list), so the badge // math may see the cross-panel totals a master pushed. s.overlayInboundsClientStats(db, inbounds) - for _, ib := range inbounds { - ib.Settings = slimSettingsClients(ib.Settings) - } return inbounds, nil } diff --git a/internal/web/service/inbound_slim_cache.go b/internal/web/service/inbound_slim_cache.go new file mode 100644 index 000000000..f7cab861f --- /dev/null +++ b/internal/web/service/inbound_slim_cache.go @@ -0,0 +1,120 @@ +package service + +import ( + "container/list" + "sync" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +const ( + slimSettingsMaxEntries = 2048 + slimSettingsMaxBytes = 32 << 20 +) + +type slimSettingsKey struct { + db *gorm.DB + id int + revision string +} + +type slimSettingsEntry struct { + key slimSettingsKey + settings string +} + +var slimSettingsCache = struct { + sync.Mutex + recency list.List + entries map[slimSettingsKey]*list.Element + bytes int +}{entries: make(map[slimSettingsKey]*list.Element)} + +func cachedSlimSettings(key slimSettingsKey) (string, bool) { + if key.revision == "" { + return "", false + } + c := &slimSettingsCache + c.Lock() + defer c.Unlock() + entry := c.entries[key] + if entry == nil { + return "", false + } + c.recency.MoveToFront(entry) + return entry.Value.(slimSettingsEntry).settings, true +} + +func rememberSlimSettings(key slimSettingsKey, settings string) { + if key.revision == "" || len(settings) > slimSettingsMaxBytes { + return + } + c := &slimSettingsCache + c.Lock() + defer c.Unlock() + if entry := c.entries[key]; entry != nil { + c.recency.MoveToFront(entry) + return + } + c.entries[key] = c.recency.PushFront(slimSettingsEntry{key, settings}) + c.bytes += len(settings) + for len(c.entries) > slimSettingsMaxEntries || c.bytes > slimSettingsMaxBytes { + oldest := c.recency.Back() + entry := c.recency.Remove(oldest).(slimSettingsEntry) + delete(c.entries, entry.key) + c.bytes -= len(entry.settings) + } +} + +// Structural revision triggers invalidate settings projections even for direct SQL edits. +// Counters and other row metadata are still read fresh on every request. +func loadSlimInboundRows(db *gorm.DB, userID int) ([]*model.Inbound, error) { + var rows []*model.Inbound + userRows := db.Model(&model.Inbound{}).Where("user_id = ?", userID) + if err := userRows.Session(&gorm.Session{}).Omit("Settings").Order("id ASC").Find(&rows).Error; err != nil { + return nil, err + } + + var missing []int + for _, row := range rows { + settings, ok := cachedSlimSettings(slimSettingsKey{db, row.Id, row.SnapshotRevision}) + if ok { + row.Settings = settings + } else { + missing = append(missing, row.Id) + } + } + if len(missing) == 0 { + return rows, nil + } + + resolved := make(map[int]*model.Inbound, len(missing)) + for _, ids := range chunkInts(missing, sqlInChunk) { + var full []*model.Inbound + if err := userRows.Session(&gorm.Session{}).Where("id IN ?", ids).Find(&full).Error; err != nil { + return nil, err + } + for _, row := range full { + row.Settings = slimSettingsClients(row.Settings) + rememberSlimSettings(slimSettingsKey{db, row.Id, row.SnapshotRevision}, row.Settings) + resolved[row.Id] = row + } + } + + // A miss is replaced with the whole row from its later read, so its metadata + // and projection share a revision. Exclude rows removed between the reads. + next := rows[:0] + miss := 0 + for _, row := range rows { + if miss < len(missing) && row.Id == missing[miss] { + miss++ + row = resolved[row.Id] + } + if row != nil { + next = append(next, row) + } + } + return next, nil +} diff --git a/internal/web/service/inbound_slim_cache_benchmark_test.go b/internal/web/service/inbound_slim_cache_benchmark_test.go new file mode 100644 index 000000000..6ac72119e --- /dev/null +++ b/internal/web/service/inbound_slim_cache_benchmark_test.go @@ -0,0 +1,132 @@ +package service + +import ( + "encoding/json" + "fmt" + "slices" + "strings" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" +) + +// BenchmarkSlimInboundList compares the list service and its JSON encoding, +// with dedicated SQL timing for the inbound queries. +func BenchmarkSlimInboundList(b *testing.B) { + cleanup, err := testpg.IsolatePackage("slim_settings_bench") + if err != nil { + b.Fatal(err) + } + b.Cleanup(cleanup) + setupBulkDB(b) + db := database.GetDB() + svc := new(InboundService) + var sqlStart time.Time + var sqlElapsed time.Duration + if err := db.Callback().Query().Before("gorm:query").Register("bench:inboundStart", func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + sqlStart = time.Now() + } + }); err != nil { + b.Fatal(err) + } + if err := db.Callback().Query().After("gorm:query").Register("bench:inboundElapsed", func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + sqlElapsed += time.Since(sqlStart) + } + }); err != nil { + b.Fatal(err) + } + + for _, count := range []int{1000, 10000, 20000} { + for _, shared := range []bool{false, true} { + userID := count * 2 + if shared { + userID++ + } + settingsBytes := 0 + for inbound := range 2 { + clients := make([]map[string]any, count) + for i := range clients { + emailIndex := i + if !shared { + emailIndex += inbound * count + } + clients[i] = map[string]any{ + "email": fmt.Sprintf("client-%d@example.test", emailIndex), + "enable": true, "comment": "fixture", "flow": "xtls-rprx-vision", + "id": strings.Repeat("a", 36), "subId": strings.Repeat("s", 16), + } + } + payload, err := json.Marshal(map[string]any{"clients": clients, "decryption": "none"}) + if err != nil { + b.Fatal(err) + } + settingsBytes += len(payload) + row := &model.Inbound{UserId: userID, Port: 2096, Tag: fmt.Sprintf("bench-%d-%d", userID, inbound), Protocol: model.VLESS, Enable: true, Settings: string(payload)} + if err := db.Create(row).Error; err != nil { + b.Fatal(err) + } + } + baseline := func() ([]*model.Inbound, error) { + var rows []*model.Inbound + if err := db.Where("user_id = ?", userID).Order("id ASC").Find(&rows).Error; err != nil { + return nil, err + } + if err := attachClientStats(db, rows); err != nil { + return nil, err + } + svc.annotateFallbackParents(db, rows) + svc.annotateLocalOriginGuid(rows) + svc.backfillClientStats(db, rows) + svc.overlayInboundsClientStats(db, rows) + for _, row := range rows { + row.Settings = slimSettingsClients(row.Settings) + } + return rows, nil + } + if _, err := svc.GetInboundsSlim(userID); err != nil { + b.Fatal(err) + } + for _, variant := range []struct { + name string + read func() ([]*model.Inbound, error) + settingsBytes int + }{ + {"full-read", baseline, settingsBytes}, + {"warm-projection", func() ([]*model.Inbound, error) { return svc.GetInboundsSlim(userID) }, 0}, + } { + b.Run(fmt.Sprintf("%d/shared=%t/%s", count, shared, variant.name), func(b *testing.B) { + var samples []time.Duration + var responseBytes int + sqlElapsed = 0 + b.ReportAllocs() + for b.Loop() { + start := time.Now() + rows, err := variant.read() + if err != nil { + b.Fatal(err) + } + response, err := json.Marshal(rows) + if err != nil { + b.Fatal(err) + } + responseBytes = len(response) + samples = append(samples, time.Since(start)) + } + slices.Sort(samples) + b.ReportMetric(float64(samples[(len(samples)-1)/2].Microseconds()), "p50-us") + b.ReportMetric(float64(samples[(len(samples)*95+99)/100-1].Microseconds()), "p95-us") + b.ReportMetric(float64(sqlElapsed.Microseconds())/float64(b.N), "inbound-sql-us/op") + b.ReportMetric(float64(variant.settingsBytes), "settings-SQL-B/op") + b.ReportMetric(float64(responseBytes), "response-B/op") + }) + } + } + } +} diff --git a/internal/web/service/inbound_slim_cache_production_benchmark_test.go b/internal/web/service/inbound_slim_cache_production_benchmark_test.go new file mode 100644 index 000000000..a44155cd4 --- /dev/null +++ b/internal/web/service/inbound_slim_cache_production_benchmark_test.go @@ -0,0 +1,267 @@ +package service + +import ( + "crypto/sha256" + "encoding/json" + "fmt" + "slices" + "strings" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +// seedSlimProductionFixture creates normalized records, shared memberships and +// sibling-owned traffic, not merely embedded settings arrays. +func seedSlimProductionFixture(b *testing.B, db *gorm.DB) (int, string, string) { + b.Helper() + const unique, memberships, inbounds = 7100, 115000, 30 + clients := makeScaleClients(unique) + records := make([]*model.ClientRecord, unique) + owners := make([]int, unique) + expiry := time.Now().AddDate(1, 0, 0).UnixMilli() + for i := range clients { + clients[i].Comment = fmt.Sprintf("fixture-plan-%04d", i%1000) + clients[i].TotalGB = 100 << 30 + clients[i].ExpiryTime = expiry + clients[i].Enable = i%17 != 0 + records[i] = clients[i].ToRecord() + } + var firstID int + var firstSettings, changedSettings string + err := db.Transaction(func(tx *gorm.DB) error { + if err := tx.CreateInBatches(records, 250).Error; err != nil { + return err + } + var nodes []model.Node + for i := range 4 { + nodes = append(nodes, model.Node{Name: fmt.Sprintf("fixture-node-%d", i), Address: "node.example.test", Port: 2053, Scheme: "https", Enable: true, Guid: fmt.Sprintf("fixture-guid-%d", i)}) + } + if err := tx.Create(&nodes).Error; err != nil { + return err + } + offset := 0 + for i := range inbounds { + count := memberships / inbounds + if i < memberships%inbounds { + count++ + } + subset := make([]model.Client, count) + links := make([]model.ClientInbound, count) + for j := range count { + index := (offset + j) % unique + subset[j] = clients[index] + links[j].ClientId = records[index].Id + } + row := model.Inbound{UserId: 1, Port: 41000 + i, Tag: fmt.Sprintf("slim-prod-%d", i), Protocol: model.VLESS, Enable: true, Settings: clientsSettings(b, subset)} + if i >= 14 { + row.NodeID = &nodes[(i-14)%len(nodes)].Id + row.OriginNodeGuid = nodes[(i-14)%len(nodes)].Guid + } + if err := tx.Create(&row).Error; err != nil { + return err + } + for j := range links { + index := (offset + j) % unique + links[j].InboundId = row.Id + if owners[index] == 0 { + owners[index] = row.Id + } + } + if err := tx.CreateInBatches(links, 1000).Error; err != nil { + return err + } + if i == 0 { + firstID, firstSettings = row.Id, row.Settings + changedSettings = strings.Replace(firstSettings, "fixture-plan-0000", "changed-plan-0000", 1) + } + offset += count + } + traffic := make([]xray.ClientTraffic, unique) + globals := make([]model.ClientGlobalTraffic, 0, unique/10) + for i, client := range clients { + traffic[i] = xray.ClientTraffic{InboundId: owners[i], Email: client.Email, Enable: client.Enable, Up: int64(i) * 1024, Down: int64(i) * 2048, Total: client.TotalGB, ExpiryTime: client.ExpiryTime} + if i%10 == 0 { + globals = append(globals, model.ClientGlobalTraffic{MasterGuid: "fixture-master", Email: client.Email, Up: int64(i) * 4096, Down: int64(i) * 8192, UpdatedAt: time.Now().UnixMilli()}) + } + } + if err := tx.CreateInBatches(traffic, 500).Error; err != nil { + return err + } + return tx.CreateInBatches(globals, 500).Error + }) + if err != nil { + b.Fatal(err) + } + for _, item := range []struct { + table string + want int64 + }{{"inbounds", inbounds}, {"clients", unique}, {"client_inbounds", memberships}, {"client_traffics", unique}} { + var count int64 + if err := db.Table(item.table).Count(&count).Error; err != nil || count != item.want { + b.Fatalf("%s: count=%d want=%d err=%v", item.table, count, item.want, err) + } + } + var rawBytes int64 + if err := db.Raw("SELECT SUM(LENGTH(settings)) FROM inbounds WHERE user_id = 1").Scan(&rawBytes).Error; err != nil { + b.Fatal(err) + } + if firstSettings == changedSettings { + b.Fatal("churn fixture did not change settings") + } + if err := db.Exec("ANALYZE").Error; err != nil { + b.Fatal(err) + } + b.Logf("fixture: %d inbounds, %d clients, %d memberships, %d traffic rows, %d raw settings bytes", inbounds, unique, memberships, unique, rawBytes) + return firstID, firstSettings, changedSettings +} + +// BenchmarkSlimInboundListProduction measures the service and JSON encoding, +// including cold reads and a single concurrent structural write per churn sample. +func BenchmarkSlimInboundListProduction(b *testing.B) { + cleanup, err := testpg.IsolatePackage("slim_production") + if err != nil { + b.Fatal(err) + } + b.Cleanup(cleanup) + setupScaleDB(b) + db := database.GetDB() + id, original, changed := seedSlimProductionFixture(b, db) + svc := new(InboundService) + baseline := func() ([]*model.Inbound, error) { + var rows []*model.Inbound + if err := db.Where("user_id = ?", 1).Order("id ASC").Find(&rows).Error; err != nil { + return nil, err + } + if err := attachClientStats(db, rows); err != nil { + return nil, err + } + svc.annotateFallbackParents(db, rows) + svc.annotateLocalOriginGuid(rows) + svc.backfillClientStats(db, rows) + svc.overlayInboundsClientStats(db, rows) + for _, row := range rows { + row.Settings = slimSettingsClients(row.Settings) + } + return rows, nil + } + projected := func() ([]*model.Inbound, error) { return svc.GetInboundsSlim(1) } + read := func(fn func() ([]*model.Inbound, error)) []byte { + rows, err := fn() + if err != nil { + b.Fatal(err) + } + payload, err := json.Marshal(rows) + if err != nil { + b.Fatal(err) + } + return payload + } + if sha256.Sum256(read(baseline)) != sha256.Sum256(read(projected)) { + b.Fatal("production fixture full/slim response mismatch") + } + var sqlStart time.Time + var sqlElapsed time.Duration + var settingsBytes, queries int64 + const before, after = "bench:slim-production-start", "bench:slim-production-end" + callbacks := db.Callback().Query() + if err := callbacks.Before("gorm:query").Register(before, func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + sqlStart = time.Now() + } + }); err != nil { + b.Fatal(err) + } + if err := callbacks.After("gorm:query").Register(after, func(tx *gorm.DB) { + if tx.Statement.Table != "inbounds" { + return + } + sqlElapsed += time.Since(sqlStart) + queries++ + if rows, ok := tx.Statement.Dest.(*[]*model.Inbound); ok { + for _, row := range *rows { + settingsBytes += int64(len(row.Settings)) + } + } + }); err != nil { + b.Fatal(err) + } + b.Cleanup(func() { _ = callbacks.Remove(before); _ = callbacks.Remove(after) }) + clear := func() { + c := &slimSettingsCache + c.Lock() + defer c.Unlock() + for key, element := range c.entries { + if key.db == db { + c.bytes -= len(element.Value.(slimSettingsEntry).settings) + c.recency.Remove(element) + delete(c.entries, key) + } + } + } + for _, mode := range []string{"warm", "cold", "churn"} { + for _, variant := range []struct { + name string + fn func() ([]*model.Inbound, error) + }{{"main", baseline}, {"pr", projected}} { + b.Run(mode+"/"+variant.name, func(b *testing.B) { + if err := db.Model(&model.Inbound{}).Where("id = ?", id).Update("settings", original).Error; err != nil { + b.Fatal(err) + } + clear() + read(variant.fn) + var samples []time.Duration + var responseBytes int + sqlElapsed, settingsBytes, queries = 0, 0, 0 + b.ReportAllocs() + for b.Loop() { + if mode == "cold" { + b.StopTimer() + clear() + b.StartTimer() + } + var done chan error + if mode == "churn" { + next := changed + if len(samples)%2 == 1 { + next = original + } + done = make(chan error, 1) + go func() { + done <- db.Model(&model.Inbound{}).Where("id = ?", id).Update("settings", next).Error + }() + } + start := time.Now() + rows, err := variant.fn() + if err != nil { + b.Fatal(err) + } + payload, err := json.Marshal(rows) + if err != nil { + b.Fatal(err) + } + responseBytes = len(payload) + samples = append(samples, time.Since(start)) + if done != nil { + if err := <-done; err != nil { + b.Fatal(err) + } + } + } + slices.Sort(samples) + b.ReportMetric(float64(samples[(len(samples)-1)/2].Microseconds())/1000, "p50-ms") + b.ReportMetric(float64(samples[(len(samples)*95+99)/100-1].Microseconds())/1000, "p95-ms") + b.ReportMetric(float64(sqlElapsed.Microseconds())/float64(b.N)/1000, "inbound-sql-ms/op") + b.ReportMetric(float64(settingsBytes)/float64(b.N), "settings-SQL-B/op") + b.ReportMetric(float64(queries)/float64(b.N), "inbound-queries/op") + b.ReportMetric(float64(responseBytes), "response-B/op") + }) + } + } +} diff --git a/internal/web/service/inbound_slim_cache_test.go b/internal/web/service/inbound_slim_cache_test.go new file mode 100644 index 000000000..c74f7407a --- /dev/null +++ b/internal/web/service/inbound_slim_cache_test.go @@ -0,0 +1,88 @@ +package service + +import ( + "reflect" + "strings" + "testing" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" +) + +func TestSlimInboundListReusesOnlyTheMatchingSettingsRevision(t *testing.T) { + cleanup, err := testpg.IsolatePackage("slim_settings") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + db := database.GetDB() + fixtures := []string{ + "{\"clients\":[{\"email\":\"Shared@test\",\"enable\":true,\"comment\":\"keep\",\"id\":\"discard\"}],\"decryption\":\"none\"}", + "{\"clients\":[null,7,{\"email\":\"Shared@test\",\"enable\":false,\"comment\":\"\"}],\"method\":\"custom\"}", + "{broken", + "{\"clients\":[]}", + } + for i, settings := range fixtures { + if err := db.Create(&model.Inbound{UserId: 1, Port: 30000 + i, Tag: "slim-" + string(rune('a'+i)), Protocol: model.VLESS, Settings: settings, Enable: true}).Error; err != nil { + t.Fatal(err) + } + } + var queries []string + if err := db.Callback().Query().After("gorm:query").Register("test:slim_settings", func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + queries = append(queries, tx.Statement.SQL.String()) + } + }); err != nil { + t.Fatal(err) + } + svc := new(InboundService) + check := func() []*model.Inbound { + t.Helper() + rows, err := svc.GetInboundsSlim(1) + if err != nil { + t.Fatal(err) + } + got := make([]string, 0, len(rows)) + want := make([]string, 0, len(fixtures)) + for _, row := range rows { + got = append(got, row.Settings) + } + for _, raw := range fixtures { + want = append(want, slimSettingsClients(raw)) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("slim settings = %q, want %q", got, want) + } + return rows + } + first := check() + queries = nil + check() + if len(queries) != 1 || strings.Contains(queries[0], "SELECT *") || strings.Contains(queries[0], "\"settings\"") || strings.Contains(queries[0], string(rune(96))+"settings"+string(rune(96))) { + t.Fatalf("warm slim list still reads the full settings: %v", queries) + } + if err := db.Model(&model.Inbound{}).Where("id = ?", first[0].Id).Update("up", 19).Error; err != nil { + t.Fatal(err) + } + queries = nil + if got := check()[0].Up; got != 19 || len(queries) != 1 { + t.Fatalf("counter change should be visible without reloading settings: up=%d, queries=%v", got, queries) + } + fixtures[0] = "{\"clients\":[{\"email\":\"changed@test\",\"enable\":true}]}" + if err := db.Exec("UPDATE inbounds SET settings = ? WHERE id = ?", fixtures[0], first[0].Id).Error; err != nil { + t.Fatal(err) + } + queries = nil + check() + if len(queries) != 2 { + t.Fatalf("one changed inbound should add a single batched read, got %v", queries) + } + full, err := svc.GetInbound(first[0].Id) + if err != nil || full.Settings != fixtures[0] { + t.Fatalf("full inbound lost its settings: %v", err) + } +} From fb14c8358a30f61a25f582b09c9e1cfe389c6c73 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 02:37:40 +0330 Subject: [PATCH 08/33] fix(inbounds): distinguish unavailable online attribution (#7289) Distinguish unavailable, pending, explicitly idle and legacy inbound online reports across REST, WebSocket and node snapshots. Require hosting-node emails and matching inbound activity; use a labeled node-wide fallback only for confirmed unsupported endpoints (HTTP 404/405). Track Xray freshness separately from sidecar observations and prevent accounting retries from publishing online state across core replacement. Preserve partial sidecar reports through mixed-version relays using the reserved nonempty NUL marker. Retain GUID/tag remapping and attached-client filtering. Validated on the reviewed head: all 12 CI jobs and Docs CI passed, including 2,332 frontend tests, mandatory PostgreSQL attribution regressions, race checks, Xray/node E2E and all four master/node version combinations. Exact client attribution across simultaneously active shared-client inbounds remains an estimate; older nodes may omit idle GUIDs during rollout. Fixes #7283. --- .github/workflows/ci.yml | 10 + .../content/docs/en/reference/api/clients.mdx | 36 ++-- docs/public/openapi.json | 10 +- frontend/public/openapi.json | 10 +- frontend/src/pages/api-docs/endpoints.ts | 4 +- .../src/pages/api-docs/websocket-events.ts | 7 +- .../pages/inbounds/list/InboundStatsModal.tsx | 9 + .../pages/inbounds/list/onlineStatusLabel.ts | 18 ++ frontend/src/pages/inbounds/list/types.ts | 1 + .../pages/inbounds/list/useInboundColumns.tsx | 13 +- frontend/src/pages/inbounds/useInbounds.ts | 64 ++++-- frontend/src/schemas/client.ts | 2 +- .../src/test/inbounds-ws-identity.test.tsx | 58 +++++- internal/mtproto/manager.go | 8 +- internal/mtproto/manager_client_ips_test.go | 5 +- internal/mtproto/manager_fronting_test.go | 7 +- internal/web/job/mtproto_job.go | 6 +- internal/web/job/node_traffic_sync_job.go | 9 + internal/web/job/tuic_job.go | 7 +- internal/web/job/xray_traffic_job.go | 35 ++-- internal/web/job/xray_traffic_retry_test.go | 75 +++++++ internal/web/runtime/node_snapshot.go | 4 +- internal/web/runtime/remote.go | 19 +- internal/web/runtime/remote_snapshot_test.go | 40 ++++ internal/web/service/inbound_node.go | 80 ++++++-- .../inbound_online_availability_test.go | 86 ++++++++ internal/web/service/node_origin_guid_test.go | 16 +- .../web/service/node_unsynced_online_test.go | 18 ++ internal/xray/online_test.go | 26 ++- internal/xray/process.go | 193 ++++++++++-------- 30 files changed, 672 insertions(+), 204 deletions(-) create mode 100644 frontend/src/pages/inbounds/list/onlineStatusLabel.ts create mode 100644 internal/web/service/inbound_online_availability_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58ad65a3b..9f8c2c9d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,6 +155,16 @@ jobs: exit 1 fi + - name: PostgreSQL online attribution regressions + run: | + set -o pipefail + go test -p=1 ./internal/web/job ./internal/web/service -run '^Test(InboundOnlineAvailabilityDistinguishesEmptyFromMissing|SetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags|XrayTrafficRetryDoesNotPublishOnlineStateAcrossCoreReplacement)$' -count=1 -v | tee /tmp/postgres-online-attribution.log + passed=$(grep -c -- '^--- PASS: Test' /tmp/postgres-online-attribution.log || true) + if [ "$passed" -ne 3 ]; then + echo "expected 3 passing PostgreSQL online attribution tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL node client push ordering run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 725bcacf2..86194e023 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -336,10 +336,9 @@ _openapi: - depth: 2 title: Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any - depth in a chain) uses its GUID. Lets the inbounds page attribute online - status to the real node instead of the intermediate one it syncs - through. - url: '#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through' + depth in a chain) uses its GUID. An empty list means the node reported + no online clients. An absent GUID means there is no usable report. + url: '#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-an-empty-list-means-the-node-reported-no-online-clients-an-absent-guid-means-there-is-no-usable-report' - depth: 2 title: Per-client source IPs grouped by the panelGuid of the node that observed them. Lets the central panel attribute and enforce per-client IP limits @@ -348,10 +347,12 @@ _openapi: url: '#per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through' - depth: 2 title: Inbound tags that carried traffic within the heartbeat window, grouped by - the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds - page only marks a multi-inbound client online on the inbounds it - actually used. Nodes that do not report per-inbound activity are absent. - url: '#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent' + the hosting node's panelGuid. Use with onlinesByGuid to scope online + counts. An empty list means no active tags, an absent GUID means there + is no usable report, and null means a confirmed legacy node lacks the + activity endpoint. The reserved NUL tag (U+0000) marks a partial report. + Inbounds whose tags are absent remain unknown. + url: '#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-use-with-onlinesbyguid-to-scope-online-counts-an-empty-list-means-no-active-tags-an-absent-guid-means-there-is-no-usable-report-and-null-means-a-confirmed-legacy-node-lacks-the-activity-endpoint-the-reserved-nul-tag-u0000-marks-a-partial-report-inbounds-whose-tags-are-absent-remain-unknown' - depth: 2 title: Map of client email → last-seen unix timestamp. url: '#map-of-client-email--last-seen-unix-timestamp' @@ -681,21 +682,22 @@ _openapi: id: list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node - content: Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each - node (at any depth in a chain) uses its GUID. Lets the inbounds page - attribute online status to the real node instead of the intermediate - one it syncs through. - id: online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through + node (at any depth in a chain) uses its GUID. An empty list means the + node reported no online clients. An absent GUID means there is no + usable report. + id: online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-an-empty-list-means-the-node-reported-no-online-clients-an-absent-guid-means-there-is-no-usable-report - content: Per-client source IPs grouped by the panelGuid of the node that observed them. Lets the central panel attribute and enforce per-client IP limits using the real visitor IPs each node sees, instead of the address of the intermediate panel it syncs through. id: per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through - content: Inbound tags that carried traffic within the heartbeat window, grouped - by the hosting node's panelGuid. Pairs with onlinesByGuid so the - inbounds page only marks a multi-inbound client online on the inbounds - it actually used. Nodes that do not report per-inbound activity are - absent. - id: inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent + by the hosting node's panelGuid. Use with onlinesByGuid to scope + online counts. An empty list means no active tags, an absent GUID + means there is no usable report, and null means a confirmed legacy + node lacks the activity endpoint. The reserved NUL tag (U+0000) marks + a partial report. Inbounds whose tags are absent remain unknown. + id: inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-use-with-onlinesbyguid-to-scope-online-counts-an-empty-list-means-no-active-tags-an-absent-guid-means-there-is-no-usable-report-and-null-means-a-confirmed-legacy-node-lacks-the-activity-endpoint-the-reserved-nul-tag-u0000-marks-a-partial-report-inbounds-whose-tags-are-absent-remain-unknown - content: Map of client email → last-seen unix timestamp. id: map-of-client-email--last-seen-unix-timestamp - content: Traffic counters for a client identified by email. diff --git a/docs/public/openapi.json b/docs/public/openapi.json index fee39fb9a..afb1a2f6b 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -13886,7 +13886,7 @@ "tags": [ "Clients" ], - "summary": "Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. Lets the inbounds page attribute online status to the real node instead of the intermediate one it syncs through.", + "summary": "Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. An empty list means the node reported no online clients. An absent GUID means there is no usable report.", "operationId": "post_panel_api_clients_onlinesByGuid", "responses": { "200": { @@ -13971,7 +13971,7 @@ "tags": [ "Clients" ], - "summary": "Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds page only marks a multi-inbound client online on the inbounds it actually used. Nodes that do not report per-inbound activity are absent.", + "summary": "Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Use with onlinesByGuid to scope online counts. An empty list means no active tags, an absent GUID means there is no usable report, and null means a confirmed legacy node lacks the activity endpoint. The reserved NUL tag (U+0000) marks a partial report. Inbounds whose tags are absent remain unknown.", "operationId": "post_panel_api_clients_activeInbounds", "responses": { "200": { @@ -20262,8 +20262,10 @@ "type": "array", "items": { "type": "string" - } - } + }, + "nullable": true + }, + "description": "Empty lists mean no active tags, absent GUIDs mean no usable report, and null denotes legacy nodes without per-inbound activity. The reserved NUL tag (U+0000) marks a partial report. Unlisted inbounds stay unknown." }, "lastOnlineMap": { "type": "object", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index fee39fb9a..afb1a2f6b 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -13886,7 +13886,7 @@ "tags": [ "Clients" ], - "summary": "Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. Lets the inbounds page attribute online status to the real node instead of the intermediate one it syncs through.", + "summary": "Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. An empty list means the node reported no online clients. An absent GUID means there is no usable report.", "operationId": "post_panel_api_clients_onlinesByGuid", "responses": { "200": { @@ -13971,7 +13971,7 @@ "tags": [ "Clients" ], - "summary": "Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds page only marks a multi-inbound client online on the inbounds it actually used. Nodes that do not report per-inbound activity are absent.", + "summary": "Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Use with onlinesByGuid to scope online counts. An empty list means no active tags, an absent GUID means there is no usable report, and null means a confirmed legacy node lacks the activity endpoint. The reserved NUL tag (U+0000) marks a partial report. Inbounds whose tags are absent remain unknown.", "operationId": "post_panel_api_clients_activeInbounds", "responses": { "200": { @@ -20262,8 +20262,10 @@ "type": "array", "items": { "type": "string" - } - } + }, + "nullable": true + }, + "description": "Empty lists mean no active tags, absent GUIDs mean no usable report, and null denotes legacy nodes without per-inbound activity. The reserved NUL tag (U+0000) marks a partial report. Unlisted inbounds stay unknown." }, "lastOnlineMap": { "type": "object", diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8e41e0bf9..a92ac3320 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1964,7 +1964,7 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/onlinesByGuid', summary: - 'Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. Lets the inbounds page attribute online status to the real node instead of the intermediate one it syncs through.', + 'Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. An empty list means the node reported no online clients. An absent GUID means there is no usable report.', response: '{\n "success": true,\n "obj": {\n "a1b2-...": ["user1"],\n "c3d4-...": ["user1", "user2"]\n }\n}', }, @@ -1980,7 +1980,7 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/activeInbounds', summary: - "Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds page only marks a multi-inbound client online on the inbounds it actually used. Nodes that do not report per-inbound activity are absent.", + "Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Use with onlinesByGuid to scope online counts. An empty list means no active tags, an absent GUID means there is no usable report, and null means a confirmed legacy node lacks the activity endpoint. The reserved NUL tag (U+0000) marks a partial report. Inbounds whose tags are absent remain unknown.", response: '{\n "success": true,\n "obj": {\n "a1b2-...": ["in-443-tcp", "in-8443-tcp"]\n }\n}', }, diff --git a/frontend/src/pages/api-docs/websocket-events.ts b/frontend/src/pages/api-docs/websocket-events.ts index 98ce384f8..681e4f938 100644 --- a/frontend/src/pages/api-docs/websocket-events.ts +++ b/frontend/src/pages/api-docs/websocket-events.ts @@ -140,7 +140,12 @@ const trafficPayloadSchema = { }, onlineClients: stringArray, onlineByGuid: stringArrayMap, - activeInbounds: stringArrayMap, + activeInbounds: { + type: 'object', + additionalProperties: { ...stringArray, nullable: true }, + description: + 'Empty lists mean no active tags, absent GUIDs mean no usable report, and null denotes legacy nodes without per-inbound activity. The reserved NUL tag (U+0000) marks a partial report. Unlisted inbounds stay unknown.', + }, lastOnlineMap: timestampMap, }, oneOf: [ diff --git a/frontend/src/pages/inbounds/list/InboundStatsModal.tsx b/frontend/src/pages/inbounds/list/InboundStatsModal.tsx index 27f638262..6a3916ab1 100644 --- a/frontend/src/pages/inbounds/list/InboundStatsModal.tsx +++ b/frontend/src/pages/inbounds/list/InboundStatsModal.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; +import { onlineStatusLabel } from './onlineStatusLabel'; import { Modal, Tag } from 'antd'; import { SizeFormatter, IntlUtil, ColorUtils } from '@/utils'; @@ -133,9 +134,17 @@ export default function InboundStatsModal({ {clientCount[record.id].clients} + {clientCount[record.id].onlineAttribution && + clientCount[record.id].online.length === 0 && ( + + {t('online')}: {onlineStatusLabel(clientCount[record.id], t)} + + )} {clientCount[record.id].online.length > 0 && ( {clientCount[record.id].online.length} {t('online')} + {clientCount[record.id].onlineAttribution === 'node' && + ` (${t('pages.inbounds.node')})`} )} {clientCount[record.id].depleted.length > 0 && ( diff --git a/frontend/src/pages/inbounds/list/onlineStatusLabel.ts b/frontend/src/pages/inbounds/list/onlineStatusLabel.ts new file mode 100644 index 000000000..8a9f26ba7 --- /dev/null +++ b/frontend/src/pages/inbounds/list/onlineStatusLabel.ts @@ -0,0 +1,18 @@ +import type { TFunction } from 'i18next'; + +import type { ClientCountEntry } from './types'; + +export function onlineStatusLabel(entry: ClientCountEntry, t: TFunction) { + switch (entry.onlineAttribution) { + case 'pending': + return t('loading'); + case 'inbound': + return '0'; + case 'node': + return `0 (${t('pages.inbounds.node')})`; + case 'unsupported': + return `${t('pages.nodes.statusValues.unknown')} (${t('pages.inbounds.node')})`; + default: + return t('pages.nodes.statusValues.unknown'); + } +} diff --git a/frontend/src/pages/inbounds/list/types.ts b/frontend/src/pages/inbounds/list/types.ts index ab76e334e..6e7d5ac44 100644 --- a/frontend/src/pages/inbounds/list/types.ts +++ b/frontend/src/pages/inbounds/list/types.ts @@ -45,6 +45,7 @@ export interface ClientCountEntry { depleted: string[]; expiring: string[]; online: string[]; + onlineAttribution?: 'pending' | 'unavailable' | 'inbound' | 'node' | 'unsupported'; } export interface InboundSpeedEntry { diff --git a/frontend/src/pages/inbounds/list/useInboundColumns.tsx b/frontend/src/pages/inbounds/list/useInboundColumns.tsx index 1d2a7c8bb..fc1d10d05 100644 --- a/frontend/src/pages/inbounds/list/useInboundColumns.tsx +++ b/frontend/src/pages/inbounds/list/useInboundColumns.tsx @@ -1,5 +1,6 @@ import { useMemo, type ReactElement } from 'react'; import { useTranslation } from 'react-i18next'; +import { onlineStatusLabel } from './onlineStatusLabel'; import { Popover, Switch, Tag, Tooltip, type TableColumnType } from 'antd'; import { TeamOutlined } from '@ant-design/icons'; @@ -366,9 +367,18 @@ export function useInboundColumns({ )} + {cc.onlineAttribution && cc.online.length === 0 && ( + + {t('online')}: {onlineStatusLabel(cc, t)} + + )} {cc.online.length > 0 && ( {cc.online.map((e) => ( @@ -383,6 +393,7 @@ export function useInboundColumns({ style={{ margin: 0, padding: '0 2px' }} > {cc.online.length} + {cc.onlineAttribution === 'node' && ` (${t('pages.inbounds.node')})`} )} diff --git a/frontend/src/pages/inbounds/useInbounds.ts b/frontend/src/pages/inbounds/useInbounds.ts index b69de541a..8911c0ce6 100644 --- a/frontend/src/pages/inbounds/useInbounds.ts +++ b/frontend/src/pages/inbounds/useInbounds.ts @@ -54,6 +54,7 @@ interface ClientRollup { depleted: string[]; expiring: string[]; online: string[]; + onlineAttribution: 'pending' | 'unavailable' | 'inbound' | 'node' | 'unsupported'; comments: Map; } @@ -101,12 +102,12 @@ async function fetchOnlineClientsByGuid(): Promise> { // Pairs with the per-node online map so a client attached to several inbounds // is only marked online on the ones that actually moved bytes — Xray's // user-level stat can't attribute traffic to a single inbound on its own. -async function fetchActiveInboundsByNode(): Promise> { +async function fetchActiveInboundsByNode(): Promise> { const msg = await HttpUtil.post('/panel/api/clients/activeInbounds', undefined, { silent: true }); if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch activeInbounds'); const validated = parseMsg(msg, ActiveInboundsByNodeSchema, 'clients/activeInbounds'); return validated.obj && typeof validated.obj === 'object' - ? (validated.obj as Record) + ? (validated.obj as Record) : {}; } @@ -119,13 +120,28 @@ function toGuidOnlineMap(data: Record): Map, +): Map | null> { + const map = new Map | 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)); + } + 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: Map>, b: Map>): boolean { +function sameGuidSets( + a: ReadonlyMap | null>, + b: ReadonlyMap | null>, +): boolean { if (a.size !== b.size) return false; for (const [key, set] of b) { const prev = a.get(key); - if (!prev || prev.size !== set.size) return false; + if (prev === set) continue; + if (!prev || !set || prev.size !== set.size) return false; for (const value of set) if (!prev.has(value)) return false; } return true; @@ -240,12 +256,11 @@ export function useInbounds() { // hosts it, attributing a sub-node's clients to that sub-node (#4983). const [onlineByGuid, setOnlineByGuid] = useState>>(() => new Map()); - // Recently-active inbound tags keyed by the hosting node's panelGuid. A GUID - // missing from this map means "no per-inbound activity reported" (e.g. remote - // nodes), so the rollup leaves that node's inbounds ungated and falls back to - // the email signal. A present GUID gates: a client only counts online on an - // inbound whose tag carried traffic this window. - const [activeByGuid, setActiveByGuid] = useState>>(() => new Map()); + // An explicit empty set is an idle node. A missing set has no usable activity sample. + const [activeByGuid, setActiveByGuid] = useState | null>>( + () => new Map(), + ); + const onlinePending = onlinesByGuidQuery.isPending || activeInboundsQuery.isPending; const [lastOnlineMap, setLastOnlineMap] = useState>({}); @@ -283,13 +298,21 @@ export function useInbounds() { const guid = dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : ''); const nodeOnline = onlineByGuid.get(guid); - // A node absent from the active map reports no per-inbound activity, so - // leave its inbounds ungated. When present, only mark a client online on - // this inbound if its tag actually carried traffic — that's what stops a - // multi-inbound client lighting up every inbound it's attached to. const activeForNode = activeByGuid.get(guid); - const inboundActive = - activeForNode === undefined || !dbInbound.tag || activeForNode.has(dbInbound.tag); + 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'; + } if (dbInbound.enable) { const statsByEmail = new Map< @@ -336,10 +359,11 @@ export function useInbounds() { depleted, expiring, online, + onlineAttribution, comments, }; }, - [onlineByGuid, activeByGuid, expireDiff, trafficDiff], + [onlineByGuid, activeByGuid, onlinePending, expireDiff, trafficDiff], ); // Every write to a DBInbound row also replaces the dbInbounds array, so this @@ -384,7 +408,7 @@ export function useInbounds() { const [syncedActiveInbounds, setSyncedActiveInbounds] = useState(); if (activeInboundsQuery.data && activeInboundsQuery.data !== syncedActiveInbounds) { setSyncedActiveInbounds(activeInboundsQuery.data); - setActiveByGuid(toGuidOnlineMap(activeInboundsQuery.data)); + setActiveByGuid(toActiveInboundMap(activeInboundsQuery.data)); } const [syncedLastOnline, setSyncedLastOnline] = useState(); @@ -443,7 +467,7 @@ export function useInbounds() { nodeTraffics?: TrafficDelta[]; onlineClients?: string[]; onlineByGuid?: Record; - activeInbounds?: Record; + activeInbounds?: Record; lastOnlineMap?: Record; }; if (Array.isArray(p.onlineClients)) { @@ -454,7 +478,7 @@ export function useInbounds() { setOnlineByGuid((prev) => (sameGuidSets(prev, next) ? prev : next)); } if (p.activeInbounds && typeof p.activeInbounds === 'object') { - const next = toGuidOnlineMap(p.activeInbounds); + const next = toActiveInboundMap(p.activeInbounds); setActiveByGuid((prev) => (sameGuidSets(prev, next) ? prev : next)); } if (p.lastOnlineMap && typeof p.lastOnlineMap === 'object') { diff --git a/frontend/src/schemas/client.ts b/frontend/src/schemas/client.ts index d7ca6016e..f851c5766 100644 --- a/frontend/src/schemas/client.ts +++ b/frontend/src/schemas/client.ts @@ -284,7 +284,7 @@ export const OnlineByNodeSchema = z .transform((v) => v ?? {}); export const ActiveInboundsByNodeSchema = z - .record(z.string(), nullableStringArray) + .record(z.string(), z.array(z.string()).nullable()) .nullable() .transform((v) => v ?? {}); diff --git a/frontend/src/test/inbounds-ws-identity.test.tsx b/frontend/src/test/inbounds-ws-identity.test.tsx index 8760dc78c..d8b6fc34b 100644 --- a/frontend/src/test/inbounds-ws-identity.test.tsx +++ b/frontend/src/test/inbounds-ws-identity.test.tsx @@ -1,8 +1,9 @@ import type { ReactNode } from 'react'; import { act, renderHook, waitFor } from '@testing-library/react'; import { QueryClientProvider } from '@tanstack/react-query'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; +import { HttpUtil } from '@/utils'; import { keys } from '@/api/queryKeys'; import { useInbounds } from '@/pages/inbounds/useInbounds'; @@ -33,7 +34,7 @@ function seedInbounds() { const wrapper = ({ children }: { children: ReactNode }) => ( {children} ); - return { rows, wrapper }; + return { queryClient, rows, wrapper }; } async function renderInbounds() { @@ -105,3 +106,56 @@ describe('inbound websocket merges keep unchanged state', () => { expect(result.current.clientCount).toBe(rollup); }); }); + +it('does not attribute shared online clients without matching inbound activity', async () => { + const { rows, queryClient, wrapper } = seedInbounds(); + queryClient.setQueryData( + keys.inbounds.slim(), + rows.map((row) => ({ + ...row, + originNodeGuid: 'shared-node', + settings: JSON.stringify({ clients: [{ email: 'c1@x', enable: true }] }), + })), + ); + const { result } = renderHook(() => useInbounds(), { wrapper }); + await waitFor(() => expect(result.current.dbInbounds).toHaveLength(2)); + const publish = ( + onlineByGuid: Record, + activeInbounds: Record, + ) => act(() => result.current.applyTrafficEvent({ onlineByGuid, activeInbounds })); + publish({ 'shared-node': ['c1@x'] }, {}); + expect(result.current.clientCount[1].online).toEqual([]); + expect(result.current.clientCount[1].onlineAttribution).toBe('unavailable'); + expect(result.current.clientCount[2].onlineAttribution).toBe('unavailable'); + publish({ 'shared-node': ['c1@x'] }, { 'shared-node': ['in-2', '\0'] }); + expect(result.current.clientCount[1].onlineAttribution).toBe('unavailable'); + expect(result.current.clientCount[2].onlineAttribution).toBe('inbound'); + expect(result.current.clientCount[2].online).toEqual(['c1@x']); + publish({ 'shared-node': ['c1@x'] }, { 'shared-node': [] }); + expect(result.current.clientCount[1].online).toEqual([]); + expect(result.current.clientCount[1].onlineAttribution).toBe('inbound'); + publish({ 'shared-node': ['c1@x'] }, { 'shared-node': ['in-2'] }); + expect(result.current.clientCount[1].online).toEqual([]); + expect(result.current.clientCount[2].online).toEqual(['c1@x']); + publish({}, {}); + expect(result.current.clientCount[2].onlineAttribution).toBe('unavailable'); + publish({ 'shared-node': ['c1@x'] }, { 'shared-node': null }); + expect(result.current.clientCount[2].onlineAttribution).toBe('node'); + expect(result.current.clientCount[2].online).toEqual(['c1@x']); + publish({ 'shared-node': [] }, { 'shared-node': [] }); + expect(result.current.clientCount[2].onlineAttribution).toBe('inbound'); + expect(result.current.clientCount[2].online).toEqual([]); +}); + +it('keeps online status pending while the activity query is unresolved', async () => { + const { queryClient, wrapper } = seedInbounds(); + queryClient.removeQueries({ queryKey: keys.clients.activeInbounds() }); + const post = vi.spyOn(HttpUtil, 'post').mockImplementation(() => new Promise(() => {})); + try { + const { result } = renderHook(() => useInbounds(), { wrapper }); + await waitFor(() => expect(result.current.clientCount[1].onlineAttribution).toBe('pending')); + expect(result.current.clientCount[1].online).toEqual([]); + } finally { + post.mockRestore(); + } +}); diff --git a/internal/mtproto/manager.go b/internal/mtproto/manager.go index 79005991e..f5ff0ffe8 100644 --- a/internal/mtproto/manager.go +++ b/internal/mtproto/manager.go @@ -429,7 +429,8 @@ func (m *Manager) StopAll() { // CollectTraffic scrapes each running mtg /stats endpoint for the byte deltas since the // previous scrape, per client and per inbound's fronted connections, and the online emails. -func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { +// The returned tags identify inbounds whose scrape succeeded, including idle ones. +func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string, []string) { type snap struct { id int apiPort int @@ -453,7 +454,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { var out []Traffic var fronted []FrontedTraffic - var online []string + var online, observedTags []string now := time.Now().Unix() for _, s := range snaps { stats, ok := scrapeStats(s.apiPort, s.apiToken) @@ -466,6 +467,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { m.mu.Unlock() continue } + observedTags = append(observedTags, s.tag) newLast := make(map[string]clientCounters, len(stats.Users)) for email, u := range stats.Users { now := u.counters() @@ -495,7 +497,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { } m.mu.Unlock() } - return out, fronted, online + return out, fronted, online, observedTags } // ClientIPs returns the addresses mtg reported connected at the last scrape, diff --git a/internal/mtproto/manager_client_ips_test.go b/internal/mtproto/manager_client_ips_test.go index c790f6922..562fd5d3e 100644 --- a/internal/mtproto/manager_client_ips_test.go +++ b/internal/mtproto/manager_client_ips_test.go @@ -66,7 +66,10 @@ func TestClientIPsFollowTheLastScrape(t *testing.T) { // A scrape that fails says nothing about who is connected: the addresses of the // previous one must not stay "live", or a client that left keeps counting. srv.Close() - mgr.CollectTraffic() + _, _, _, observed := mgr.CollectTraffic() + if len(observed) != 0 { + t.Fatalf("a failed scrape must leave the inbound unobserved, got %v", observed) + } if got := mgr.ClientIPs(); len(got) != 0 { t.Fatalf("a failed scrape must drop the known addresses, got %v", fmt.Sprint(got)) } diff --git a/internal/mtproto/manager_fronting_test.go b/internal/mtproto/manager_fronting_test.go index df9b06c61..47067e297 100644 --- a/internal/mtproto/manager_fronting_test.go +++ b/internal/mtproto/manager_fronting_test.go @@ -76,7 +76,7 @@ func TestCollectTrafficReportsFrontedBytes(t *testing.T) { nil, } for i, want := range wants { - clients, fronted, _ := mgr.CollectTraffic() + clients, fronted, _, _ := mgr.CollectTraffic() if len(clients) != 0 { t.Fatalf("scrape %d: fronted bytes must not be attributed to a client: %+v", i+1, clients) } @@ -104,7 +104,10 @@ func TestCollectTrafficWithoutFrontingCounters(t *testing.T) { mgr.procs[1].apiPort = serverPort(t, srv) mgr.CollectTraffic() - clients, fronted, online := mgr.CollectTraffic() + clients, fronted, online, tags := mgr.CollectTraffic() + if !reflect.DeepEqual(tags, []string{"inbound-1"}) { + t.Fatalf("successfully polled inbounds = %v, want [inbound-1]", tags) + } if want := []Traffic{{Tag: "inbound-1", Email: "alice", Up: 10, Down: 20}}; !reflect.DeepEqual(clients, want) { t.Fatalf("clients = %+v, want %+v", clients, want) } diff --git a/internal/web/job/mtproto_job.go b/internal/web/job/mtproto_job.go index 82a474f07..1e2dfbc02 100644 --- a/internal/web/job/mtproto_job.go +++ b/internal/web/job/mtproto_job.go @@ -30,9 +30,7 @@ func (j *MtprotoJob) Run() { } routedTags := make(map[string]bool) - activeTags := make([]string, 0, len(desired)) for _, inst := range desired { - activeTags = append(activeTags, inst.Tag) if inst.RouteThroughXray { routedTags[inst.Tag] = true } @@ -41,7 +39,7 @@ func (j *MtprotoJob) Run() { mgr := mtproto.GetManager() mgr.Reconcile(desired) - deltas, fronted, onlineEmails := mgr.CollectTraffic() + deltas, fronted, onlineEmails, observedTags := mgr.CollectTraffic() traffics, clientTraffics := rollUpMtprotoTraffic(deltas, fronted, routedTags) if len(traffics) > 0 || len(clientTraffics) > 0 { @@ -50,7 +48,7 @@ func (j *MtprotoJob) Run() { } } - j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags) + j.inboundService.RefreshLocalOnlineClients(onlineEmails, observedTags) } // rollUpMtprotoTraffic turns scraped mtg deltas into inbound and client traffic. diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index f86fc0934..aefa2acc0 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -151,6 +151,15 @@ func (j *NodeTrafficSyncJob) Run() { if j.hadNodes && !j.publishing { j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic) j.hadNodes = false + } else if websocket.HasClients() && !j.inboundService.HasFreshXrayOnlineSample() { + // Standalone panels also need to refresh attribution while Xray is unpolled. + j.startPeriodicWorker("local-online-publish", &j.publishing, func() { + websocket.BroadcastTraffic(map[string]any{ + "nodeTraffics": []*xray.Traffic{}, + "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(), + "activeInbounds": j.inboundService.GetActiveInboundsByGuid(), + }) + }) } return } diff --git a/internal/web/job/tuic_job.go b/internal/web/job/tuic_job.go index 9ae4abb38..1436f63ad 100644 --- a/internal/web/job/tuic_job.go +++ b/internal/web/job/tuic_job.go @@ -41,16 +41,11 @@ func (j *TuicJob) Run() { return } - activeTags := make([]string, 0, len(desired)) - for _, inst := range desired { - activeTags = append(activeTags, inst.Tag) - } - mgr := tuic.GetManager() mgr.Reconcile(desired) _, clientDeltas := mgr.CollectAllTraffic() - onlineEmails, _ := mgr.GetActiveClients(30 * time.Second) + onlineEmails, activeTags := mgr.GetActiveClients(30 * time.Second) clientTraffics := aggregateTuicClientTraffic(clientDeltas, onlineEmails) sampledAt := time.Now() diff --git a/internal/web/job/xray_traffic_job.go b/internal/web/job/xray_traffic_job.go index b1bd3e1a0..fc09c8bec 100644 --- a/internal/web/job/xray_traffic_job.go +++ b/internal/web/job/xray_traffic_job.go @@ -27,6 +27,7 @@ type XrayTrafficJob struct { type xrayTrafficSample struct { id string + core *xray.Process traffics []*xray.Traffic clients []*xray.ClientTraffic } @@ -77,11 +78,12 @@ func NewXrayTrafficJob() *XrayTrafficJob { func (j *XrayTrafficJob) pollTraffic(collect func() ([]*xray.Traffic, []*xray.ClientTraffic, error)) (sample *xrayTrafficSample, needRestart, clientsDisabled bool) { if j.pending == nil { + core := service.XrayProcess() traffics, clients, err := collect() if err != nil { return nil, false, false } - j.pending = &xrayTrafficSample{id: uuid.NewString(), traffics: traffics, clients: clients} + j.pending = &xrayTrafficSample{id: uuid.NewString(), core: core, traffics: traffics, clients: clients} } sample = j.pending needRestart, clientsDisabled, err := j.inboundService.AddXrayTrafficBatch(sample.id, sample.traffics, sample.clients) @@ -135,22 +137,25 @@ func (j *XrayTrafficJob) Run() { // client moves no bytes between polls (the delta heuristic's blind spot), // while a short-lived connection can close before this poll yet still show // in the delta. Older cores fall back to deltas alone. - if onlineUsers, apiMode, ouErr := j.xrayService.GetOnlineUsers(); ouErr != nil { - logger.Debug("get online users from xray api failed:", ouErr) - } else if apiMode { - idleOnline := make([]string, 0, len(onlineUsers)) - for _, u := range onlineUsers { - if !deltaActive[u.Email] { - activeEmails = append(activeEmails, u.Email) - idleOnline = append(idleOnline, u.Email) + if sample.core == service.XrayProcess() { + if onlineUsers, apiMode, ouErr := j.xrayService.GetOnlineUsers(); ouErr != nil { + logger.Debug("get online users from xray api failed:", ouErr) + } else if apiMode { + idleOnline := make([]string, 0, len(onlineUsers)) + for _, u := range onlineUsers { + if !deltaActive[u.Email] { + activeEmails = append(activeEmails, u.Email) + idleOnline = append(idleOnline, u.Email) + } + } + // The traffic path only bumps last_online on a non-zero delta; keep the + // column fresh for clients kept online purely by a live connection. + if err := j.inboundService.BumpClientsLastOnline(idleOnline); err != nil { + logger.Warning("bump last online for connected clients failed:", err) } } - // The traffic path only bumps last_online on a non-zero delta; keep the - // column fresh for clients kept online purely by a live connection. - if err := j.inboundService.BumpClientsLastOnline(idleOnline); err != nil { - logger.Warning("bump last online for connected clients failed:", err) - } } + // Pair the email signal with the inbound tags that moved bytes this poll. // Xray's user>>>email counter aggregates across every inbound a client is // attached to, so an online email alone can't say which inbound it used — @@ -162,7 +167,7 @@ func (j *XrayTrafficJob) Run() { activeInboundTags = append(activeInboundTags, tr.Tag) } } - j.inboundService.RefreshLocalOnlineClients(activeEmails, activeInboundTags) + j.inboundService.PublishXrayOnlineClients(sample.core, activeEmails, activeInboundTags) if !websocket.HasClients() { return diff --git a/internal/web/job/xray_traffic_retry_test.go b/internal/web/job/xray_traffic_retry_test.go index 5d52354a6..0404945d6 100644 --- a/internal/web/job/xray_traffic_retry_test.go +++ b/internal/web/job/xray_traffic_retry_test.go @@ -9,6 +9,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "runtime" "strings" "sync/atomic" "testing" @@ -23,6 +24,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/web/global" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" "github.com/mhsanaei/3x-ui/v3/internal/web/websocket" "github.com/mhsanaei/3x-ui/v3/internal/xray" ) @@ -303,3 +305,76 @@ func testXrayTrafficPollRetriesRolledBackSample(t *testing.T) { }) } } + +func TestXrayTrafficRetryDoesNotPublishOnlineStateAcrossCoreReplacement(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("uses a shell stub for the managed process") + } + cleanup, err := testpg.IsolatePackage("online_retry") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + dir := t.TempDir() + t.Setenv("XUI_DB_FOLDER", dir) + t.Setenv("XUI_BIN_FOLDER", dir) + t.Setenv("XUI_LOG_FOLDER", dir) + dbtest.InitDB(t, filepath.Join(dir, "x-ui.db")) + db := database.GetDB() + inbound := model.Inbound{Tag: "old-core", Protocol: model.VLESS, Enable: true, Settings: "{}"} + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + stub := "#!/bin/sh\nif [ \"$1\" = -version ]; then echo 'Xray 0.0.0 test'; exit 0; fi\nexec sleep 60\n" + if err := os.WriteFile(xray.GetBinaryPath(), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + startCore := func(name string) *xray.Process { + t.Helper() + core := xray.NewTestProcess(&xray.Config{}, filepath.Join(dir, name+".json")) + if err := core.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = core.Stop() }) + t.Cleanup(service.SetXrayProcessForTest(core)) + return core + } + old := startCore("old") + + const failure = "test:fail_pending_commit" + callback := db.Callback().Update() + if err := callback.Before("gorm:update").Register(failure, func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + _ = tx.AddError(errors.New("injected inbound traffic write failure")) + } + }); err != nil { + t.Fatal(err) + } + job := NewXrayTrafficJob() + sample, _, _ := job.pollTraffic(func() ([]*xray.Traffic, []*xray.ClientTraffic, error) { + return []*xray.Traffic{{Tag: inbound.Tag, IsInbound: true, Up: 11}}, nil, nil + }) + if sample != nil || job.pending == nil { + t.Fatal("the old core's sample was not retained for retry") + } + if err := callback.Remove(failure); err != nil { + t.Fatal(err) + } + + replacement := startCore("replacement") + job.Run() + if job.pending != nil { + t.Fatal("the old core's sample should still commit its accounting delta") + } + if err := db.First(&inbound, inbound.Id).Error; err != nil { + t.Fatal(err) + } + if inbound.Up != 11 { + t.Fatalf("inbound up=%d, want committed delta 11", inbound.Up) + } + for _, core := range []*xray.Process{old, replacement} { + if emails, tags := core.LocalOnlineSnapshot(time.Now().UnixMilli(), 20_000); emails != nil || tags != nil { + t.Fatalf("retry published online state across core replacement: %v / %v", emails, tags) + } + } +} diff --git a/internal/web/runtime/node_snapshot.go b/internal/web/runtime/node_snapshot.go index ac82098a1..d9bac194b 100644 --- a/internal/web/runtime/node_snapshot.go +++ b/internal/web/runtime/node_snapshot.go @@ -2,7 +2,6 @@ package runtime import ( "context" - "errors" "fmt" "net/http" "net/url" @@ -101,8 +100,7 @@ func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, er r.snapshotRevision = "" r.snapshotStructure = nil r.snapshotClients = nil - var status *remoteHTTPError - if !errors.As(err, &status) || (status.code != http.StatusNotFound && status.code != http.StatusMethodNotAllowed) { + if !nodeEndpointUnsupported(err) { return nil, err } r.snapshotUnsupportedUntil = time.Now().Add(5 * time.Minute) diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 7f9eab52f..e3e0830fd 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -1036,11 +1036,11 @@ type TrafficSnapshot struct { // the per-GUID endpoint — OnlineEmails is the fallback then. OnlineTree map[string][]string // ActiveInboundTree is the GUID-keyed subtree of inbound tags that carried - // traffic within the node's online grace window. Empty when the node is an - // old build without the endpoint; the master then falls back to email-only - // online attribution for that node. - ActiveInboundTree map[string][]string - LastOnlineMap map[string]int64 + // traffic within the node's online grace window. Missing keys carry no + // per-inbound attribution; an empty slice is a successful idle report. + ActiveInboundTree map[string][]string + LegacyInboundActivity bool + LastOnlineMap map[string]int64 // HostGroups carries the node's per-inbound host overrides (TLS/SNI/ // fingerprint), fetched only when the snapshot holds a not-yet-adopted tag. HostGroups []*entity.HostGroup @@ -1060,6 +1060,12 @@ func (r *Remote) FetchHostGroups(ctx context.Context) ([]*entity.HostGroup, erro return groups, nil } +func nodeEndpointUnsupported(err error) bool { + var status *remoteHTTPError + return errors.As(err, &status) && + (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed) +} + func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) { snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}} @@ -1077,7 +1083,7 @@ func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapsh if err == nil && len(envTree.Obj) > 0 { _ = decodeCappedValues(envTree.Obj, &snap.OnlineTree, maxNodeMapValues) } - if len(snap.OnlineTree) == 0 { + if nodeEndpointUnsupported(err) { envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlines", nil) if err != nil { logger.Warning("remote", r.node.Name, "onlines fetch failed:", err) @@ -1095,6 +1101,7 @@ func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapsh envActiveInbounds, err := r.do(ctx, http.MethodPost, "panel/api/clients/activeInbounds", nil) if err != nil { + snap.LegacyInboundActivity = nodeEndpointUnsupported(err) logger.Debugf("remote %s active inbounds fetch failed: %v", r.node.Name, err) } else if len(envActiveInbounds.Obj) > 0 { _ = decodeCappedValues(envActiveInbounds.Obj, &snap.ActiveInboundTree, maxNodeMapValues) diff --git a/internal/web/runtime/remote_snapshot_test.go b/internal/web/runtime/remote_snapshot_test.go index b3cddb33b..87e6ba6eb 100644 --- a/internal/web/runtime/remote_snapshot_test.go +++ b/internal/web/runtime/remote_snapshot_test.go @@ -194,3 +194,43 @@ func TestRemoteSnapshotRejectsTruncatedUnchangedCounters(t *testing.T) { t.Fatalf("partial counters could reach full merge: %+v %v", partial, err) } } + +func TestLegacySnapshotOnlyUnsupportedActivityEnablesNodeWideAttribution(t *testing.T) { + for _, code := range []int{200, 404, 405, 403, 500} { + t.Run(fmt.Sprint(code), func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/list", "/panel/api/clients/onlines": + fmt.Fprint(w, `{"success":true,"obj":[]}`) + case "/panel/api/clients/onlinesByGuid": + http.NotFound(w, req) + case "/panel/api/clients/activeInbounds": + if code == http.StatusOK { + fmt.Fprint(w, `{"success":true,"obj":{"online-guid":[],"legacy-descendant":null}}`) + } else { + w.WriteHeader(code) + } + default: + fmt.Fprint(w, `{"success":true,"obj":{}}`) + } + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + snapshot, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + if want := code == 404 || code == 405; snapshot.LegacyInboundActivity != want { + t.Fatalf("legacy activity=%v, want %v", snapshot.LegacyInboundActivity, want) + } + if code == http.StatusOK { + if idle := snapshot.ActiveInboundTree["online-guid"]; idle == nil || len(idle) != 0 { + t.Fatalf("lost successful idle sample: %v", snapshot.ActiveInboundTree) + } + if legacy, present := snapshot.ActiveInboundTree["legacy-descendant"]; !present || legacy != nil { + t.Fatalf("lost confirmed legacy descendant: %v", snapshot.ActiveInboundTree) + } + } + }) + } +} diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 269a2450e..f701851a3 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1675,15 +1675,18 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi attached, err := nodeAttachedEmails(db, nodeID) if err != nil { logger.Warningf("setRemoteTraffic: load the clients of node %d failed, dropping its online report: %v", nodeID, err) + snap.OnlineTree = nil + snap.OnlineEmails = nil + } else { + keepAttachedOnlineEmails(snap, attached) } - keepAttachedOnlineEmails(snap, attached) } if process := currentXrayProcess(); process != nil { hostedGuids := activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor) tree := snap.OnlineTree switch { - case len(tree) == 0 && len(snap.OnlineEmails) > 0: + case tree == nil && snap.OnlineEmails != nil: // Old-build node (no GUID tree): key its flat online list under its // own effective identity so attribution still works for that branch. tree = map[string][]string{selfKey: snap.OnlineEmails} @@ -1707,6 +1710,12 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if len(activeTree) > 0 { activeTree = filterGuidTreeKeys(activeTree, hostedGuids) } + if _, hosted := hostedGuids[selfKey]; hosted && snap.LegacyInboundActivity { + if activeTree == nil { + activeTree = make(map[string][]string) + } + activeTree[selfKey] = nil + } process.SetNodeActiveInboundTree(nodeID, activeTree) } @@ -1778,7 +1787,7 @@ func (s *InboundService) GetOnlineClientsByGuid() map[string][]string { return map[string][]string{} } out := process.GetMergedNodeTrees() - if local := process.GetLocalOnlineClients(); len(local) > 0 { + if local, _ := process.LocalOnlineSnapshot(time.Now().UnixMilli(), onlineGracePeriodMs); local != nil { if guid := s.panelGuid(); guid != "" { out[guid] = mergeEmails(out[guid], local) } @@ -1788,16 +1797,17 @@ func (s *InboundService) GetOnlineClientsByGuid() map[string][]string { // GetActiveInboundsByGuid returns the inbound tags that carried traffic within // the grace window, keyed by the panelGuid of the node that physically hosts -// each inbound. A GUID missing from the map means "don't gate" for that node's -// inbounds (old-build node or no active-inbound signal). +// each inbound. An absent GUID means the node did not supply usable activity +// data; an empty slice means idle and nil denotes a confirmed legacy node. +// The reserved NUL tag marks a partial report: unlisted inbounds remain unknown. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string { process := currentXrayProcess() if process == nil { return map[string][]string{} } out := process.GetMergedActiveInboundTrees() - active := process.GetLocalActiveInbounds() - if len(active) == 0 { + _, active := process.LocalOnlineSnapshot(time.Now().UnixMilli(), onlineGracePeriodMs) + if active == nil { return out } guid := s.panelGuid() @@ -1890,7 +1900,9 @@ func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]st if guid == from { guid = to } - remapped[guid] = mergeEmails(remapped[guid], values) + if prior, exists := remapped[guid]; !exists || values != nil { + remapped[guid] = mergeEmails(prior, values) + } } return remapped } @@ -1927,12 +1939,25 @@ func keepAttachedOnlineEmails(snap *runtime.TrafficSnapshot, attached map[string } return kept } - snap.OnlineEmails = keep(snap.OnlineEmails) + if snap.OnlineEmails != nil { + snap.OnlineEmails = keep(snap.OnlineEmails) + if snap.OnlineEmails == nil { + snap.OnlineEmails = []string{} + } + } + if snap.OnlineTree == nil { + return + } tree := make(map[string][]string, len(snap.OnlineTree)) for guid, emails := range snap.OnlineTree { - if kept := keep(emails); len(kept) > 0 { - tree[guid] = kept + if emails == nil { + continue } + kept := keep(emails) + if kept == nil { + kept = []string{} + } + tree[guid] = kept } snap.OnlineTree = tree } @@ -1943,15 +1968,20 @@ func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[s } out := make(map[string][]string, len(tree)) for guid, tags := range tree { - if guid == "" || len(tags) == 0 { + if guid == "" { continue } + if tags == nil { + out[guid] = nil + continue + } + out[guid] = []string{} seen := make(map[string]struct{}, len(tags)) for _, tag := range tags { if tag == "" { continue } - if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" { + if central, ok := tagToCentral[tag]; tag != xray.PartialInboundActivityTag && ok && central != nil && central.Tag != "" { tag = central.Tag } if _, dup := seen[tag]; dup { @@ -1992,9 +2022,7 @@ func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) m if _, ok := allowed[guid]; !ok { continue } - if len(values) > 0 { - out[guid] = values - } + out[guid] = values } if len(out) == 0 { return nil @@ -2019,17 +2047,27 @@ func clientsLastOnline(db *gorm.DB) (map[string]int64, error) { return result, nil } -// RefreshLocalOnlineClients folds the emails and inbound tags active on this -// panel's own xray this poll into the local online/active sets, applying the -// grace window and pruning stale entries. Pass nil to only prune. See -// xray.Process for why the local sets are kept separate from the shared -// last_online column. +// HasFreshXrayOnlineSample reports freshness independently of sidecar observations. +func (*InboundService) HasFreshXrayOnlineSample() bool { + process := currentXrayProcess() + return process != nil && process.HasFreshXrayOnlineSample(time.Now().UnixMilli(), onlineGracePeriodMs) +} + +// RefreshLocalOnlineClients adds sidecar activity or prunes the local window +// without treating it as a successful Xray poll. Pass nil slices to only prune. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) { if process := currentXrayProcess(); process != nil { process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs) } } +// PublishXrayOnlineClients records a successful poll on the current running core. +func (s *InboundService) PublishXrayOnlineClients(process *xray.Process, activeEmails, activeInboundTags []string) { + if process != nil && process == currentXrayProcess() && process.IsRunning() { + process.RecordXrayOnlineSample(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs) + } +} + func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) { db := database.GetDB() diff --git a/internal/web/service/inbound_online_availability_test.go b/internal/web/service/inbound_online_availability_test.go new file mode 100644 index 000000000..5ac8be17c --- /dev/null +++ b/internal/web/service/inbound_online_availability_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "slices" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestInboundOnlineAvailabilityDistinguishesEmptyFromMissing(t *testing.T) { + cleanup, err := testpg.IsolatePackage("online_availability") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupConflictDB(t) + process := useOnlineTestProcess(t) + svc := &InboundService{} + guid := svc.panelGuid() + if guid == "" { + t.Fatal("test panel has no GUID") + } + + process.RefreshLocalOnline(nil, nil, time.Now().UnixMilli(), onlineGracePeriodMs) + if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok { + t.Fatal("pruning before a local poll must not publish a known-empty result") + } + process = xray.NewTestProcess(nil, "") + xrayState.replace(process) + svc.RefreshLocalOnlineClients([]string{}, []string{}) + if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok { + t.Fatal("an idle sidecar tick must not publish activity on a replacement core") + } + process.RecordXrayOnlineSample(nil, nil, time.Now().UnixMilli(), onlineGracePeriodMs) + assertEmpty := func(signal map[string][]string, key string) { + t.Helper() + values, ok := signal[key] + if !ok || values == nil || len(values) != 0 { + t.Fatalf("expected an explicit empty list for %v in %v", key, signal) + } + } + assertEmpty(svc.GetOnlineClientsByGuid(), guid) + assertEmpty(svc.GetActiveInboundsByGuid(), guid) + + // A recently observed sidecar remains attributable while the Xray sample + // is stale. The reserved tag marks this as a partial report. + now := time.Now().UnixMilli() + process.RecordXrayOnlineSample([]string{"xray@example"}, []string{"xray"}, now-onlineGracePeriodMs, onlineGracePeriodMs) + svc.RefreshLocalOnlineClients([]string{"sidecar@example"}, []string{"sidecar"}) + if got := svc.GetOnlineClientsByGuid()[guid]; !slices.Equal(got, []string{"sidecar@example"}) { + t.Fatalf("partial report lost the sidecar or retained expired Xray clients: %v", got) + } + tags := svc.GetActiveInboundsByGuid()[guid] + if len(tags) != 2 || !slices.Contains(tags, "sidecar") || !slices.Contains(tags, xray.PartialInboundActivityTag) { + t.Fatalf("want only the sidecar tag and the partial report marker, got %v", tags) + } + if got := svc.GetOnlineClients(); !slices.Equal(got, []string{"sidecar@example"}) { + t.Fatalf("combined online list lost sidecar activity: %v", got) + } + process.RefreshLocalOnline(nil, nil, now+onlineGracePeriodMs+1000, onlineGracePeriodMs) + if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok { + t.Fatal("expired sidecar observations must not keep the partial report") + } + + xrayState.replace(xray.NewTestProcess(nil, "")) + if _, ok := svc.GetOnlineClientsByGuid()[guid]; ok { + t.Fatal("replacement core has not reported online clients yet") + } + if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok { + t.Fatal("replacement core has not reported active inbounds yet") + } + + svc.SetNodeOnlineTree(5, map[string][]string{"remote": {}}) + currentXrayProcess().SetNodeActiveInboundTree(5, map[string][]string{"remote": {}}) + assertEmpty(svc.GetOnlineClientsByGuid(), "remote") + assertEmpty(svc.GetActiveInboundsByGuid(), "remote") + svc.ClearNodeOnlineClients(5) + if _, ok := svc.GetOnlineClientsByGuid()["remote"]; ok { + t.Fatal("remote timeout must remove the stale online result") + } + if _, ok := svc.GetActiveInboundsByGuid()["remote"]; ok { + t.Fatal("remote timeout must remove the stale active-inbound result") + } +} diff --git a/internal/web/service/node_origin_guid_test.go b/internal/web/service/node_origin_guid_test.go index c577db363..4208c9951 100644 --- a/internal/web/service/node_origin_guid_test.go +++ b/internal/web/service/node_origin_guid_test.go @@ -7,6 +7,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" "github.com/mhsanaei/3x-ui/v3/internal/xray" ) @@ -146,6 +147,11 @@ func TestSetRemoteTraffic_RemapsClonedNodeOwnGuidOrigin(t *testing.T) { } func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) { + cleanup, err := testpg.IsolatePackage("online_remap") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) setupConflictDB(t) db := database.GetDB() @@ -178,6 +184,12 @@ func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) { } } + reporter := xray.NewTestProcess(nil, "") + reporter.RefreshLocalOnline([]string{"online@example.test"}, []string{"shared-tag"}, 1_000, 20_000) + _, tags := reporter.LocalOnlineSnapshot(1_000, 20_000) + // Older relays discard empty active tags when normalizing and forwarding a subtree. + tags = slices.DeleteFunc(tags, func(tag string) bool { return tag == "" }) + snap := &runtime.TrafficSnapshot{ Inbounds: []*model.Inbound{{ Tag: "shared-tag", @@ -187,7 +199,7 @@ func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) { Settings: `{"clients":[]}`, }}, ActiveInboundTree: map[string][]string{ - "dup": {"shared-tag"}, + "dup": tags, }, } @@ -197,7 +209,7 @@ func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) { } merged := process.GetMergedActiveInboundTrees() - assertStringSet(t, "active node:1", merged["node:1"], []string{"n1-shared-tag"}) + assertStringSet(t, "active node:1", merged["node:1"], []string{"n1-shared-tag", xray.PartialInboundActivityTag}) if _, ok := merged["dup"]; ok { t.Fatalf("cloned active-inbound subtree must not stay under shared GUID: %v", merged) } diff --git a/internal/web/service/node_unsynced_online_test.go b/internal/web/service/node_unsynced_online_test.go index 486c64123..f478922a8 100644 --- a/internal/web/service/node_unsynced_online_test.go +++ b/internal/web/service/node_unsynced_online_test.go @@ -92,6 +92,24 @@ func TestSetRemoteTrafficKeepsOnlyTheNodesOwnClientsOnline(t *testing.T) { if got, want := svc.GetOnlineClientsByGuid(), map[string][]string{"node-guid": {"kept@x"}}; !reflect.DeepEqual(got, want) { t.Fatalf("online by guid = %v, want %v", got, want) } + for _, legacy := range []bool{true, false} { + snap = snapshotWithClients(t, "keep", settings, xray.ClientTraffic{Email: "kept@x", Enable: true}) + snap.OnlineTree = map[string][]string{"node-guid": {}} + if legacy { + snap.LegacyInboundActivity = true + } else { + snap.ActiveInboundTree = map[string][]string{"node-guid": {}} + } + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatal(err) + } + if idle := svc.GetOnlineClientsByGuid()["node-guid"]; idle == nil || len(idle) != 0 { + t.Fatalf("lost explicit empty node online list: %v", idle) + } + if tags, present := svc.GetActiveInboundsByGuid()["node-guid"]; !present || (tags == nil) != legacy { + t.Fatalf("legacy=%t: incorrect activity report %v, present=%t", legacy, tags, present) + } + } } // The client-IP reports feed the IP limit and fail2ban; a node must not plant rows for diff --git a/internal/xray/online_test.go b/internal/xray/online_test.go index a621d6c2f..d973caba6 100644 --- a/internal/xray/online_test.go +++ b/internal/xray/online_test.go @@ -45,16 +45,15 @@ func TestMergedNodeTreesScopesPerGuid(t *testing.T) { } } -// TestMergedNodeTreesOmitsEmpty keeps the payload small: empty GUID sets don't -// appear as keys. -func TestMergedNodeTreesOmitsEmpty(t *testing.T) { +// Explicit empty reports are retained for the UI; omitted reports are unknown. +func TestMergedNodeTreesKeepsEmpty(t *testing.T) { p := newOnlineTestProcess() p.SetNodeOnlineTree(1, map[string][]string{ "guid-a": {"user1"}, "guid-x": {}, }) - if _, ok := p.GetMergedNodeTrees()["guid-x"]; ok { - t.Errorf("empty GUID set should be omitted: %v", p.GetMergedNodeTrees()) + if got := p.GetMergedNodeTrees()["guid-x"]; got == nil || len(got) != 0 { + t.Errorf("expected an explicit empty GUID set: %v", p.GetMergedNodeTrees()) } } @@ -132,8 +131,21 @@ func TestMergedActiveInboundTreesScopesPerGuid(t *testing.T) { merged := p.GetMergedActiveInboundTrees() assertSameSet(t, "guid-a", merged["guid-a"], []string{"in-a", "in-c"}) assertSameSet(t, "guid-b", merged["guid-b"], []string{"in-b"}) - if _, ok := merged["guid-c"]; ok { - t.Errorf("empty active-inbound GUID set should be omitted: %v", merged) + if idle := merged["guid-c"]; idle == nil || len(idle) != 0 { + t.Errorf("expected an explicit idle report for guid-c: %v", merged) + } +} + +func TestMergedActiveInboundTreesPreferActivityToLegacy(t *testing.T) { + p := newOnlineTestProcess() + p.SetNodeActiveInboundTree(1, map[string][]string{"reported": nil, "legacy-only": nil}) + p.SetNodeActiveInboundTree(2, map[string][]string{"reported": {}}) + merged := p.GetMergedActiveInboundTrees() + if tags, ok := merged["legacy-only"]; !ok || tags != nil { + t.Fatalf("lost confirmed legacy report: %v", merged) + } + if tags := merged["reported"]; tags == nil || len(tags) != 0 { + t.Fatalf("successful idle report should take precedence over legacy: %v", merged) } } diff --git a/internal/xray/process.go b/internal/xray/process.go index b3d836916..e270581ad 100644 --- a/internal/xray/process.go +++ b/internal/xray/process.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "os" "os/exec" "path/filepath" @@ -145,11 +146,14 @@ type process struct { apiPort int // onlineClients is the set of emails active on THIS panel's own xray - // within the online grace window. It is derived only from local xray - // traffic polls (see RefreshLocalOnline) — never from remote-node + // within the online grace window. It is derived from local Xray and sidecar + // traffic polls, never from remote-node // snapshots — so a client connected solely to a remote node is not // reported online on local inbounds. - onlineClients []string + onlineClients []string + localXraySampleAt int64 + localSidecarLastOnline map[string]int64 + localSidecarInboundLastActive map[string]int64 // localActiveInbounds is the set of THIS panel's inbound tags that // carried traffic within the same grace window. Xray's user>>>email // stat aggregates across every inbound a client is attached to, so an @@ -470,40 +474,55 @@ func (p *Process) GetLocalOnlineClients() []string { return out } -// GetMergedNodeTrees returns the union of every direct node's reported subtree, -// keyed by the panelGuid of the node that physically hosts each client set. -// Because each child already reports its descendants under their own GUIDs, -// merging the direct children yields the whole tree at any depth (#4983), so a -// client three hops down is attributed to its real node, not the intermediate -// one. GUIDs are globally unique, but a set reported under the same GUID by more -// than one path is deduped per key; empty sets are omitted. +// GetMergedNodeTrees returns online emails grouped by their physical node, +// including explicit empty results from nodes that reported a successful poll. func (p *Process) GetMergedNodeTrees() map[string][]string { p.onlineMu.RLock() defer p.onlineMu.RUnlock() - if len(p.nodeOnlineTrees) == 0 { - return map[string][]string{} - } + return mergeNodeOnlineTrees(p.nodeOnlineTrees, false) +} + +func mergeNodeOnlineTrees(trees map[int]map[string][]string, inboundActivity bool) map[string][]string { out := make(map[string][]string) seen := make(map[string]map[string]struct{}) - for _, tree := range p.nodeOnlineTrees { - for guid, emails := range tree { - if guid == "" || len(emails) == 0 { + complete := make(map[string]struct{}) + for _, tree := range trees { + for guid, values := range tree { + if guid == "" { continue } + if values == nil { + if _, known := out[guid]; inboundActivity && !known { + out[guid] = nil + } + continue + } + if inboundActivity && !slices.Contains(values, PartialInboundActivityTag) { + complete[guid] = struct{}{} + } dedup := seen[guid] if dedup == nil { - dedup = make(map[string]struct{}, len(emails)) + dedup = make(map[string]struct{}, len(values)) seen[guid] = dedup + out[guid] = make([]string, 0, len(values)) } - for _, email := range emails { - if _, ok := dedup[email]; ok { + for _, value := range values { + if value == "" { continue } - dedup[email] = struct{}{} - out[guid] = append(out[guid], email) + if _, ok := dedup[value]; ok { + continue + } + dedup[value] = struct{}{} + out[guid] = append(out[guid], value) } } } + for guid := range complete { + if _, partial := seen[guid][PartialInboundActivityTag]; partial { + out[guid] = slices.DeleteFunc(out[guid], func(tag string) bool { return tag == PartialInboundActivityTag }) + } + } return out } @@ -529,76 +548,86 @@ func (p *Process) GetLocalActiveInbounds() []string { func (p *Process) GetMergedActiveInboundTrees() map[string][]string { p.onlineMu.RLock() defer p.onlineMu.RUnlock() - if len(p.nodeActiveInboundTrees) == 0 { - return map[string][]string{} - } - out := make(map[string][]string) - seen := make(map[string]map[string]struct{}) - for _, tree := range p.nodeActiveInboundTrees { - for guid, tags := range tree { - if guid == "" || len(tags) == 0 { - continue - } - dedup := seen[guid] - if dedup == nil { - dedup = make(map[string]struct{}, len(tags)) - seen[guid] = dedup - } - for _, tag := range tags { - if tag == "" { - continue - } - if _, ok := dedup[tag]; ok { - continue - } - dedup[tag] = struct{}{} - out[guid] = append(out[guid], tag) - } - } - } - return out + return mergeNodeOnlineTrees(p.nodeActiveInboundTrees, true) } -// RefreshLocalOnline records that each email in activeEmails and each tag in -// activeInboundTags had local xray traffic at now, then rebuilds onlineClients -// and localActiveInbounds from every entry seen within graceMs, pruning older -// ones. Called by the local XrayTrafficJob after each xray gRPC stats poll. -// Pass nil/empty slices to only prune — NodeTrafficSyncJob does this so a -// stopped local xray's clients and inbounds still age out between local polls. +// PartialInboundActivityTag marks a report whose listed tags are known but +// whose other inbounds are unknown. Use a reserved nonempty value so older +// panels that drop empty tags can still forward it. +const PartialInboundActivityTag = "\x00" + +// HasFreshXrayOnlineSample reports whether this core has a usable Xray sample. +func (p *Process) HasFreshXrayOnlineSample(now, graceMs int64) bool { + p.onlineMu.RLock() + defer p.onlineMu.RUnlock() + return p.hasFreshXrayOnlineSample(now, graceMs) +} + +func (p *Process) hasFreshXrayOnlineSample(now, graceMs int64) bool { + return p.localXraySampleAt != 0 && now-p.localXraySampleAt < graceMs +} + +// LocalOnlineSnapshot reports the full window when Xray is fresh. Otherwise +// only independently observed sidecar inbounds can be attributed. +func (p *Process) LocalOnlineSnapshot(now, graceMs int64) (emails, tags []string) { + p.onlineMu.RLock() + defer p.onlineMu.RUnlock() + if p.hasFreshXrayOnlineSample(now, graceMs) { + return slices.Clone(p.onlineClients), slices.Clone(p.localActiveInbounds) + } + tags = recentOnlineObservations(p.localSidecarInboundLastActive, now, graceMs) + if len(tags) == 0 { + return nil, nil + } + emails = recentOnlineObservations(p.localSidecarLastOnline, now, graceMs) + return emails, append(tags, PartialInboundActivityTag) +} + +// RecordXrayOnlineSample records a successful poll, including an idle one. +func (p *Process) RecordXrayOnlineSample(activeEmails, activeInboundTags []string, now, graceMs int64) { + p.onlineMu.Lock() + defer p.onlineMu.Unlock() + p.localXraySampleAt = now + p.refreshLocalOnline(activeEmails, activeInboundTags, now, graceMs) +} + +// RefreshLocalOnline merges sidecar activity or prunes old observations without +// marking the local Xray core as polled. func (p *Process) RefreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) { p.onlineMu.Lock() defer p.onlineMu.Unlock() - if p.localLastOnline == nil { - p.localLastOnline = make(map[string]int64, len(activeEmails)) - } - for _, email := range activeEmails { - p.localLastOnline[email] = now - } - online := make([]string, 0, len(p.localLastOnline)) - for email, ts := range p.localLastOnline { - if now-ts < graceMs { - online = append(online, email) - } else { - delete(p.localLastOnline, email) - } - } - p.onlineClients = online + refreshOnlineObservations(&p.localSidecarLastOnline, activeEmails, now, graceMs) + refreshOnlineObservations(&p.localSidecarInboundLastActive, activeInboundTags, now, graceMs) + p.refreshLocalOnline(activeEmails, activeInboundTags, now, graceMs) +} - if p.localInboundLastActive == nil { - p.localInboundLastActive = make(map[string]int64, len(activeInboundTags)) +func (p *Process) refreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) { + refreshOnlineObservations(&p.localLastOnline, activeEmails, now, graceMs) + refreshOnlineObservations(&p.localInboundLastActive, activeInboundTags, now, graceMs) + p.onlineClients = slices.AppendSeq(make([]string, 0, len(p.localLastOnline)), maps.Keys(p.localLastOnline)) + p.localActiveInbounds = slices.AppendSeq(make([]string, 0, len(p.localInboundLastActive)), maps.Keys(p.localInboundLastActive)) +} + +func refreshOnlineObservations(last *map[string]int64, active []string, now, graceMs int64) { + if len(active) > 0 && *last == nil { + *last = make(map[string]int64, len(active)) } - for _, tag := range activeInboundTags { - p.localInboundLastActive[tag] = now - } - activeInbounds := make([]string, 0, len(p.localInboundLastActive)) - for tag, ts := range p.localInboundLastActive { - if now-ts < graceMs { - activeInbounds = append(activeInbounds, tag) - } else { - delete(p.localInboundLastActive, tag) + for _, value := range active { + if value != "" && value != PartialInboundActivityTag { + (*last)[value] = now } } - p.localActiveInbounds = activeInbounds + maps.DeleteFunc(*last, func(_ string, ts int64) bool { return now-ts >= graceMs }) +} + +func recentOnlineObservations(last map[string]int64, now, graceMs int64) []string { + recent := make([]string, 0, len(last)) + for value, ts := range last { + if now-ts < graceMs { + recent = append(recent, value) + } + } + return recent } // SetNodeOnlineTree records the GUID-keyed online subtree one direct remote From 8a686cd8bdd524a3068209ca73e57bbd12e0c586 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 03:00:12 +0330 Subject: [PATCH 09/33] 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. --- .../pages/inbounds/ClientRollups.stories.tsx | 115 ++++++++ frontend/src/pages/inbounds/InboundsPage.tsx | 5 +- .../src/pages/inbounds/list/InboundList.tsx | 2 + frontend/src/pages/inbounds/list/types.ts | 1 + .../pages/inbounds/list/useInboundColumns.tsx | 150 +++++------ frontend/src/pages/inbounds/useInbounds.ts | 255 +++++++++++++----- .../src/test/inbounds-ws-identity.test.tsx | 243 ++++++++++++++++- internal/amneziawgnet/relay_e2e_test.go | 45 ++-- internal/web/service/tgbot/tgbot_send_test.go | 17 +- .../web/service/tuic_relay_isolation_test.go | 17 +- 10 files changed, 645 insertions(+), 205 deletions(-) create mode 100644 frontend/src/pages/inbounds/ClientRollups.stories.tsx diff --git a/frontend/src/pages/inbounds/ClientRollups.stories.tsx b/frontend/src/pages/inbounds/ClientRollups.stories.tsx new file mode 100644 index 000000000..06b74132d --- /dev/null +++ b/frontend/src/pages/inbounds/ClientRollups.stories.tsx @@ -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 ( + <> + +

+ {clientCount[30] + ? 'Rollups ready' + : dbInbounds.length + ? 'Calculating rollups' + : 'Waiting for inbounds'} +

+ +
Last inbound online: {clientCount[30]?.online.length ?? '…'}
+
First inbound online: {clientCount[1]?.online.length ?? '…'}
+ + ); +} + +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 ( + + + + + ); +} + +export const LargeDeployment: StoryObj = { + render: () => , + 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), + }); + }, +}; diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx index 7ffaf5de0..6c062533f 100644 --- a/frontend/src/pages/inbounds/InboundsPage.tsx +++ b/frontend/src/pages/inbounds/InboundsPage.tsx @@ -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() { ; + clientCountsPending: boolean; onlineClients: string[]; lastOnlineMap: Record; inboundSpeed: Record; diff --git a/frontend/src/pages/inbounds/list/useInboundColumns.tsx b/frontend/src/pages/inbounds/list/useInboundColumns.tsx index fc1d10d05..63e42b33a 100644 --- a/frontend/src/pages/inbounds/list/useInboundColumns.tsx +++ b/frontend/src/pages/inbounds/list/useInboundColumns.tsx @@ -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 = ( + + {emails.length} + {suffix && ` ${suffix}`} + + ); + if (!emails.length) return badge; + return ( + + {emails.map((email) => ( +
{email}
+ ))} +
+ ) : null + } + > + {badge} + + ); +} + interface UseInboundColumnsParams { hasAnyRemark: boolean; hasAnySubSortIndex: boolean; @@ -35,6 +78,7 @@ interface UseInboundColumnsParams { nodesById: Map; hostRemarksByInboundId: Map; clientCount: Record; + clientCountsPending: boolean; inboundSpeed: Record; 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 ( <> {cc.clients} - {cc.active.length > 0 ? ( - - {cc.active.map((e) => ( -
{e}
- ))} - - } - > - - {cc.active.length} - -
- ) : ( - - 0 - - )} + {cc.deactive.length > 0 && ( - - {cc.deactive.map((e) => ( -
{e}
- ))} - - } - > - - {cc.deactive.length} - -
+ )} {cc.depleted.length > 0 && ( - - {cc.depleted.map((e) => ( -
{e}
- ))} - - } - > - - {cc.depleted.length} - -
+ )} {cc.onlineAttribution && cc.online.length === 0 && ( @@ -373,29 +363,12 @@ export function useInboundColumns({ )} {cc.online.length > 0 && ( - - {cc.online.map((e) => ( -
{e}
- ))} - - } - > - - {cc.online.length} - {cc.onlineAttribution === 'node' && ` (${t('pages.inbounds.node')})`} - -
+ )} ); @@ -488,6 +461,7 @@ export function useInboundColumns({ nodesById, hostRemarksByInboundId, clientCount, + clientCountsPending, inboundSpeed, subEnable, expireDiff, diff --git a/frontend/src/pages/inbounds/useInbounds.ts b/frontend/src/pages/inbounds/useInbounds.ts index 8911c0ce6..4cc55c11a 100644 --- a/frontend/src/pages/inbounds/useInbounds.ts +++ b/frontend/src/pages/inbounds/useInbounds.ts @@ -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; } +interface CachedClientRollup { + base: ClientRollup; + refreshAt: number; + online?: { emails?: Set; result: ClientRollup }; +} + +const EMPTY_ONLINE: string[] = []; +const EMPTY_ROLLUPS: Record = {}; + const TRACKED_PROTOCOLS: readonly string[] = [ Protocols.VMESS, Protocols.VLESS, @@ -124,27 +133,37 @@ function toActiveInboundMap( data: Record, ): Map | null> { const map = new Map | 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 | null>, - b: ReadonlyMap | 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 | null>( + previous: Map, + next: Map, +): Map { + 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> { @@ -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([]); + const [inboundGeneration, setInboundGeneration] = useState(0); const dbInboundsRef = useRef([]); useEffect(() => { dbInboundsRef.current = dbInbounds; @@ -265,10 +285,7 @@ export function useInbounds() { const [lastOnlineMap, setLastOnlineMap] = useState>({}); 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(); - 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(), 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; + }>(); + useEffect(() => { + if (!largeList) return; const counts: Record = {}; - 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; + 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 = {}; + 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(); 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, diff --git a/frontend/src/test/inbounds-ws-identity.test.tsx b/frontend/src/test/inbounds-ws-identity.test.tsx index d8b6fc34b..70118871f 100644 --- a/frontend/src/test/inbounds-ws-identity.test.tsx +++ b/frontend/src/test/inbounds-ws-identity.test.tsx @@ -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( + + + , + { 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( diff --git a/internal/amneziawgnet/relay_e2e_test.go b/internal/amneziawgnet/relay_e2e_test.go index 2d5a5756c..753ff6545 100644 --- a/internal/amneziawgnet/relay_e2e_test.go +++ b/internal/amneziawgnet/relay_e2e_test.go @@ -152,7 +152,7 @@ func TestSocksRelayAgainstRealXray(t *testing.T) { } defer func() { _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() + _ = cmd.Wait() }() waitForPort(t, socksPort) @@ -268,20 +268,10 @@ func TestSocksRelayAgainstRealXray(t *testing.T) { t.Fatalf("UDP echo = %q, want %q (xray log follows)\n%s", gotUDP, udpMsg, xrayLog.String()) } - // Real per-peer stats attribution: stop xray so its log is complete, then - // look for both directions' counters keyed by the peer's real email -- - // the exact proof Finding 3 established manually in Phase 0. - _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() - log := xrayLog.String() - wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail) - wantDown := fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail) - if !strings.Contains(log, wantUp) { - t.Errorf("xray log missing uplink stats counter %q\nfull log:\n%s", wantUp, log) - } - if !strings.Contains(log, wantDown) { - t.Errorf("xray log missing downlink stats counter %q\nfull log:\n%s", wantDown, log) - } + waitForXrayCounters(t, &xrayLog, + fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail), + fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail), + ) } // TestManagerEnsureAutomaticallyWiresRelay is Phase 3's own real proof: unlike @@ -392,7 +382,7 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) { } defer func() { _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() + _ = cmd.Wait() }() waitForPort(t, socksPort) @@ -462,12 +452,23 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) { t.Errorf("TCP echo = %q, want %q", buf, tcpMsg) } - _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() - log := xrayLog.String() - wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail) - if !strings.Contains(log, wantUp) { - t.Errorf("xray log missing uplink stats counter %q (Manager.Ensure's automatic relay wiring may not be attributing traffic correctly)\nfull log:\n%s", wantUp, log) + waitForXrayCounters(t, &xrayLog, fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail)) +} + +func waitForXrayCounters(t *testing.T, log *syncBuffer, counters ...string) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for _, counter := range counters { + for { + output := log.String() + if strings.Contains(output, counter) { + break + } + if time.Now().After(deadline) { + t.Fatalf("xray log missing stats counter %q\nfull log:\n%s", counter, output) + } + time.Sleep(10 * time.Millisecond) + } } } diff --git a/internal/web/service/tgbot/tgbot_send_test.go b/internal/web/service/tgbot/tgbot_send_test.go index b86391725..b71112ae8 100644 --- a/internal/web/service/tgbot/tgbot_send_test.go +++ b/internal/web/service/tgbot/tgbot_send_test.go @@ -11,7 +11,6 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/logger" - "github.com/mymmrac/telego" tu "github.com/mymmrac/telego/telegoutil" "github.com/nicksnyder/go-i18n/v2/i18n" ) @@ -55,13 +54,7 @@ func TestEditMessageTgBotSkipsNotModified(t *testing.T) { defer mock.Close() // Point the package-level bot at the mock. - origBot := liveBot() - t.Cleanup(func() { setTestBot(origBot) }) - var err error - bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL)) - if err != nil { - t.Fatalf("NewBot: %v", err) - } + swapTestBot(t, mock.URL) // Snapshot warning count before the edit call. before := logger.GetLogs(100, "warning") @@ -87,13 +80,7 @@ func TestEditMessageCallbackTgBotSkipsNotModified(t *testing.T) { })) defer mock.Close() - origBot := liveBot() - t.Cleanup(func() { setTestBot(origBot) }) - var err error - bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL)) - if err != nil { - t.Fatalf("NewBot: %v", err) - } + swapTestBot(t, mock.URL) before := logger.GetLogs(100, "warning") diff --git a/internal/web/service/tuic_relay_isolation_test.go b/internal/web/service/tuic_relay_isolation_test.go index bc19cfc3c..f6caa4bdd 100644 --- a/internal/web/service/tuic_relay_isolation_test.go +++ b/internal/web/service/tuic_relay_isolation_test.go @@ -262,6 +262,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) dependent := ordinary dependent.Tag = "dependent-ordinary" dependent.Port = freeLoopbackPort(t) + for dependent.Port == ordinary.Port { + dependent.Port = freeLoopbackPort(t) + } updatedSecond := isolationRelay(t, second.TuicInboundID, "new-second@test") after.InboundConfigs = []xray.InboundConfig{before.InboundConfigs[0], next, updatedSecond, ordinary, dependent} var policy map[string]any @@ -278,6 +281,12 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) if applied, err := (&XrayService{}).tryHotApply(process, &after); applied || err == nil || !strings.Contains(err.Error(), "SOCKS5 bounds") { t.Fatalf("failed rename result = %t, %v", applied, err) } + // Reserve the deferred port before the relay probes start their own listeners. + reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port)) + if err != nil { + t.Fatalf("new inbound started before its dependent routing was applied: %v", err) + } + t.Cleanup(func() { _ = reservation.Close() }) assertIsolationRelay(t, previous, "original@test") assertIsolationRelay(t, second, "old-second@test") ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) @@ -294,11 +303,6 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) t.Fatalf("new TUIC account escaped its deferred routing policy: %v", err) } assertIsolationRelay(t, ordinary, "other@test") - reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port)) - if err != nil { - t.Fatalf("new inbound started before its dependent routing was applied: %v", err) - } - _ = reservation.Close() route, err := api.TestRoute(xray.RouteTestRequest{InboundTag: next.Tag, IP: "203.0.113.1", Port: 6697}) if err != nil || route.Matched { t.Fatalf("routing depending on an uninstalled relay was published: route=%+v err=%v", route, err) @@ -306,6 +310,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) if string(process.GetConfig().RouterConfig) != string(before.RouterConfig) { t.Fatal("snapshot recorded deferred routing as applied") } + if err := reservation.Close(); err != nil { + t.Fatal(err) + } after.InboundConfigs[1] = previous after.InboundConfigs[1].Tag = next.Tag if applied, err := (&XrayService{}).tryHotApply(process, &after); !applied || err != nil { From 0afa11ddffa7958585d320179415d1d5fe410a5c Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 03:26:44 +0330 Subject: [PATCH 10/33] fix(nodes): share lightweight remote inbound catalog refreshes (#7313) Replace full inbound/client-list downloads on cold remote ID lookups with an owner-scoped six-field catalog projected directly from the database. Coalesce concurrent catalog refreshes per remote while preserving independent caller cancellation and rejecting stale ID mappings after topology mutations. Seed reconciliation from the catalog, create missing inbounds directly, preserve prefixed/adopted aliases and invalidate pushed state when remote IDs change. Avoid invalidating catalog generations on unchanged-ID settings pushes. Retain client-membership-aware reconciliation state and legacy full-list fallback only on HTTP 404/405. Cover permissions, query projection, concurrent refresh/cancellation, deletion/recreation, reconciliation request counts and mixed-version node compatibility. Integrated CI and Docs CI passed, including race, node E2E and PostgreSQL catalog projection. Synthetic response-size comparison is not a production latency benchmark. Fixes #7303. --- .github/workflows/ci.yml | 3 + .../docs/en/reference/api/inbounds.mdx | 17 +- docs/public/openapi.json | 86 +++++ frontend/public/openapi.json | 86 +++++ frontend/src/generated/examples.ts | 8 + frontend/src/generated/schemas.ts | 37 ++ frontend/src/generated/types.ts | 9 + frontend/src/generated/zod.ts | 10 + frontend/src/pages/api-docs/endpoints.ts | 10 + internal/nodee2e/node_snapshot_test.go | 21 +- internal/web/controller/api.go | 1 + internal/web/controller/inbound.go | 10 + internal/web/job/ldap_sync_hung_node_test.go | 2 +- .../web/job/node_traffic_isolation_test.go | 7 +- .../job/periodic_traffic_reset_nodes_test.go | 2 +- internal/web/node_contract_test.go | 76 ++++ internal/web/runtime/reconcile_skip_test.go | 8 + internal/web/runtime/remote.go | 140 +++----- .../web/runtime/remote_inbound_catalog.go | 153 ++++++++ .../runtime/remote_inbound_catalog_test.go | 334 ++++++++++++++++++ .../web/runtime/remote_inbound_lookup_test.go | 6 +- internal/web/runtime/remote_reset_test.go | 7 +- .../service/client_create_reconcile_test.go | 2 +- internal/web/service/inbound.go | 11 + .../service/inbound_node_reconcile_test.go | 42 ++- internal/web/service/node_http_fake_test.go | 4 +- tools/openapigen/main.go | 2 +- 27 files changed, 990 insertions(+), 104 deletions(-) create mode 100644 internal/web/runtime/remote_inbound_catalog.go create mode 100644 internal/web/runtime/remote_inbound_catalog_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f8c2c9d3..73f7498be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,6 +155,9 @@ jobs: exit 1 fi + - name: PostgreSQL inbound catalog scope and projection + run: go test ./internal/web -run '^TestRemoteInboundCatalogScopeAndProjection$' -count=1 -v + - name: PostgreSQL online attribution regressions run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/inbounds.mdx b/docs/content/docs/en/reference/api/inbounds.mdx index 165dc5fd8..3f0d9d5ca 100644 --- a/docs/content/docs/en/reference/api/inbounds.mdx +++ b/docs/content/docs/en/reference/api/inbounds.mdx @@ -29,6 +29,11 @@ _openapi: for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...). url: '#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-' + - depth: 2 + title: List inbound metadata for the authenticated user. Returns id, tag, + remark, listen, protocol, and port for remote ID lookup and + reconciliation. + url: '#list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation' - depth: 2 title: Lightweight picker projection of the authenticated user’s inbounds. Returns id, remark, tag, protocol, port, a server-computed @@ -148,6 +153,10 @@ _openapi: Use this for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...). id: same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow- + - content: List inbound metadata for the authenticated user. Returns id, tag, + remark, listen, protocol, and port for remote ID lookup and + reconciliation. + id: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation - content: Lightweight picker projection of the authenticated user’s inbounds. Returns id, remark, tag, protocol, port, a server-computed tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on @@ -231,7 +240,11 @@ _openapi: decryption. An empty list can remove rules even from an incompatible inbound. Triggers an Xray restart. id: replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-nonempty-lists-require-tcp-with-tlsreality-and-no-active-vless-server-decryption-an-empty-list-can-remove-rules-even-from-an-incompatible-inbound-triggers-an-xray-restart - contents: [] + contents: + - content: Available to panel sessions, admin, node-admin, and node-sync tokens. + The catalog queries only metadata columns. An empty catalog is + returned as an empty array. + heading: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} @@ -241,7 +254,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index afb1a2f6b..870ef99e3 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -5867,6 +5867,43 @@ ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { @@ -7153,6 +7190,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "description": "Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index afb1a2f6b..870ef99e3 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -5867,6 +5867,43 @@ ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { @@ -7153,6 +7190,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "description": "Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 310051ae7..b8e09aa02 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1567,6 +1567,14 @@ export const EXAMPLES: Record = { ], "target": "old.example.com:443" }, + "RemoteInboundOption": { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + }, "ServerSettings": { "contentPaddingAddition": "", "disableCookies": false, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 542b3178d..378fc8b16 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -5841,6 +5841,43 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 62b462e76..4d2bca454 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1318,6 +1318,15 @@ export interface RealityWatchStatus { target: string; } +export interface RemoteInboundOption { + id: number; + listen: string; + port: number; + protocol: Protocol; + remark: string; + tag: string; +} + export interface ServerSettings { contentPaddingAddition?: string; disableCookies: boolean; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index f0a263118..de23c7e02 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1411,6 +1411,16 @@ export const RealityWatchStatusSchema = z.object({ }); export type RealityWatchStatus = z.infer; +export const RemoteInboundOptionSchema = z.object({ + id: z.number().int(), + listen: z.string(), + port: z.number().int(), + protocol: z.lazy(() => ProtocolSchema), + remark: z.string(), + tag: z.string(), +}); +export type RemoteInboundOption = z.infer; + export const ServerSettingsSchema = z.object({ contentPaddingAddition: z.string().optional(), disableCookies: z.boolean(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index a92ac3320..91080469e 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -303,6 +303,16 @@ export const sections: readonly Section[] = [ response: '{\n "success": true,\n "obj": [\n {\n "id": 1,\n "remark": "VLESS-443",\n "settings": {\n "clients": [\n { "email": "alice", "enable": true }\n ],\n "decryption": "none"\n },\n "clientStats": []\n }\n ]\n}', }, + { + method: 'GET', + path: '/panel/api/inbounds/catalog', + summary: + 'List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.', + description: + 'Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.', + responseSchema: 'RemoteInboundOption', + responseSchemaArray: true, + }, { method: 'GET', path: '/panel/api/inbounds/options', diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go index dcdbf55cf..50fdfa891 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -45,7 +45,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { token := node.mintToken("snapshot-link", "node-sync") master.start() node.start() - var lists, compact, full, unchanged, clientAdds atomic.Int32 + var catalogs, lists, compact, full, unchanged, clientAdds atomic.Int32 target, err := url.Parse(node.url()) if err != nil { t.Fatal(err) @@ -90,6 +90,8 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { } front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { switch req.URL.Path { + case "/panel/api/inbounds/catalog": + catalogs.Add(1) case "/panel/api/inbounds/list": lists.Add(1) case "/panel/api/inbounds/trafficSnapshot": @@ -114,10 +116,25 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { t.Fatal(err) } + params := map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true} + if version.master == current { + var options []inboundView + obj := master.call(http.MethodPost, "/panel/api/nodes/inbounds", params) + if err := json.Unmarshal(obj, &options); err != nil || len(options) != 1 || options[0].Id != source.Id { + t.Fatalf("read node options: %s, %v", obj, err) + } + var wantLists int32 + if version.node != current { + wantLists = 1 + } + if got := lists.Swap(0); catalogs.Load() != 1 || got != wantLists { + t.Fatalf("node options used catalog=%d and full list=%d, want 1 and %d", catalogs.Load(), got, wantLists) + } + } if version.master == current { node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil)) } - master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) + master.call(http.MethodPost, "/panel/api/nodes/add", params) eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { ib, ok := master.inboundOnPort(inboundPort) ready := lists.Load() >= 3 diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go index 879b6e930..bbe7fc371 100644 --- a/internal/web/controller/api.go +++ b/internal/web/controller/api.go @@ -114,6 +114,7 @@ var monitorScopeAllow = map[string]struct{}{ var nodeSyncScopeAllow = map[string]map[string]struct{}{ "/server/status": {http.MethodGet: {}}, "/inbounds/list": {http.MethodGet: {}}, + "/inbounds/catalog": {http.MethodGet: {}}, "/inbounds/trafficSnapshot": {http.MethodGet: {}}, "/inbounds/add": {http.MethodPost: {}}, "/inbounds/del/:id": {http.MethodPost: {}}, diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index f89aea5bb..d8354d795 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -84,6 +84,7 @@ func (a *InboundController) initRouter(g *gin.RouterGroup) { g.GET("/trafficSnapshot", a.getTrafficSnapshot) g.GET("/list/slim", a.getInboundsSlim) g.GET("/options", a.getInboundOptions) + g.GET("/catalog", a.getInboundCatalog) g.GET("/allLinks", a.getAllInboundLinks) g.GET("/get/:id", a.getInbound) g.GET("/:id/fallbacks", a.getFallbacks) @@ -152,6 +153,15 @@ func (a *InboundController) getInboundOptions(c *gin.Context) { jsonObj(c, options, nil) } +func (a *InboundController) getInboundCatalog(c *gin.Context) { + options, err := a.inboundService.GetInboundCatalog(session.GetLoginUser(c).Id) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err) + return + } + jsonObj(c, options, nil) +} + // getAmneziaWGKernelReadiness reports whether this host can run an AmneziaWG // inbound on the kernel module, so the form can disable the toggle and say why. func (a *InboundController) getAmneziaWGKernelReadiness(c *gin.Context) { diff --git a/internal/web/job/ldap_sync_hung_node_test.go b/internal/web/job/ldap_sync_hung_node_test.go index 0c9d2c55e..f89ef01f2 100644 --- a/internal/web/job/ldap_sync_hung_node_test.go +++ b/internal/web/job/ldap_sync_hung_node_test.go @@ -29,7 +29,7 @@ func ldapHungNodeInbound(t *testing.T, emails []string) (*resetGate, *model.Inbo srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) w.Header().Set("Content-Type", "application/json") - if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/list") { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/catalog") { _, _ = w.Write([]byte(`{"success":true,"obj":[{"id":1,"tag":"` + tag + `"}]}`)) return } diff --git a/internal/web/job/node_traffic_isolation_test.go b/internal/web/job/node_traffic_isolation_test.go index 68bed06a1..82d74a063 100644 --- a/internal/web/job/node_traffic_isolation_test.go +++ b/internal/web/job/node_traffic_isolation_test.go @@ -39,11 +39,14 @@ func TestNodeTrafficSyncAllowsHealthyNextTickDuringSlowReconcile(t *testing.T) { var slowID int for _, slow := range []bool{true, false} { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + switch { + case slow && strings.HasSuffix(r.URL.Path, "/inbounds/catalog"): slowReconciles.Add(1) slowRequests <- struct{}{} <-release - } else if !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + case slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"): + slowRequests <- struct{}{} + case !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"): fastRequests <- struct{}{} } w.Header().Set("Content-Type", "application/json") diff --git a/internal/web/job/periodic_traffic_reset_nodes_test.go b/internal/web/job/periodic_traffic_reset_nodes_test.go index 18619fd1b..525a220f6 100644 --- a/internal/web/job/periodic_traffic_reset_nodes_test.go +++ b/internal/web/job/periodic_traffic_reset_nodes_test.go @@ -46,7 +46,7 @@ func resetNode(t *testing.T, gate *resetGate, name, inboundTag string) int { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) - if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/list") { + if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/catalog") { w.Header().Set("Content-Type", "application/json") _, _ = fmt.Fprintf(w, `{"success":true,"obj":[{"id":1,"tag":%q}]}`, inboundTag) return diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index f2e13b453..83d7b81ca 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -13,14 +13,17 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" "github.com/robfig/cron/v3" + "gorm.io/gorm" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/util/crypto" "github.com/mhsanaei/3x-ui/v3/internal/web/global" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" @@ -137,6 +140,79 @@ func seedNodeTraffic(t *testing.T, emails ...string) { const contractTag = "in-51001-tcp" +func TestRemoteInboundCatalogScopeAndProjection(t *testing.T) { + cleanup, err := testpg.IsolatePackage("inbound_catalog") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + node := startContractNode(t) + db := database.GetDB() + var user model.User + if err := db.Order("id ASC").First(&user).Error; err != nil { + t.Fatal(err) + } + owned := masterInbound("owned", true, "private") + owned.UserId, owned.Listen = user.Id, "127.0.0.1" + other := masterInbound("different owner", true, "private-other") + other.UserId, other.Port, other.Tag = user.Id+1, 51002, "in-51002-tcp" + if err := db.Create([]*model.Inbound{owned, other}).Error; err != nil { + t.Fatal(err) + } + var reads, wide atomic.Int32 + if err := db.Callback().Query().After("gorm:query").Register("test:catalog_projection", func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + reads.Add(1) + sql := tx.Statement.SQL.String() + if strings.Contains(sql, "*") || strings.Contains(sql, "settings") { + wide.Add(1) + } + } + }); err != nil { + t.Fatal(err) + } + for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeAdmin, model.ApiScopeNodeSync, model.ApiScopeMonitor} { + t.Run(scope, func(t *testing.T) { + node.masterWithToken(t, scope) + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, node.srv.URL+"/panel/api/inbounds/catalog", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer contract-"+scope) + resp, err := node.srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if scope == model.ApiScopeMonitor { + if resp.StatusCode != http.StatusForbidden { + t.Fatalf("monitor catalog status=%d, want forbidden", resp.StatusCode) + } + return + } + var envelope struct { + Success bool + Obj []map[string]any + } + if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK || !envelope.Success || len(envelope.Obj) != 1 { + t.Fatalf("catalog status=%d envelope=%+v", resp.StatusCode, envelope) + } + got := envelope.Obj[0] + if len(got) != 6 || got["id"] != float64(owned.Id) || got["tag"] != owned.Tag || + got["remark"] != owned.Remark || got["listen"] != owned.Listen || + got["protocol"] != string(owned.Protocol) || got["port"] != float64(owned.Port) { + t.Fatalf("unexpected catalog fields: %v", got) + } + }) + } + if reads.Load() != 3 || wide.Load() != 0 { + t.Fatalf("catalog queries = %d, wide queries = %d", reads.Load(), wide.Load()) + } +} + func masterInbound(remark string, enable bool, clients ...string) *model.Inbound { entries := make([]string, 0, len(clients)) for i, email := range clients { diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 8e225320c..42fc4bd1e 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -17,6 +17,11 @@ import ( func TestReconcileInbound_SkipsUnchanged(t *testing.T) { var pushes atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/panel/api/inbounds/add" { + pushes.Add(1) + _, _ = w.Write([]byte(`{"success":true,"obj":{"id":7,"tag":"in-1"}}`)) + return + } if r.Method == http.MethodPost && (strings.Contains(r.URL.Path, "/panel/api/inbounds/update/") || strings.Contains(r.URL.Path, "/panel/api/inbounds/add")) { pushes.Add(1) @@ -109,6 +114,9 @@ func newCountingNodeServer(t *testing.T, clientsResp string) (*httptest.Server, srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch { + case r.URL.Path == "/panel/api/inbounds/catalog": + _, _ = w.Write([]byte(`{"success":true,"obj":[]}`)) + return case strings.Contains(r.URL.Path, "/panel/api/inbounds/add"): counts.adds.Add(1) case strings.Contains(r.URL.Path, "/panel/api/inbounds/update/"): diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index e3e0830fd..cfdf8c9a1 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -94,6 +94,8 @@ type Remote struct { mu sync.RWMutex remoteIDByTag map[string]int adoptedAliases map[string]string + catalogFlight *inboundCatalogFlight + catalogVersion uint64 // pushedFP holds the fingerprint of the last inbound wire payload successfully // pushed, keyed by panel-side tag, so reconcile can skip re-sending an // unchanged inbound. Guarded by mu; dropped with the Remote on node config change. @@ -123,12 +125,12 @@ type Remote struct { } type RemoteInboundOption struct { - Id int `json:"id"` - Tag string `json:"tag"` - Remark string `json:"remark"` - Listen string `json:"listen"` - Protocol model.Protocol `json:"protocol"` - Port int `json:"port"` + Id int `json:"id" example:"7"` + Tag string `json:"tag" example:"in-443"` + Remark string `json:"remark" example:"VLESS-443"` + Listen string `json:"listen" example:"127.0.0.1"` + Protocol model.Protocol `json:"protocol" example:"vless"` + Port int `json:"port" example:"443"` } func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { @@ -190,7 +192,7 @@ func (r *Remote) nodeSupports(ctx context.Context, capability string) (bool, err caps := r.nodeCaps r.mu.RUnlock() if caps == nil { - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, ""); err != nil { return false, err } r.mu.RLock() @@ -444,7 +446,7 @@ func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) { if id, ok := r.cacheGetTag(tag); ok { return id, nil } - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, tag); err != nil { return 0, err } if id, ok := r.cacheGetTag(tag); ok { @@ -478,24 +480,32 @@ func (r *Remote) cacheGetTag(tag string) (int, bool) { return r.cachedTagID(tag) } +// cachedTagID requires r.mu to be held. func (r *Remote) cachedTagID(tag string) (int, bool) { - if id, ok := r.remoteIDByTag[tag]; ok { + return lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)) +} + +func lookupRemoteTag(ids map[string]int, tag, prefix string) (int, bool) { + if id, ok := ids[tag]; ok { return id, true } - prefix := nodeInboundTagPrefix(r.node.Id) if stripped, found := strings.CutPrefix(tag, prefix); found { - tag = stripped - } else { - tag = prefix + tag + id, ok := ids[stripped] + return id, ok } - id, ok := r.remoteIDByTag[tag] + id, ok := ids[prefix+tag] return id, ok } func (r *Remote) cacheSet(tag string, id int) { r.mu.Lock() defer r.mu.Unlock() + previous, known := r.cachedTagID(tag) r.remoteIDByTag[tag] = id + // Settings-only pushes do not supersede the catalog's ID mapping. + if !known || previous != id { + r.catalogVersion++ + } } func (r *Remote) cacheDel(tag string) { @@ -503,19 +513,11 @@ func (r *Remote) cacheDel(tag string) { defer r.mu.Unlock() delete(r.remoteIDByTag, tag) delete(r.pushedFP, tag) -} - -// forgetTag drops every tag form cacheGetTag would match, once the node reports -// none of them, so the next resolve re-reads the node instead of a deleted id. -func (r *Remote) forgetTag(tag string) { - prefix := nodeInboundTagPrefix(r.node.Id) - bare := strings.TrimPrefix(tag, prefix) - r.cacheDel(bare) - r.cacheDel(prefix + bare) + r.catalogVersion++ } func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) { - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, ""); err != nil { return nil, err } r.mu.RLock() @@ -528,52 +530,8 @@ func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) { } func (r *Remote) ListInboundOptions(ctx context.Context) ([]RemoteInboundOption, error) { - env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) - if err != nil { - return nil, err - } - list, err := json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds) - if err != nil { - return nil, fmt.Errorf("decode inbound list: %w", err) - } - return list, nil -} - -func (r *Remote) refreshRemoteIDs(ctx context.Context) error { - env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) - if err != nil { - return err - } - list, err := json_util.DecodeCappedList[struct { - Id int `json:"id"` - Tag string `json:"tag"` - }](env.Obj, maxNodeInbounds) - if err != nil { - return fmt.Errorf("decode inbound list: %w", err) - } - next := make(map[string]int, len(list)) - for _, ib := range list { - if ib.Tag == "" { - continue - } - next[ib.Tag] = ib.Id - } - r.mu.Lock() - // A rebuild sees only node-reported tags, so the adopted aliases must be - // re-applied or a later op on an adopted inbound re-creates it as a duplicate. - for centralTag, nodeTag := range r.adoptedAliases { - // A tag the node reports itself is authoritative; the alias only fills - // the gap left for a central tag the node knows under another name. - if _, reported := next[centralTag]; reported { - continue - } - if id, ok := next[nodeTag]; ok { - next[centralTag] = id - } - } - r.remoteIDByTag = next - r.mu.Unlock() - return nil + list, err := r.loadInboundCatalog(ctx, "") + return slices.Clone(list), err } func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error { @@ -652,16 +610,17 @@ func (r *Remote) SetInboundSubSortIndex(ctx context.Context, ib *model.Inbound, // whether a push actually happened. This turns a full-fleet reconcile from "send // every inbound's full settings" into "send only what changed". func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, existsOnNode bool) (bool, error) { + if !existsOnNode { + r.ForgetInbound(ib.Tag) + err := r.AddInbound(ctx, ib) + return err == nil, err + } fp := wireFingerprint(wireInbound(ib, r.node.Id)) - if existsOnNode { - r.mu.RLock() - prev, ok := r.pushedFP[ib.Tag] - r.mu.RUnlock() - if ok && prev.fingerprint == fp { - return false, nil - } - } else { - r.forgetTag(ib.Tag) + r.mu.RLock() + prev, ok := r.pushedFP[ib.Tag] + r.mu.RUnlock() + if ok && prev.fingerprint == fp { + return false, nil } if err := r.UpdateInbound(ctx, ib, ib); err != nil { return false, err @@ -702,14 +661,22 @@ func (r *Remote) ForgetInbound(tag string) { bare := strings.TrimPrefix(tag, prefix) r.mu.Lock() defer r.mu.Unlock() - for _, t := range []string{bare, prefix + bare} { - if alias, ok := r.adoptedAliases[t]; ok { - delete(r.remoteIDByTag, alias) - delete(r.adoptedAliases, t) + forget := func(t string) { + t = strings.TrimPrefix(t, prefix) + for _, form := range []string{t, prefix + t} { + delete(r.remoteIDByTag, form) + delete(r.pushedFP, form) } - delete(r.remoteIDByTag, t) - delete(r.pushedFP, t) } + for central, nodeTag := range r.adoptedAliases { + if strings.TrimPrefix(central, prefix) == bare || strings.TrimPrefix(nodeTag, prefix) == bare { + forget(central) + forget(nodeTag) + delete(r.adoptedAliases, central) + } + } + forget(bare) + r.catalogVersion++ } // AdoptInboundAlias records a deployed alias without mutating either panel. @@ -720,6 +687,7 @@ func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption r.remoteIDByTag[remote.Tag] = remote.Id r.remoteIDByTag[ib.Tag] = remote.Id r.adoptedAliases[ib.Tag] = remote.Tag + r.catalogVersion++ r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -831,7 +799,7 @@ func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json. var refreshErr error for _, tag := range tags { if id, ok := r.cacheGetTag(tag); !ok || id <= 0 { - refreshErr = r.refreshRemoteIDs(ctx) + _, refreshErr = r.loadInboundCatalog(ctx, "") break } } diff --git a/internal/web/runtime/remote_inbound_catalog.go b/internal/web/runtime/remote_inbound_catalog.go new file mode 100644 index 000000000..5531cc031 --- /dev/null +++ b/internal/web/runtime/remote_inbound_catalog.go @@ -0,0 +1,153 @@ +package runtime + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + + "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" +) + +type inboundCatalogFlight struct { + done chan struct{} + cancel context.CancelFunc + waiters int + options []RemoteInboundOption + err error +} + +// loadInboundCatalog shares a refresh across callers. A lookup rechecks its cache +// under the same lock used to register the flight. +func (r *Remote) loadInboundCatalog(ctx context.Context, tag string) ([]RemoteInboundOption, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.Lock() + if tag != "" { + if _, ok := lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)); ok { + r.mu.Unlock() + return nil, nil + } + } + flight := r.catalogFlight + if flight == nil { + // The RPC belongs to the group. Each caller waits on its own context. + requestCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), remoteHTTPTimeout) + flight = &inboundCatalogFlight{done: make(chan struct{}), cancel: cancel} + r.catalogFlight = flight + go r.refreshInboundCatalog(requestCtx, flight, r.catalogVersion) + } + flight.waiters++ + r.mu.Unlock() + + select { + case <-flight.done: + if err := ctx.Err(); err != nil { + return nil, err + } + return flight.options, flight.err + case <-ctx.Done(): + r.mu.Lock() + flight.waiters-- + if r.catalogFlight == flight && flight.waiters == 0 { + r.catalogFlight = nil + flight.cancel() + } + r.mu.Unlock() + return nil, ctx.Err() + } +} + +func (r *Remote) refreshInboundCatalog(ctx context.Context, flight *inboundCatalogFlight, version uint64) { + defer flight.cancel() + defer close(flight.done) + for attempt := 0; ; attempt++ { + options, ids, err := r.fetchInboundCatalog(ctx) + r.mu.Lock() + if r.catalogFlight != flight { + r.mu.Unlock() + return + } + if err == nil && version != r.catalogVersion { + // An inbound mutation completed during the read. Retry once within + // the same budget, so a stale response cannot revive an old ID. + if attempt == 0 { + version = r.catalogVersion + r.mu.Unlock() + continue + } + err = errors.New("remote inbound catalog changed during refresh") + } + if err == nil { + r.installInboundCatalog(ids) + flight.options = options + } + flight.err = err + r.catalogFlight = nil + r.mu.Unlock() + return + } +} + +func (r *Remote) fetchInboundCatalog(ctx context.Context) (list []RemoteInboundOption, ids map[string]int, err error) { + // Fetching runs on the shared worker, outside each caller's panic boundary. + defer func() { + if cause := recover(); cause != nil { + list, ids, err = nil, nil, fmt.Errorf("fetch inbound catalog: panic: %v", cause) + } + }() + env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/catalog", nil) + var status *remoteHTTPError + legacy := errors.As(err, &status) && (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed) + if legacy { + env, err = r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) + } + if err != nil { + return nil, nil, err + } + if !legacy && !bytes.HasPrefix(bytes.TrimSpace(env.Obj), []byte("[")) { + return nil, nil, errors.New("decode inbound list: catalog must be an array") + } + list, err = json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds) + if err != nil { + return nil, nil, fmt.Errorf("decode inbound list: %w", err) + } + ids = make(map[string]int, len(list)) + for _, ib := range list { + if ib.Id <= 0 || ib.Tag == "" { + return nil, nil, errors.New("decode inbound list: entry missing a valid ID or tag") + } + if _, exists := ids[ib.Tag]; exists { + return nil, nil, errors.New("decode inbound list: duplicate tag") + } + ids[ib.Tag] = ib.Id + } + return list, ids, nil +} + +// installInboundCatalog runs with mu held. Explicit node tags outrank inferred aliases. +func (r *Remote) installInboundCatalog(ids map[string]int) { + prefix := nodeInboundTagPrefix(r.node.Id) + aliases := make(map[string]int, len(r.adoptedAliases)) + for central, nodeTag := range r.adoptedAliases { + if _, exists := lookupRemoteTag(ids, central, prefix); exists { + continue + } + if id, ok := lookupRemoteTag(ids, nodeTag, prefix); ok { + aliases[central] = id + } + } + for tag, id := range aliases { + ids[tag] = id + } + for tag := range r.pushedFP { + oldID, known := lookupRemoteTag(r.remoteIDByTag, tag, prefix) + nextID, present := lookupRemoteTag(ids, tag, prefix) + if !present || known && nextID != oldID { + delete(r.pushedFP, tag) + } + } + r.remoteIDByTag = ids +} diff --git a/internal/web/runtime/remote_inbound_catalog_test.go b/internal/web/runtime/remote_inbound_catalog_test.go new file mode 100644 index 000000000..b34e01edd --- /dev/null +++ b/internal/web/runtime/remote_inbound_catalog_test.go @@ -0,0 +1,334 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type observedCatalogContext struct { + context.Context + waiting chan struct{} + once sync.Once +} + +func (ctx *observedCatalogContext) Done() <-chan struct{} { + ctx.once.Do(func() { close(ctx.waiting) }) + return ctx.Context.Done() +} + +func TestRemoteInboundCatalogCoalescesMissesAcrossCallerCancellation(t *testing.T) { + var modern, legacy atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var first, cleanup sync.Once + unblock := func() { cleanup.Do(func() { close(release) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + modern.Add(1) + case "/panel/api/inbounds/list": + legacy.Add(1) + default: + http.NotFound(w, req) + return + } + first.Do(func() { close(started) }) + select { + case <-release: + fmt.Fprint(w, `{"success":true,"obj":[{"id":43,"tag":"in-443"}]}`) + case <-req.Context().Done(): + } + })) + t.Cleanup(srv.Close) + t.Cleanup(unblock) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx, finish := context.WithTimeout(context.Background(), 4*time.Second) + defer finish() + leaderCtx, cancel := context.WithCancel(ctx) + defer cancel() + leader := make(chan error, 1) + go func() { + _, err := r.resolveRemoteID(leaderCtx, "in-443") + leader <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog request never started") + } + const followers = 6 + results := make(chan error, followers) + tag := fmt.Sprintf("n%d-in-443", r.node.Id) + for range followers { + waiter := &observedCatalogContext{Context: ctx, waiting: make(chan struct{})} + go func() { + id, err := r.resolveRemoteID(waiter, tag) + if err == nil && id != 43 { + err = fmt.Errorf("resolved ID = %d, want 43", id) + } + results <- err + }() + select { + case <-waiter.waiting: + case <-ctx.Done(): + t.Fatal("follower did not join the lookup") + } + } + cancel() + select { + case err := <-leader: + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled caller got %v", err) + } + case <-ctx.Done(): + t.Fatal("canceled caller still waits on the catalog") + } + unblock() + for range followers { + select { + case err := <-results: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("follower never received the catalog") + } + } + if id, err := r.resolveRemoteID(ctx, tag); err != nil || id != 43 { + t.Fatalf("warm cache = (%d, %v), want 43", id, err) + } + if modern.Load() != 1 || legacy.Load() != 0 { + t.Fatalf("catalog requests = %d, full list requests = %d; want 1 and 0", modern.Load(), legacy.Load()) + } +} + +func TestRemoteInboundCatalogLegacyFallbackSeedsCache(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} { + t.Run(http.StatusText(status), func(t *testing.T) { + var modern, legacy atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + modern.Add(1) + w.WriteHeader(status) + case "/panel/api/inbounds/list": + legacy.Add(1) + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"test","port":443,"settings":"large"}]}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx := context.Background() + options, err := r.ListInboundOptions(ctx) + if err != nil || len(options) != 1 || options[0].Port != 443 { + t.Fatalf("legacy options=%+v err=%v", options, err) + } + if id, err := r.resolveRemoteID(ctx, "test"); err != nil || id != 7 { + t.Fatalf("legacy ID = %d, err=%v", id, err) + } + if modern.Load() != 1 || legacy.Load() != 1 { + t.Fatalf("catalog requests=%d full list requests=%d, want 1 each", modern.Load(), legacy.Load()) + } + }) + } +} + +func TestRemoteInboundCatalogSurvivesSettingsOnlyPushes(t *testing.T) { + var reads atomic.Int32 + started := make(chan chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + reads.Add(1) + resume := make(chan struct{}) + select { + case started <- resume: + case <-req.Context().Done(): + return + } + select { + case <-resume: + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"warm"},{"id":8,"tag":"cold"}]}`) + case <-req.Context().Done(): + } + case "/panel/api/inbounds/update/7": + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + r.cacheSet("warm", 7) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + id, err := r.resolveRemoteID(ctx, "cold") + if err == nil && id != 8 { + err = fmt.Errorf("cold lookup resolved ID %d, want 8", id) + } + done <- err + }() + + for { + select { + case resume := <-started: + before := &model.Inbound{Tag: "warm", Protocol: model.VLESS, Settings: `{"clients":[]}`} + after := *before + after.Settings = fmt.Sprintf(`{"clients":[{"email":"client-%d@example.test"}]}`, reads.Load()) + err := r.UpdateInbound(ctx, before, &after) + close(resume) + if err != nil { + t.Fatal(err) + } + case err := <-done: + if err != nil || reads.Load() != 1 { + t.Fatalf("lookup during settings-only updates: reads=%d, err=%v", reads.Load(), err) + } + return + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } +} + +func TestRemoteInboundCatalogDoesNotRestoreDeletedAlias(t *testing.T) { + var gets atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list": + if gets.Add(1) == 1 { + close(started) + <-release + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"adopted"}]}`) + } else { + fmt.Fprint(w, `{"success":true,"obj":[]}`) + } + case "/panel/api/inbounds/del/7": + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + t.Cleanup(unblock) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ib := &model.Inbound{Tag: "central", Protocol: model.VLESS} + r.AdoptInboundAlias(ib, RemoteInboundOption{Id: 7, Tag: "adopted"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + options, err := r.ListInboundOptions(ctx) + if err == nil && len(options) != 0 { + err = fmt.Errorf("stale catalog returned: %+v", options) + } + done <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog never started") + } + if err := r.DelInbound(ctx, &model.Inbound{Tag: "adopted"}); err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + if _, ok := r.cacheGetTag(ib.Tag); ok || gets.Load() != 2 { + t.Fatalf("deleted alias still cached or stale read was not retried: gets=%d", gets.Load()) + } +} + +func TestRemoteInboundCatalogRefreshDetectsRecreatedInbound(t *testing.T) { + var remoteID, pushedID atomic.Int32 + remoteID.Store(7) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + fmt.Fprintf(w, `{"success":true,"obj":[{"id":%d,"tag":"in-443"}]}`, remoteID.Load()) + case "/panel/api/inbounds/update/7": + pushedID.Store(7) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/update/8": + pushedID.Store(8) + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ib := &model.Inbound{Tag: "in-443", Protocol: model.VLESS, Port: 443} + ctx := context.Background() + if err := r.UpdateInbound(ctx, ib, ib); err != nil || pushedID.Load() != 7 { + t.Fatalf("first update used ID %d, err=%v", pushedID.Load(), err) + } + remoteID.Store(8) + if _, err := r.ListInboundOptions(ctx); err != nil { + t.Fatal(err) + } + if pushed, err := r.ReconcileInbound(ctx, ib, true); err != nil || !pushed || pushedID.Load() != 8 { + t.Fatalf("reconcile after recreation: pushed=%t, ID=%d, err=%v", pushed, pushedID.Load(), err) + } +} + +func TestRemoteInboundCatalogCancelsRPCWhenLastWaiterLeaves(t *testing.T) { + var calls atomic.Int32 + started, canceled := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if calls.Add(1) == 1 { + close(started) + <-req.Context().Done() + close(canceled) + return + } + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"valid"}]}`) + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx, finish := context.WithTimeout(context.Background(), 3*time.Second) + defer finish() + lookup, cancel := context.WithCancel(ctx) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := r.resolveRemoteID(lookup, "valid") + done <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog never started") + } + cancel() + if err := <-done; !errors.Is(err, context.Canceled) { + t.Fatalf("lookup error=%v, want canceled", err) + } + select { + case <-canceled: + case <-ctx.Done(): + t.Fatal("abandoned catalog request was not canceled") + } + if id, err := r.resolveRemoteID(ctx, "valid"); err != nil || id != 7 || calls.Load() != 2 { + t.Fatalf("fresh lookup ID=%d err=%v calls=%d", id, err, calls.Load()) + } +} diff --git a/internal/web/runtime/remote_inbound_lookup_test.go b/internal/web/runtime/remote_inbound_lookup_test.go index a0504029b..05441f24f 100644 --- a/internal/web/runtime/remote_inbound_lookup_test.go +++ b/internal/web/runtime/remote_inbound_lookup_test.go @@ -23,11 +23,13 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) { {"unavailable", http.StatusServiceUnavailable, "", "HTTP 503"}, {"application error", http.StatusOK, `{"success":false,"msg":"node database unavailable"}`, "node database unavailable"}, {"invalid catalog", http.StatusOK, `{"success":true,"obj":{"id":4}}`, "decode inbound list"}, + {"missing catalog", http.StatusOK, `{"success":true}`, "decode inbound list"}, + {"invalid row", http.StatusOK, `{"success":true,"obj":[{"id":0,"tag":"in-lookup"}]}`, "decode inbound list"}, } { t.Run(tc.name, func(t *testing.T) { var mutations atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/list") { + if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/catalog") { mutations.Add(1) _, _ = w.Write([]byte(`{"success":true}`)) return @@ -45,7 +47,7 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) { t.Errorf("UpdateInbound error = %v, want %q", err, tc.want) } if got := mutations.Load(); got != 0 { - t.Errorf("mutation requests after failed lookup = %d, want 0", got) + t.Errorf("mutation or fallback requests after failed lookup = %d, want 0", got) } }) } diff --git a/internal/web/runtime/remote_reset_test.go b/internal/web/runtime/remote_reset_test.go index 27159e3e6..722d29bff 100644 --- a/internal/web/runtime/remote_reset_test.go +++ b/internal/web/runtime/remote_reset_test.go @@ -3,6 +3,7 @@ package runtime import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "slices" @@ -62,7 +63,7 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) { var resetPosted bool srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") - if req.URL.Path == "/panel/api/inbounds/list" { + if req.URL.Path == "/panel/api/inbounds/catalog" { _, _ = w.Write([]byte(`{"success":true,"msg":"ok","obj":[]}`)) return } @@ -73,8 +74,8 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) { r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) ib := &model.Inbound{Id: 42, Tag: "n1-in-443"} - if err := r.ResetInboundTraffic(context.Background(), ib); err == nil { - t.Fatal("ResetInboundTraffic error = nil, want unknown-tag error") + if err := r.ResetInboundTraffic(context.Background(), ib); !errors.Is(err, errRemoteInboundNotFound) { + t.Fatalf("ResetInboundTraffic error = %v, want unknown-tag error", err) } if resetPosted { t.Fatal("reset request posted to node despite an unresolved tag") diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go index 87f435e46..e56e722fc 100644 --- a/internal/web/service/client_create_reconcile_test.go +++ b/internal/web/service/client_create_reconcile_test.go @@ -33,7 +33,7 @@ type groupedCreatePeer struct { func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch { - case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + case strings.HasSuffix(r.URL.Path, "/inbounds/catalog"), strings.HasSuffix(r.URL.Path, "/inbounds/list"): p.mu.Lock() catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags)) for tag, id := range p.tags { diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 59bc2cabe..03fe9cd14 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -400,6 +400,17 @@ type InboundOption struct { ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"` } +// GetInboundCatalog selects the fields needed for remote inbound lookup and reconciliation. +func (s *InboundService) GetInboundCatalog(userID int) ([]runtime.RemoteInboundOption, error) { + catalog := make([]runtime.RemoteInboundOption, 0) + err := database.GetDB().Model(&model.Inbound{}). + Select("id", "tag", "remark", "listen", "protocol", "port"). + Where("user_id = ?", userID). + Order("id ASC"). + Find(&catalog).Error + return catalog, err +} + func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) { db := database.GetDB() var rows []struct { diff --git a/internal/web/service/inbound_node_reconcile_test.go b/internal/web/service/inbound_node_reconcile_test.go index 2075f1fc1..0e62543da 100644 --- a/internal/web/service/inbound_node_reconcile_test.go +++ b/internal/web/service/inbound_node_reconcile_test.go @@ -12,6 +12,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "github.com/mhsanaei/3x-ui/v3/internal/database" @@ -263,7 +264,7 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "msg": "", "obj": obj}) } mux := http.NewServeMux() - mux.HandleFunc("/panel/api/inbounds/list", func(w http.ResponseWriter, _ *http.Request) { + mux.HandleFunc("/panel/api/inbounds/catalog", func(w http.ResponseWriter, _ *http.Request) { writeOK(w, []map[string]any{{"id": 41, "tag": "already-deployed", "listen": "", "port": 8443, "protocol": "vless"}}) }) mux.HandleFunc("/panel/api/inbounds/", func(w http.ResponseWriter, _ *http.Request) { @@ -301,6 +302,45 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes } } +func TestReconcileNodeUsesOneCatalogForUpdatesCreatesAndDeletes(t *testing.T) { + setupConflictDB(t) + var reads, fullLists, adds, updates, deletes atomic.Int32 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list": + if req.URL.Path == "/panel/api/inbounds/catalog" { + reads.Add(1) + } else { + fullLists.Add(1) + } + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"existing"},{"id":6,"tag":"removed"}]}`) + case "/panel/api/inbounds/add": + adds.Add(1) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/update/7": + updates.Add(1) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/del/6": + deletes.Add(1) + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(ts.Close) + node := reconcileTestNode(t, ts, "catalog-node", "all", nil) + for i, tag := range []string{"existing", "missing-a", "missing-b"} { + seedInboundConflictNode(t, tag, "", 12000+i, model.VLESS, `{"network":"tcp"}`, `{"clients":[]}`, &node.Id) + } + svc := InboundService{} + if err := svc.ReconcileNode(context.Background(), runtime.NewRemote(node, nil), node); err != nil { + t.Fatal(err) + } + if reads.Load() != 1 || fullLists.Load() != 0 || adds.Load() != 2 || updates.Load() != 1 || deletes.Load() != 1 { + t.Fatalf("catalog=%d full list=%d adds=%d updates=%d deletes=%d", reads.Load(), fullLists.Load(), adds.Load(), updates.Load(), deletes.Load()) + } +} + func TestReconcileNode_AmbiguousCompatibleInboundsAreNotSwept(t *testing.T) { setupConflictDB(t) diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index aaf21b930..aaf1655b4 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -27,7 +27,7 @@ type fakeNodeHTTP struct { pendingClientAcks int clientAdds []ClientCreatePayload clientAddEvents chan ClientCreatePayload - // hold makes every non-list request block until the master gives up. + // hold makes requests outside inbound discovery block until the master gives up. hold bool release chan struct{} } @@ -43,7 +43,7 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { f.mu.Lock() w.Header().Set(wirecodec.CapsHeader, f.caps) f.mu.Unlock() - if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + if strings.HasSuffix(r.URL.Path, "/inbounds/catalog") || strings.HasSuffix(r.URL.Path, "/inbounds/list") { f.mu.Lock() f.hits["list"]++ type ent struct { diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 2633d92c0..04362843f 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -97,7 +97,7 @@ func run(root, outDir string) error { }, { Path: resolveRel(root, "internal/web/runtime"), - StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1"), + StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1", "RemoteInboundOption"), }, { Path: resolveRel(root, "internal/web/service"), From ef99e67507e9d5b8b588fa0a8488e2ea546a321f Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 04:19:48 +0330 Subject: [PATCH 11/33] feat(nodes): add fleet monitoring and implement the Penpot layout (#7342) Expose sampled CPU topology, absolute RAM, TCP/UDP counts, load averages and network throughput through the existing heartbeat and descendant contracts, preserving measured zero versus unavailable values. Add an explicit nullable telemetry migration and freshness/availability checks. Provide read-only All nodes and Master rows with deduplicated host/client totals, grouped SQL aggregation and reporting coverage. Preserve known descendants during parent outages and prefer the freshest valid observation of shared GUIDs. Keep the ordinary heartbeat broadcast free of fleet-wide totals. Implement the approved compact Penpot-inspired Nodes layout, responsive stacked details, status diagnostics and existing remote actions. Preserve cached rows, search and controls on overview refresh failures. By maintainer decision, hide both system rows when no remote nodes are registered. Final review of 44ed4579856020f7bfebb42fc522de4d6c2b8ca4: no outstanding HIGH or MEDIUM findings. CI and Docs CI passed (13 jobs; 2342 frontend tests in 269 files), including Go/race and mixed-version node E2E. Feature-specific PostgreSQL regression execution was not independently verified in the selected CI logs. See https://github.com/MHSanaei/3x-ui/pull/7342#issuecomment-7363599190. Closes #7335 Closes #7336 Closes #7337 --- docs/content/docs/en/reference/api/nodes.mdx | 9 +- docs/public/openapi.json | 288 +++ frontend/public/openapi.json | 288 +++ frontend/src/api/queries/useNodesQuery.ts | 29 +- frontend/src/api/queryKeys.ts | 1 + frontend/src/generated/examples.ts | 73 + frontend/src/generated/schemas.ts | 220 +++ frontend/src/generated/types.ts | 47 + frontend/src/generated/zod.ts | 51 + frontend/src/pages/api-docs/endpoints.ts | 7 + frontend/src/pages/nodes/NodeList.css | 776 ++++++-- frontend/src/pages/nodes/NodeList.stories.tsx | 169 ++ frontend/src/pages/nodes/NodeList.tsx | 1632 +++++++++-------- frontend/src/pages/nodes/NodeNetworkSpeed.tsx | 72 +- frontend/src/pages/nodes/NodesPage.tsx | 118 +- frontend/src/pages/nodes/fleetTelemetry.ts | 103 ++ frontend/src/pages/nodes/fonts/LICENSE.txt | 93 + .../nodes/fonts/SourceSansPro-Bold.woff2 | Bin 0 -> 76860 bytes .../nodes/fonts/SourceSansPro-Regular.woff2 | Bin 0 -> 62636 bytes .../nodes/fonts/SourceSansPro-Semibold.woff2 | Bin 0 -> 77452 bytes frontend/src/schemas/node.ts | 7 + .../src/test/node-fleet-monitoring.test.tsx | 125 ++ frontend/src/test/node-list-a11y.test.tsx | 9 +- .../src/test/node-list-online-total.test.tsx | 18 +- frontend/src/test/node-list-rerender.test.tsx | 1 - frontend/src/test/node-list-rowkey.test.tsx | 1 - .../test/node-list-untrusted-i18n.test.tsx | 1 - .../test/node-metrics-availability.test.tsx | 141 +- .../src/test/node-overview-refresh.test.tsx | 47 + frontend/src/test/node-restart.test.tsx | 131 +- internal/database/db.go | 12 + internal/database/model/model.go | 16 +- internal/database/model/node_telemetry.go | 22 + .../database/node_telemetry_migration_test.go | 42 + internal/web/controller/api.go | 5 + internal/web/controller/node.go | 11 + internal/web/controller/server.go | 4 +- .../job/node_heartbeat_descendants_test.go | 65 +- internal/web/job/node_heartbeat_job.go | 14 +- internal/web/service/node.go | 196 +- internal/web/service/node_contract.go | 91 +- internal/web/service/node_fleet.go | 162 ++ internal/web/service/node_fleet_test.go | 343 ++++ internal/web/service/node_shared_guid_test.go | 4 +- internal/web/service/node_telemetry.go | 123 ++ internal/web/service/node_tree.go | 209 +-- internal/web/service/server.go | 13 +- internal/web/service/server_scope_test.go | 4 +- internal/web/translation/ar-EG.json | 37 +- internal/web/translation/en-US.json | 37 +- internal/web/translation/es-ES.json | 37 +- internal/web/translation/fa-IR.json | 37 +- internal/web/translation/id-ID.json | 37 +- internal/web/translation/ja-JP.json | 37 +- internal/web/translation/pt-BR.json | 37 +- internal/web/translation/ru-RU.json | 37 +- internal/web/translation/sk-SK.json | 37 +- internal/web/translation/tr-TR.json | 37 +- internal/web/translation/uk-UA.json | 37 +- internal/web/translation/vi-VN.json | 37 +- internal/web/translation/zh-CN.json | 37 +- internal/web/translation/zh-TW.json | 37 +- internal/web/web.go | 3 +- tools/openapigen/main.go | 4 + 64 files changed, 4710 insertions(+), 1608 deletions(-) create mode 100644 frontend/src/pages/nodes/NodeList.stories.tsx create mode 100644 frontend/src/pages/nodes/fleetTelemetry.ts create mode 100644 frontend/src/pages/nodes/fonts/LICENSE.txt create mode 100644 frontend/src/pages/nodes/fonts/SourceSansPro-Bold.woff2 create mode 100644 frontend/src/pages/nodes/fonts/SourceSansPro-Regular.woff2 create mode 100644 frontend/src/pages/nodes/fonts/SourceSansPro-Semibold.woff2 create mode 100644 frontend/src/test/node-fleet-monitoring.test.tsx create mode 100644 frontend/src/test/node-overview-refresh.test.tsx create mode 100644 internal/database/model/node_telemetry.go create mode 100644 internal/database/node_telemetry_migration_test.go create mode 100644 internal/web/service/node_fleet.go create mode 100644 internal/web/service/node_fleet_test.go create mode 100644 internal/web/service/node_telemetry.go diff --git a/docs/content/docs/en/reference/api/nodes.mdx b/docs/content/docs/en/reference/api/nodes.mdx index fb6e627e3..afc8cc506 100644 --- a/docs/content/docs/en/reference/api/nodes.mdx +++ b/docs/content/docs/en/reference/api/nodes.mdx @@ -11,6 +11,10 @@ _openapi: title: List every configured node with its connection details, health, and last heartbeat patch. url: '#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch' + - depth: 2 + title: Read the local panel, unique fleet client counts and sampled remote host + telemetry. + url: '#read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry' - depth: 2 title: This panel's node-auth CA certificate (public, PEM) to paste into a node's mTLS trust setting. Lazily mints the CA and the master client @@ -99,6 +103,9 @@ _openapi: - content: List every configured node with its connection details, health, and last heartbeat patch. id: list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch + - content: Read the local panel, unique fleet client counts and sampled remote + host telemetry. + id: read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry - content: This panel's node-auth CA certificate (public, PEM) to paste into a node's mTLS trust setting. Lazily mints the CA and the master client cert on first call. Pair with setting tlsVerifyMode=mtls on the node. @@ -175,7 +182,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 870ef99e3..6774178eb 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -4755,6 +4755,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4916,6 +4924,43 @@ ], "type": "object" }, + "NodeFleetCounts": { + "properties": { + "activeCount": { + "example": 90, + "type": "integer" + }, + "clientCount": { + "example": 100, + "type": "integer" + }, + "depletedCount": { + "example": 2, + "type": "integer" + }, + "disabledCount": { + "example": 8, + "type": "integer" + }, + "inboundCount": { + "example": 8, + "type": "integer" + }, + "onlineCount": { + "example": 20, + "type": "integer" + } + }, + "required": [ + "activeCount", + "clientCount", + "depletedCount", + "disabledCount", + "inboundCount", + "onlineCount" + ], + "type": "object" + }, "NodeInboundTraffic": { "properties": { "down": { @@ -4938,6 +4983,40 @@ ], "type": "object" }, + "NodeMasterView": { + "properties": { + "counts": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "panelVersion": { + "example": "v3.12.0", + "type": "string" + }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, + "xrayError": { + "type": "string" + }, + "xrayState": { + "example": "running", + "type": "string" + }, + "xrayVersion": { + "example": "26.1.1", + "type": "string" + } + }, + "required": [ + "counts" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -5028,6 +5107,33 @@ ], "type": "object" }, + "NodeOverview": { + "properties": { + "fleet": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "master": { + "$ref": "#/components/schemas/NodeMasterView" + }, + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeView" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "fleet", + "master", + "nodes" + ], + "type": "object" + }, "NodeSnapshotAttachment": { "properties": { "email": { @@ -5071,6 +5177,106 @@ ], "type": "object" }, + "NodeTelemetry": { + "description": "NodeTelemetry describes one host sample. Nil metrics were not measured.", + "properties": { + "cpuPct": { + "example": 12.5, + "nullable": true, + "type": "number" + }, + "load1": { + "example": 0.25, + "nullable": true, + "type": "number" + }, + "load15": { + "example": 0.12, + "nullable": true, + "type": "number" + }, + "load5": { + "example": 0.18, + "nullable": true, + "type": "number" + }, + "logicalCores": { + "example": 8, + "nullable": true, + "type": "integer" + }, + "memAvailableBytes": { + "example": 1073741824, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memTotalBytes": { + "example": 4294967296, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memUsedBytes": { + "example": 2147483648, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netDown": { + "example": 2048, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netUp": { + "example": 1024, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "physicalCores": { + "example": 4, + "nullable": true, + "type": "integer" + }, + "resourceScope": { + "example": "container", + "type": "string" + }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "sampledAt": { + "example": 1700000000000, + "format": "int64", + "type": "integer" + }, + "tcpCount": { + "example": 75, + "nullable": true, + "type": "integer" + }, + "udpCount": { + "example": 12, + "nullable": true, + "type": "integer" + }, + "uptimeSecs": { + "example": 3600, + "format": "int64", + "nullable": true, + "type": "integer" + } + }, + "required": [ + "sampledAt" + ], + "type": "object" + }, "NodeTrafficSnapshotV1": { "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", "properties": { @@ -5302,6 +5508,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -6205,6 +6419,12 @@ "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" @@ -8270,6 +8490,7 @@ "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, @@ -14490,6 +14711,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14509,6 +14731,69 @@ } } }, + "/panel/api/nodes/overview": { + "get": { + "tags": [ + "Nodes" + ], + "summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.", + "operationId": "get_panel_api_nodes_overview", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeOverview" + } + } + }, + "example": { + "success": true, + "obj": { + "fleet": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "master": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, + "nodes": [ + null + ] + } + } + } + } + } + } + } + }, "/panel/api/nodes/mtls/ca": { "post": { "tags": [ @@ -14696,6 +14981,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14851,6 +15137,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -20654,6 +20941,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 870ef99e3..6774178eb 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -4755,6 +4755,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4916,6 +4924,43 @@ ], "type": "object" }, + "NodeFleetCounts": { + "properties": { + "activeCount": { + "example": 90, + "type": "integer" + }, + "clientCount": { + "example": 100, + "type": "integer" + }, + "depletedCount": { + "example": 2, + "type": "integer" + }, + "disabledCount": { + "example": 8, + "type": "integer" + }, + "inboundCount": { + "example": 8, + "type": "integer" + }, + "onlineCount": { + "example": 20, + "type": "integer" + } + }, + "required": [ + "activeCount", + "clientCount", + "depletedCount", + "disabledCount", + "inboundCount", + "onlineCount" + ], + "type": "object" + }, "NodeInboundTraffic": { "properties": { "down": { @@ -4938,6 +4983,40 @@ ], "type": "object" }, + "NodeMasterView": { + "properties": { + "counts": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "panelVersion": { + "example": "v3.12.0", + "type": "string" + }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, + "xrayError": { + "type": "string" + }, + "xrayState": { + "example": "running", + "type": "string" + }, + "xrayVersion": { + "example": "26.1.1", + "type": "string" + } + }, + "required": [ + "counts" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -5028,6 +5107,33 @@ ], "type": "object" }, + "NodeOverview": { + "properties": { + "fleet": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "master": { + "$ref": "#/components/schemas/NodeMasterView" + }, + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeView" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "fleet", + "master", + "nodes" + ], + "type": "object" + }, "NodeSnapshotAttachment": { "properties": { "email": { @@ -5071,6 +5177,106 @@ ], "type": "object" }, + "NodeTelemetry": { + "description": "NodeTelemetry describes one host sample. Nil metrics were not measured.", + "properties": { + "cpuPct": { + "example": 12.5, + "nullable": true, + "type": "number" + }, + "load1": { + "example": 0.25, + "nullable": true, + "type": "number" + }, + "load15": { + "example": 0.12, + "nullable": true, + "type": "number" + }, + "load5": { + "example": 0.18, + "nullable": true, + "type": "number" + }, + "logicalCores": { + "example": 8, + "nullable": true, + "type": "integer" + }, + "memAvailableBytes": { + "example": 1073741824, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memTotalBytes": { + "example": 4294967296, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memUsedBytes": { + "example": 2147483648, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netDown": { + "example": 2048, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netUp": { + "example": 1024, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "physicalCores": { + "example": 4, + "nullable": true, + "type": "integer" + }, + "resourceScope": { + "example": "container", + "type": "string" + }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "sampledAt": { + "example": 1700000000000, + "format": "int64", + "type": "integer" + }, + "tcpCount": { + "example": 75, + "nullable": true, + "type": "integer" + }, + "udpCount": { + "example": 12, + "nullable": true, + "type": "integer" + }, + "uptimeSecs": { + "example": 3600, + "format": "int64", + "nullable": true, + "type": "integer" + } + }, + "required": [ + "sampledAt" + ], + "type": "object" + }, "NodeTrafficSnapshotV1": { "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", "properties": { @@ -5302,6 +5508,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -6205,6 +6419,12 @@ "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" @@ -8270,6 +8490,7 @@ "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, @@ -14490,6 +14711,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14509,6 +14731,69 @@ } } }, + "/panel/api/nodes/overview": { + "get": { + "tags": [ + "Nodes" + ], + "summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.", + "operationId": "get_panel_api_nodes_overview", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeOverview" + } + } + }, + "example": { + "success": true, + "obj": { + "fleet": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "master": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, + "nodes": [ + null + ] + } + } + } + } + } + } + } + }, "/panel/api/nodes/mtls/ca": { "post": { "tags": [ @@ -14696,6 +14981,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14851,6 +15137,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -20654,6 +20941,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ diff --git a/frontend/src/api/queries/useNodesQuery.ts b/frontend/src/api/queries/useNodesQuery.ts index 23d5db507..7273fb719 100644 --- a/frontend/src/api/queries/useNodesQuery.ts +++ b/frontend/src/api/queries/useNodesQuery.ts @@ -3,12 +3,39 @@ import { useMemo } from 'react'; import { HttpUtil } from '@/utils'; import { parseMsg } from '@/utils/zodValidate'; -import { NodeListSchema } from '@/schemas/node'; +import { NodeListSchema, NodeOverviewSchema } from '@/schemas/node'; import type { NodeRecord } from '@/schemas/node'; import { keys } from '@/api/queryKeys'; export type { NodeRecord }; +async function fetchNodeOverview() { + const msg = await HttpUtil.get('/panel/api/nodes/overview', undefined, { silent: true }); + if (!msg.success || msg.obj == null) throw new Error(msg.msg || 'Failed to fetch node overview'); + return NodeOverviewSchema.parse(msg.obj); +} + +const emptyNodes: NodeRecord[] = []; + +export function useNodeOverviewQuery() { + const query = useQuery({ + queryKey: keys.nodes.overview(), + queryFn: fetchNodeOverview, + refetchInterval: 5_000, + }); + return { + nodes: query.data?.nodes ?? emptyNodes, + master: query.data?.master, + fleet: query.data?.fleet, + nodesUpdatedAt: query.dataUpdatedAt, + loading: query.isFetching, + fetched: query.data !== undefined || query.isError, + fetchError: query.isLoadingError ? query.error.message : '', + refreshError: query.isRefetchError ? query.error.message : '', + refetch: query.refetch, + }; +} + export interface NodeTotals { total: number; online: number; diff --git a/frontend/src/api/queryKeys.ts b/frontend/src/api/queryKeys.ts index c03d796ad..e8448b04b 100644 --- a/frontend/src/api/queryKeys.ts +++ b/frontend/src/api/queryKeys.ts @@ -8,6 +8,7 @@ export const keys = { nodes: { root: () => ['nodes'] as const, list: () => ['nodes', 'list'] as const, + overview: () => ['nodes', 'overview'] as const, }, hosts: { root: () => ['hosts'] as const, diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index b8e09aa02..1a2cd19d9 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1297,6 +1297,7 @@ export const EXAMPLES: Record = { "remark": "", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -1324,11 +1325,34 @@ export const EXAMPLES: Record = { "total": 10737418240, "up": 1048576 }, + "NodeFleetCounts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, "NodeInboundTraffic": { "down": 0, "id": 1, "up": 0 }, + "NodeMasterView": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, "NodeMutationRequest": { "address": "", "allowPrivateAddress": false, @@ -1349,6 +1373,34 @@ export const EXAMPLES: Record = { "scheme": "http", "tlsVerifyMode": "verify" }, + "NodeOverview": { + "fleet": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "master": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, + "nodes": [ + null + ] + }, "NodeSnapshotAttachment": { "email": "user1", "inboundId": 1 @@ -1364,6 +1416,25 @@ export const EXAMPLES: Record = { null ] }, + "NodeTelemetry": { + "cpuPct": 12.5, + "load1": 0.25, + "load15": 0.12, + "load5": 0.18, + "logicalCores": 8, + "memAvailableBytes": 1073741824, + "memTotalBytes": 4294967296, + "memUsedBytes": 2147483648, + "netDown": 2048, + "netUp": 1024, + "physicalCores": 4, + "resourceScope": "container", + "sampleAgeMillis": 125, + "sampledAt": 1700000000000, + "tcpCount": 75, + "udpCount": 12, + "uptimeSecs": 3600 + }, "NodeTrafficSnapshotV1": { "activeInboundTree": {}, "clients": [ @@ -1439,6 +1510,7 @@ export const EXAMPLES: Record = { "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -1674,6 +1746,7 @@ export const EXAMPLES: Record = { "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 378fc8b16..2b7872427 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -4729,6 +4729,14 @@ export const SCHEMAS: Record = { "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4890,6 +4898,43 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeFleetCounts": { + "properties": { + "activeCount": { + "example": 90, + "type": "integer" + }, + "clientCount": { + "example": 100, + "type": "integer" + }, + "depletedCount": { + "example": 2, + "type": "integer" + }, + "disabledCount": { + "example": 8, + "type": "integer" + }, + "inboundCount": { + "example": 8, + "type": "integer" + }, + "onlineCount": { + "example": 20, + "type": "integer" + } + }, + "required": [ + "activeCount", + "clientCount", + "depletedCount", + "disabledCount", + "inboundCount", + "onlineCount" + ], + "type": "object" + }, "NodeInboundTraffic": { "properties": { "down": { @@ -4912,6 +4957,40 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeMasterView": { + "properties": { + "counts": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "panelVersion": { + "example": "v3.12.0", + "type": "string" + }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, + "xrayError": { + "type": "string" + }, + "xrayState": { + "example": "running", + "type": "string" + }, + "xrayVersion": { + "example": "26.1.1", + "type": "string" + } + }, + "required": [ + "counts" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -5002,6 +5081,33 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeOverview": { + "properties": { + "fleet": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "master": { + "$ref": "#/components/schemas/NodeMasterView" + }, + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeView" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "fleet", + "master", + "nodes" + ], + "type": "object" + }, "NodeSnapshotAttachment": { "properties": { "email": { @@ -5045,6 +5151,106 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeTelemetry": { + "description": "NodeTelemetry describes one host sample. Nil metrics were not measured.", + "properties": { + "cpuPct": { + "example": 12.5, + "nullable": true, + "type": "number" + }, + "load1": { + "example": 0.25, + "nullable": true, + "type": "number" + }, + "load15": { + "example": 0.12, + "nullable": true, + "type": "number" + }, + "load5": { + "example": 0.18, + "nullable": true, + "type": "number" + }, + "logicalCores": { + "example": 8, + "nullable": true, + "type": "integer" + }, + "memAvailableBytes": { + "example": 1073741824, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memTotalBytes": { + "example": 4294967296, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memUsedBytes": { + "example": 2147483648, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netDown": { + "example": 2048, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netUp": { + "example": 1024, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "physicalCores": { + "example": 4, + "nullable": true, + "type": "integer" + }, + "resourceScope": { + "example": "container", + "type": "string" + }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "sampledAt": { + "example": 1700000000000, + "format": "int64", + "type": "integer" + }, + "tcpCount": { + "example": 75, + "nullable": true, + "type": "integer" + }, + "udpCount": { + "example": 12, + "nullable": true, + "type": "integer" + }, + "uptimeSecs": { + "example": 3600, + "format": "int64", + "nullable": true, + "type": "integer" + } + }, + "required": [ + "sampledAt" + ], + "type": "object" + }, "NodeTrafficSnapshotV1": { "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", "properties": { @@ -5276,6 +5482,14 @@ export const SCHEMAS: Record = { "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -6179,6 +6393,12 @@ export const SCHEMAS: Record = { "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 4d2bca454..e97cad010 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1092,6 +1092,7 @@ export interface Node { remark: string; scheme: string; status: string; + telemetry?: NodeTelemetry | null; tlsVerifyMode: string; transitive?: boolean; unavailableMetrics?: string[]; @@ -1119,12 +1120,30 @@ export interface NodeClientTraffic { up: number; } +export interface NodeFleetCounts { + activeCount: number; + clientCount: number; + depletedCount: number; + disabledCount: number; + inboundCount: number; + onlineCount: number; +} + export interface NodeInboundTraffic { down: number; id: number; up: number; } +export interface NodeMasterView { + counts: NodeFleetCounts; + panelVersion?: string; + telemetry?: NodeTelemetry | null; + xrayError?: string; + xrayState?: string; + xrayVersion?: string; +} + export interface NodeMutationRequest { address: string; allowPrivateAddress: boolean; @@ -1144,6 +1163,12 @@ export interface NodeMutationRequest { tlsVerifyMode: string; } +export interface NodeOverview { + fleet: NodeFleetCounts; + master: NodeMasterView; + nodes: NodeView | null[]; +} + export interface NodeSnapshotAttachment { email: string; inboundId: number; @@ -1154,6 +1179,26 @@ export interface NodeSnapshotStructure { inbounds: Inbound | null[]; } +export interface NodeTelemetry { + cpuPct?: number | null; + load1?: number | null; + load15?: number | null; + load5?: number | null; + logicalCores?: number | null; + memAvailableBytes?: number | null; + memTotalBytes?: number | null; + memUsedBytes?: number | null; + netDown?: number | null; + netUp?: number | null; + physicalCores?: number | null; + resourceScope?: string; + sampleAgeMillis?: number | null; + sampledAt: number; + tcpCount?: number | null; + udpCount?: number | null; + uptimeSecs?: number | null; +} + export interface NodeTrafficSnapshotV1 { activeInboundTree: Record; clients: NodeClientTraffic[]; @@ -1203,6 +1248,7 @@ export interface NodeView { remark: string; scheme: string; status: string; + telemetry?: NodeTelemetry | null; tlsVerifyMode: string; transitive?: boolean; unavailableMetrics?: string[]; @@ -1411,6 +1457,7 @@ export interface Status { panelVersion: string; publicIP: unknown; resourceScope?: string; + sampleAgeMillis?: number | null; swap: unknown; tcpCount: number; udpCount: number; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index de23c7e02..cab871448 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1167,6 +1167,7 @@ export const NodeSchema = z.object({ remark: z.string(), scheme: z.enum(['http', 'https']), status: z.string(), + telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(), tlsVerifyMode: z.enum(['verify', 'skip', 'pin', 'mtls']), transitive: z.boolean().optional(), unavailableMetrics: z.array(z.string()).optional(), @@ -1196,6 +1197,16 @@ export const NodeClientTrafficSchema = z.object({ }); export type NodeClientTraffic = z.infer; +export const NodeFleetCountsSchema = z.object({ + activeCount: z.number().int(), + clientCount: z.number().int(), + depletedCount: z.number().int(), + disabledCount: z.number().int(), + inboundCount: z.number().int(), + onlineCount: z.number().int(), +}); +export type NodeFleetCounts = z.infer; + export const NodeInboundTrafficSchema = z.object({ down: z.number().int(), id: z.number().int(), @@ -1203,6 +1214,16 @@ export const NodeInboundTrafficSchema = z.object({ }); export type NodeInboundTraffic = z.infer; +export const NodeMasterViewSchema = z.object({ + counts: z.lazy(() => NodeFleetCountsSchema), + panelVersion: z.string().optional(), + telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(), + xrayError: z.string().optional(), + xrayState: z.string().optional(), + xrayVersion: z.string().optional(), +}); +export type NodeMasterView = z.infer; + export const NodeMutationRequestSchema = z.object({ address: z.string(), allowPrivateAddress: z.boolean(), @@ -1223,6 +1244,13 @@ export const NodeMutationRequestSchema = z.object({ }); export type NodeMutationRequest = z.infer; +export const NodeOverviewSchema = z.object({ + fleet: z.lazy(() => NodeFleetCountsSchema), + master: z.lazy(() => NodeMasterViewSchema), + nodes: z.array(z.lazy(() => NodeViewSchema).nullable()), +}); +export type NodeOverview = z.infer; + export const NodeSnapshotAttachmentSchema = z.object({ email: z.string(), inboundId: z.number().int(), @@ -1235,6 +1263,27 @@ export const NodeSnapshotStructureSchema = z.object({ }); export type NodeSnapshotStructure = z.infer; +export const NodeTelemetrySchema = z.object({ + cpuPct: z.number().nullable().optional(), + load1: z.number().nullable().optional(), + load15: z.number().nullable().optional(), + load5: z.number().nullable().optional(), + logicalCores: z.number().int().nullable().optional(), + memAvailableBytes: z.number().int().nullable().optional(), + memTotalBytes: z.number().int().nullable().optional(), + memUsedBytes: z.number().int().nullable().optional(), + netDown: z.number().int().nullable().optional(), + netUp: z.number().int().nullable().optional(), + physicalCores: z.number().int().nullable().optional(), + resourceScope: z.string().optional(), + sampleAgeMillis: z.number().int().nullable().optional(), + sampledAt: z.number().int(), + tcpCount: z.number().int().nullable().optional(), + udpCount: z.number().int().nullable().optional(), + uptimeSecs: z.number().int().nullable().optional(), +}); +export type NodeTelemetry = z.infer; + export const NodeTrafficSnapshotV1Schema = z.object({ activeInboundTree: z.record(z.string(), z.array(z.string())), clients: z.array(z.lazy(() => NodeClientTrafficSchema)), @@ -1285,6 +1334,7 @@ export const NodeViewSchema = z.object({ remark: z.string(), scheme: z.string(), status: z.string(), + telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(), tlsVerifyMode: z.string(), transitive: z.boolean().optional(), unavailableMetrics: z.array(z.string()).optional(), @@ -1509,6 +1559,7 @@ export const StatusSchema = z.object({ panelVersion: z.string(), publicIP: z.unknown(), resourceScope: z.string().optional(), + sampleAgeMillis: z.number().int().nullable().optional(), swap: z.unknown(), tcpCount: z.number().int(), udpCount: z.number().int(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 91080469e..5dcc424f0 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -2082,6 +2082,13 @@ export const sections: readonly Section[] = [ responseSchema: 'NodeView', responseSchemaArray: true, }, + { + method: 'GET', + path: '/panel/api/nodes/overview', + summary: + 'Read the local panel, unique fleet client counts and sampled remote host telemetry.', + responseSchema: 'NodeOverview', + }, { method: 'POST', path: '/panel/api/nodes/mtls/ca', diff --git a/frontend/src/pages/nodes/NodeList.css b/frontend/src/pages/nodes/NodeList.css index 920ac4978..e495fdfab 100644 --- a/frontend/src/pages/nodes/NodeList.css +++ b/frontend/src/pages/nodes/NodeList.css @@ -1,160 +1,652 @@ -.toolbar { - margin-bottom: 12px; - display: flex; - justify-content: space-between; - align-items: center; +@font-face { + font-family: 'Source Sans Pro'; + src: url('./fonts/SourceSansPro-Regular.woff2') format('woff2'); + font-weight: 400; + font-display: swap; } - -.name-cell { - display: flex; - flex-direction: column; -} - -.name-cell .name { - font-weight: 500; -} - -.name-cell .remark { - font-size: 12px; - opacity: 0.65; -} - -.address-header { - display: inline-flex; - align-items: center; - gap: 6px; -} - -.ip-toggle-icon { - cursor: pointer; - font-size: 14px; - opacity: 0.7; -} - -.ip-toggle-icon:hover { - opacity: 1; -} - -.address-hidden { - filter: blur(5px); - transition: filter 0.2s ease; -} - -.address-visible { - filter: none; -} - -.node-cards { - display: flex; - flex-direction: column; - gap: 12px; - margin-top: 4px; -} - -.node-card { - border: 1px solid var(--ant-color-border-secondary); - border-radius: 10px; - padding: 12px; - background: var(--ant-color-fill-quaternary); - display: flex; - flex-direction: column; - gap: 8px; -} - -.card-head { - display: flex; - align-items: center; - gap: 8px; - cursor: pointer; - user-select: none; -} - -.card-expand { - font-size: 12px; - opacity: 0.6; - transition: transform 150ms ease; - flex-shrink: 0; -} - -.card-expand.is-expanded { - transform: rotate(90deg); -} - -.node-name { +@font-face { + font-family: 'Source Sans Pro'; + src: url('./fonts/SourceSansPro-Semibold.woff2') format('woff2'); font-weight: 600; - flex: 1; + font-display: swap; +} +@font-face { + font-family: 'Source Sans Pro'; + src: url('./fonts/SourceSansPro-Bold.woff2') format('woff2'); + font-weight: 700; + font-display: swap; +} +.nodes-page.is-dark:not(.is-ultra) { + --bg-page: #1c1e23; +} + +@media (min-width: 769px) { + .nodes-page .ant-sidebar:not(.sidebar-pinned) { + --sider-rail: 69px !important; + } + + .nodes-page .ant-sidebar:not(.sidebar-pinned) .ant-layout-sider-collapsed { + flex-basis: 69px !important; + width: 69px !important; + min-width: 69px !important; + max-width: 69px !important; + } + + .nodes-page .content-area { + padding-inline-start: 23px; + } +} +.nodes-overview { + --node-fg: var(--node-text); + --node-secondary: var(--node-muted); + --node-card: var(--node-surface); + --node-field: var(--node-header-bg); + --node-line: var(--node-border); + --node-fleet: var(--node-fleet-bg); + --node-button: var(--node-accent); + --node-add-bg: #1269eb; + --node-link: #185ea8; + --node-good: #317a19; + --node-bad: #b42e35; + --node-purple: #722ed1; + --node-group-bg: #ebedf0; + --node-active-bg: #eef6e9; + --node-disabled-bg: #eeeff2; + --node-depleted-bg: #f9ebeb; + --node-online-bg: #e7f0fa; min-width: 0; + font: + 400 13px/1.25 'Source Sans Pro', + system-ui, + sans-serif; + color: var(--node-fg); +} +.dark .nodes-overview, +.nodes-page.is-dark:not(.is-ultra) .nodes-overview { + --node-fg: #d6d9e0; + --node-secondary: #9296a0; + --node-card: #23252b; + --node-field: #2b2d32; + --node-line: #353841; + --node-fleet: #252b34; + --node-button: #1677ff; + --node-link: #8cb8ff; + --node-good: #66b740; + --node-bad: #eb6469; + --node-purple: #bb9df5; + --node-group-bg: #30333b; + --node-active-bg: #172d12; + --node-disabled-bg: #37393e; + --node-depleted-bg: #401a1c; + --node-online-bg: #102d4b; +} +.nodes-heading, +.nodes-toolbar, +.nodes-footnote { + display: flex; + align-items: center; + gap: 12px; + margin-inline-start: 12px; +} +.nodes-heading { + align-items: start; + justify-content: space-between; + margin-block-end: 21px; +} +.nodes-heading h1 { + margin: 0; + font: + 600 25px/34px 'Source Sans Pro', + system-ui, + sans-serif; +} +.nodes-heading p { + margin: 1px 0 0; + color: var(--node-secondary); + font-size: 13px; + line-height: 21px; +} +.nodes-heading-actions { + display: flex; + gap: 12px; + padding-block-start: 4px; +} +.nodes-heading .ant-btn, +.nodes-toolbar .ant-btn { + font-family: inherit; + border-radius: 7px; +} +.nodes-heading .ant-btn { + height: 38px; +} +.nodes-heading .nodes-add { + width: 138px; + background: var(--node-add-bg); + font-weight: 600; +} +.nodes-heading .nodes-add:hover { + background: #145fd1; +} +.nodes-heading .nodes-mtls { + width: 145px; + background: var(--node-card); + border-color: var(--node-line); +} +.nodes-toolbar { + min-height: 36px; + margin-block-end: 13px; + flex-wrap: wrap; +} +.nodes-toolbar .ant-input-affix-wrapper { + width: min(278px, 100%); +} +.nodes-toolbar .ant-input-affix-wrapper, +.nodes-toolbar .ant-select { + height: 36px; + border-radius: 7px; + font: inherit; + color: var(--node-fg); + background: var(--node-field); + border-color: var(--node-line); +} +.nodes-toolbar .ant-input::placeholder, +.nodes-toolbar .ant-input-prefix, +.node-registered { + color: var(--node-secondary); +} +.nodes-toolbar .ant-input { + font: inherit; +} +.nodes-toolbar .ant-select { + width: 148px; +} +.nodes-toolbar .ant-select-selector { + background: transparent; +} +.node-registered { + margin-inline-start: auto; +} +.nodes-table-card { + padding: 15px 11px 30px; + border: 1px solid var(--node-line); + border-radius: 12px; + background: var(--node-card); +} +.nodes-table-scroll { + overflow-x: auto; + container-type: inline-size; +} +.node-fleet-table { + width: 100%; + min-width: 920px; + table-layout: fixed; + border-spacing: 0; + color: var(--node-fg); +} +.node-fleet-table th, +.node-fleet-table td { + padding: 0 8px; + text-align: start; + vertical-align: middle; + overflow-wrap: anywhere; +} +.node-fleet-table thead th { + height: 44px; + padding-inline: 1px; + background: var(--node-field); + color: var(--node-secondary); + text-align: center; + font-size: 12px; + font-weight: 600; +} +.node-fleet-table thead th:nth-child(6), +.node-fleet-table thead th:nth-child(8) { + font-weight: 700; +} +.node-fleet-table thead th:first-child { + border-start-start-radius: 8px; + border-end-start-radius: 8px; +} +.node-fleet-table thead th:last-child { + border-start-end-radius: 8px; + border-end-end-radius: 8px; +} +.node-fleet-table tbody > tr:not(.node-history-row) { + height: 70px; +} +.node-fleet-table td, +.node-fleet-table .node-name-cell { + border-block-end: 1px solid var(--node-line); +} +.node-row-remote > td:first-child { + padding-inline-end: 0; +} +.node-fleet-table .node-enabled { + text-align: center; + color: var(--node-secondary); +} +.node-fleet-table .node-enabled .ant-switch { + min-width: 34px; + height: 18px; +} +.node-fleet-table .node-enabled .ant-switch-handle { + width: 14px; + height: 14px; +} +.node-fleet-table .node-enabled .ant-switch.ant-switch-checked { + background: var(--node-button); +} +.node-row-fleet > * { + background: var(--node-fleet); +} +.node-row-fleet td:first-child { + box-shadow: inset 3px 0 var(--node-button); +} +.node-row-fleet > td:nth-child(5) { + padding-inline-end: 2px; +} +[dir='rtl'] .node-row-fleet td:first-child { + box-shadow: inset -3px 0 var(--node-button); +} +.node-actions-heading, +.node-readonly-action, +.node-icon-action, +.node-expander, +.node-status-button { + border: 0; + padding: 0; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} +.node-actions, +.node-system-action, +.node-status-button { + display: flex; + align-items: center; +} +.node-actions { + flex-wrap: wrap; + row-gap: 3px; +} +.node-actions > .ant-checkbox-wrapper { + margin-inline: 8px 5px; +} +.node-actions .ant-checkbox-inner { + width: 16px; + height: 16px; + background: var(--node-card); + border-color: #636b7b; +} +.node-actions .ant-checkbox-checked .ant-checkbox-inner { + background: var(--node-button); + border-color: var(--node-button); +} +.node-system-action { + gap: 12px; + padding-inline-start: 9px; + color: var(--node-secondary); +} +.node-system-badge { + min-width: 52px; + padding: 4px 12px; + border-radius: 4px; + color: var(--node-fg); + background: var(--node-group-bg); + font-size: 10px; + font-weight: 600; + text-align: center; + text-transform: uppercase; +} +.node-sigma { + color: var(--node-link); + font-size: 18px; + font-weight: 600; +} +.node-icon-action, +.node-expander { + display: inline-grid; + place-content: center; + width: 18px; + height: 24px; + font-size: 15px; +} +.node-icon-delete { + color: var(--node-bad); +} +.node-icon-action:disabled { + color: var(--node-secondary); + opacity: 0.5; + cursor: default; +} +.node-expander { + height: 18px; + border: 1px solid var(--node-line); + border-radius: 4px; + background: var(--node-field); + color: var(--node-secondary); + font-size: 13px; +} +.node-name, +.node-cell-stack { + display: flex; + flex-direction: column; + min-width: 0; +} +.node-name { + gap: 4px; + font-size: 12px; + font-weight: 600; +} +.node-name > span, +.node-name > small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } - -.card-actions { - display: flex; - align-items: center; - gap: 8px; - flex-shrink: 0; +.node-row-fleet .node-name > span, +.node-row-master .node-name > span { + font-size: 14px; } - -.row-action-trigger { - font-size: 20px; - cursor: pointer; +.node-row-fleet .node-name > small { + font-size: 11px; + white-space: normal; } - -.card-stats { - display: flex; - flex-direction: column; - gap: 6px; -} - -.stat-row { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 6px; -} - -.stat-label { +.node-name small { + color: var(--node-secondary); font-size: 10px; - text-transform: uppercase; - letter-spacing: 0.04em; - opacity: 0.6; - min-width: 96px; - flex-shrink: 0; + font-weight: 400; } - -.card-stats .ant-tag { +.node-open-link:any-link { + color: var(--node-link); + font-size: 10px; + white-space: nowrap; +} +.node-open-link:hover, +.node-open-link:focus-visible { + text-decoration: underline; +} +.node-open-link span { + font-size: 13px; + font-weight: 600; +} +.node-status-button { + gap: 5px; + width: 100%; + text-align: start; + font-size: 11px; + font-weight: 600; +} +.node-status-button[data-status='online'] { + color: var(--node-good); +} +.node-status-button[data-status='offline'] { + color: var(--node-bad); +} +.node-status-button .online-dot, +.node-status-button .xray-error-dot, +.node-status-button .ant-badge-status-dot { + display: inline-block; + width: 8px; + height: 8px; + flex: 0 0 8px; + border-radius: 50%; +} +.node-status-button .online-dot { + background: var(--node-good); +} +.node-status-button .xray-error-dot { + background: var(--node-purple); +} +.node-status-info { + margin-inline-start: auto; + color: var(--node-secondary); + font-size: 10px; +} +.node-status-popup .ant-tooltip-container { + width: min(258px, 90vw); + padding: 12px 14px; + border: 1px solid #414550; + border-radius: 8px; + color: #d6d9e0; + font: + 400 11px/1.4 'Source Sans Pro', + system-ui, + sans-serif; +} +.node-status-tooltip h3 { + margin: 0 0 5px; + color: #a6aab4; + font: + 600 11px 'Source Sans Pro', + system-ui, + sans-serif; +} +.node-status-tooltip dl { margin: 0; } - -.card-history { - margin-top: 4px; - padding-top: 8px; - border-top: 1px solid var(--ant-color-border-secondary); -} - -.card-empty { - text-align: center; - color: var(--ant-color-text-secondary); - padding: 24px 12px; +.node-status-tooltip dl > div { display: flex; - flex-direction: column; - align-items: center; - gap: 8px; + justify-content: space-between; + gap: 25px; + line-height: 23px; } - -.node-network-speed { - display: inline-grid; - row-gap: 2px; - text-align: start; - line-height: 1.25; +.node-status-tooltip dd { + margin: 0; + font-size: 12px; + font-weight: 600; } - -.node-network-direction { - display: grid; - grid-template-columns: 1em auto; - column-gap: 4px; - align-items: center; - white-space: nowrap; +.node-status-tooltip dt { + color: #a6aab4; +} +.node-hardware { + gap: 6px; font-variant-numeric: tabular-nums; } +.node-cpu { + font: + 400 11px/15px 'Source Sans Pro', + system-ui, + sans-serif; +} +.node-ram { + font: + 400 10px/13px 'Source Sans Pro', + system-ui, + sans-serif; +} +.node-memory-detail { + color: var(--node-secondary); + font-size: 9px; +} +.node-network-speed, +.node-runtime, +.node-connections, +.node-system-clients { + gap: 5px; + font-size: 10px; +} +.node-network-speed { + display: inline-grid; + font-variant-numeric: tabular-nums; +} +.node-network-direction { + display: flex; + align-items: center; + gap: 3px; +} +.node-network-up { + color: var(--node-link); +} +.node-row-fleet .node-network-speed, +.node-row-master .node-network-speed { + font-size: 12px; +} +.node-connections > span:nth-child(-n + 2) { + font-weight: 600; +} +.node-connection-load, +.node-runtime small { + color: var(--node-secondary); + font-size: 9px; +} +.node-runtime .node-panel-line { + display: flex; + align-items: center; + gap: 3px; +} +.node-runtime .node-icon-action { + width: 13px; + height: 13px; + color: var(--node-link); + font-size: 11px; +} +.node-system-clients { + font-size: 11px; +} +.node-system-clients small { + color: var(--node-secondary); + font-size: 10px; +} +.node-client-counts { + display: grid; + grid-template-columns: 52fr 54fr 58fr; + grid-template-rows: repeat(2, 21px); + gap: 4px 6px; + align-items: center; +} +.node-count-total { + grid-column: 1; + grid-row: 1 / span 2; +} +.node-client-counts .ant-tag { + margin: 0; + padding-inline: 2px; + text-align: center; + line-height: 19px; + font: + 400 11px/19px 'Source Sans Pro', + system-ui, + sans-serif; + color: var(--node-fg); + background: var(--node-disabled-bg); +} +.node-client-counts .node-count-active { + grid-column: 2; + grid-row: 1; + background: var(--node-active-bg); + color: var(--node-good); +} +.node-client-counts .node-count-disabled { + grid-column: 3; + grid-row: 1; +} +.node-client-counts .node-count-depleted { + grid-column: 2; + grid-row: 2; + background: var(--node-depleted-bg); + color: var(--node-bad); +} +.node-client-counts .node-count-online { + grid-column: 3; + grid-row: 2; + background: var(--node-online-bg); + color: var(--node-link); +} +.node-history-row td { + padding: 12px; +} +.nodes-footnote { + justify-content: space-between; + margin-block-start: 9px; + color: var(--node-secondary); + font-size: 11px; + line-height: 22px; +} +@container (max-width: 1205px) { + .node-actions > .ant-checkbox-wrapper { + margin-inline: 4px; + } + + .node-actions > .node-icon-action { + width: 17px; + } +} +@media (max-width: 650px) { + .nodes-heading { + flex-wrap: wrap; + } + .nodes-heading-actions { + flex-wrap: wrap; + } + .node-registered { + margin-inline-start: 0; + } +} +@container (width < 920px) { + .node-fleet-table, + .node-fleet-table thead, + .node-fleet-table tbody, + .node-fleet-table tr, + .node-fleet-table .node-history-row td { + display: block; + min-width: 0; + } + .node-fleet-table colgroup { + display: none; + } + .node-fleet-table thead th:not(:first-child) { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + } + .node-fleet-table thead th:first-child { + display: flex; + align-items: center; + padding-inline: 10px; + border-radius: 8px; + } + .node-fleet-table tbody > tr:not(.node-history-row) { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; + height: auto; + margin-block-start: 8px; + padding: 10px; + border: 1px solid var(--node-line); + border-radius: 8px; + } + .node-row-fleet { + background: var(--node-fleet); + } + .node-fleet-table tbody td, + .node-fleet-table .node-name-cell { + min-width: 0; + padding: 0; + border: 0; + text-align: start; + } + .node-fleet-table .node-name-cell, + .node-fleet-table tbody td:first-child { + grid-column: 1 / -1; + } + .node-fleet-table .node-name-cell { + grid-row: 1; + } + .node-fleet-table td[data-label]::before { + display: block; + margin-block-end: 4px; + color: var(--node-secondary); + font-size: 11px; + content: attr(data-label); + } + .node-fleet-table .node-row-fleet td:first-child { + box-shadow: none; + } + .node-fleet-table .node-history-row td { + padding: 10px; + } +} diff --git a/frontend/src/pages/nodes/NodeList.stories.tsx b/frontend/src/pages/nodes/NodeList.stories.tsx new file mode 100644 index 000000000..932e3c954 --- /dev/null +++ b/frontend/src/pages/nodes/NodeList.stories.tsx @@ -0,0 +1,169 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, within } from 'storybook/test'; +import { ConfigProvider } from 'antd'; +import { useState } from 'react'; +import type { NodeRecord } from '@/schemas/node'; +import NodeList from './NodeList'; + +const counts = { + clientCount: 7100, + inboundCount: 40, + activeCount: 6050, + disabledCount: 50, + depletedCount: 1000, + onlineCount: 210, +}; +const noop = () => {}; + +function Fixture({ rtl }: { rtl?: boolean }) { + const [selectedIds, setSelectedIds] = useState([]); + const [now] = useState(Date.now); + const nodes: NodeRecord[] = [ + { + id: 1, + name: 'Finland edge', + status: 'online', + enable: true, + xrayVersion: '26.1.1', + panelVersion: '3.12.0', + latencyMs: 42, + lastHeartbeat: Math.floor(now / 1000) - 2, + scheme: 'https', + address: '2001:db8::3', + port: 2053, + basePath: '/edge/', + telemetry: { + sampledAt: now, + cpuPct: 0, + logicalCores: 8, + memUsedBytes: 4 * 2 ** 30, + memTotalBytes: 16 * 2 ** 30, + netUp: 1024, + netDown: 2048, + tcpCount: 0, + udpCount: 21, + load1: 0.25, + load5: 0.15, + load15: 0.1, + uptimeSecs: 5000, + }, + clientCount: 3077, + onlineCount: 31, + onlineTotalCount: 53, + }, + { + id: 2, + name: 'Frankfurt', + status: 'online', + enable: true, + panelVersion: '3.13.0', + scheme: 'https', + address: 'frankfurt-with-a-very-long-hostname.example.test', + port: 443, + telemetry: { sampledAt: now, cpuPct: 40, logicalCores: 4, tcpCount: 4, load1: 0.75 }, + }, + { + id: 3, + name: 'This-is-an-intentionally-long-node-name-without-spaces', + status: 'offline', + enable: true, + lastError: 'Remote panel did not respond', + }, + { + id: 4, + name: 'Standby', + status: 'online', + enable: false, + telemetry: { sampledAt: now, cpuPct: 100, tcpCount: 9 }, + }, + ]; + return ( + +
+ +
+
+ ); +} + +const meta = { title: 'Nodes/Fleet Monitoring', component: Fixture } satisfies Meta; +export default meta; +type Story = StoryObj; + +export const Desktop: Story = { + play: async ({ canvasElement, userEvent }) => { + const canvas = within(canvasElement); + const row = canvas.getByRole('row', { name: /All nodes/ }); + await expect(within(row).getByText('3/5 reporting')).toBeVisible(); + await expect(within(row).getByText('20.0%')).toBeVisible(); + await expect(within(row).queryByRole('checkbox')).toBeNull(); + await expect( + within(canvas.getByRole('row', { name: /Master/ })).queryByRole('switch'), + ).toBeNull(); + const edge = canvas.getByRole('row', { name: /Finland edge/ }); + const link = within(edge).getByRole('link', { name: 'Open' }); + await expect(link).toHaveAttribute('href', 'https://[2001:db8::3]:2053/edge/'); + await expect(link).toHaveAttribute('rel', 'noopener noreferrer'); + const status = within(edge).getByRole('button', { name: 'Online' }); + await userEvent.click(status); + await expect(await within(canvasElement.ownerDocument.body).findByText('42 ms')).toBeVisible(); + const input = canvas.getByRole('searchbox', { name: 'Search' }); + await userEvent.click(input); + for (const viewport of [1280, 1440, 1664, 1920]) { + const container = canvas.getByRole('region', { name: 'Nodes' }); + container.style.width = `${viewport - 260}px`; + const table = container.querySelector('.nodes-table-scroll') as HTMLElement; + await expect(table.scrollWidth).toBeLessThanOrEqual(table.clientWidth + 1); + container.style.width = ''; + } + await userEvent.type(input, 'Frankfurt'); + await expect(canvas.queryByText('Finland edge')).toBeNull(); + await expect(canvas.getByText('3/5 reporting')).toBeVisible(); + await userEvent.clear(input); + }, +}; + +export const RTL: Story = { args: { rtl: true }, globals: { theme: 'light' } }; diff --git a/frontend/src/pages/nodes/NodeList.tsx b/frontend/src/pages/nodes/NodeList.tsx index 3ae461c32..00da6117f 100644 --- a/frontend/src/pages/nodes/NodeList.tsx +++ b/frontend/src/pages/nodes/NodeList.tsx @@ -1,39 +1,58 @@ -import { useCallback, useMemo, useState } from 'react'; +import { Fragment, useMemo, useState, type CSSProperties, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; -import { Badge, Button, Card, Dropdown, Modal, Space, Switch, Table, Tag, Tooltip } from 'antd'; +import { + Badge, + Checkbox, + Button, + Dropdown, + Input, + Select, + Switch, + Tag, + Tooltip, + theme, +} from 'antd'; import type { BadgeProps } from 'antd'; -import type { ColumnsType } from 'antd/es/table'; import { ApartmentOutlined, - ClusterOutlined, CloudDownloadOutlined, DeleteOutlined, EditOutlined, ExclamationCircleOutlined, EyeInvisibleOutlined, EyeOutlined, + LockOutlined, InfoCircleOutlined, + SearchOutlined, MoreOutlined, PlusOutlined, ReloadOutlined, - RightOutlined, SafetyCertificateOutlined, TeamOutlined, ThunderboltOutlined, } from '@ant-design/icons'; import NodeHistoryPanel from './NodeHistoryPanel'; -import NodeNetworkSpeed from './NodeNetworkSpeed'; +import { NetworkSpeedValues } from './NodeNetworkSpeed'; +import { + aggregateTelemetry, + freshTelemetry, + reportingSample, + useTelemetryClock, +} from './fleetTelemetry'; +import type { NodeTelemetry, NodeFleetCounts, NodeMasterView } from '@/generated/types'; +import { SizeFormatter } from '@/utils'; +import { withBasePath } from '@/api/http-init'; import type { NodeRecord } from '@/api/queries/useNodesQuery'; import { isPanelUpdateAvailable } from '@/lib/panel-version'; -import { activateOnKey } from '@/utils/a11y'; import './NodeList.css'; interface NodeListProps { nodes: NodeRecord[]; + master?: NodeMasterView; + fleet?: NodeFleetCounts; nodesUpdatedAt?: number; loading?: boolean; - isMobile?: boolean; latestVersion?: string; selectedIds: number[]; onSelectionChange: (ids: number[]) => void; @@ -57,18 +76,15 @@ function isUpdateEligible(n: NodeRecord): boolean { // A node also serves clients on inbounds this panel does not sync; when it reports // more online than the synced count, both show as "synced / total". -function onlineCounts(n: NodeRecord): { label: string; synced: number; total: number } | null { +function onlineCounts( + n: Pick, +): { label: string; synced: number; total: number } | null { const synced = n.onlineCount || 0; const total = Math.max(n.onlineTotalCount || 0, synced); if (!total) return null; return { label: total > synced ? `${synced} / ${total}` : String(synced), synced, total }; } -interface NodeRow extends NodeRecord { - url: string; - key: string | number; -} - function badgeStatus(status?: string): BadgeProps['status'] { switch (status) { case 'online': @@ -132,16 +148,12 @@ function StatusLabel({ status, xrayState }: HealthProps) { ? t('pages.nodes.statusValues.xrayError') : t('pages.nodes.statusValues.xrayStopped'); return ( - + {t('pages.nodes.statusValues.online')} ({detail}) ); } - return ( - - {t('pages.nodes.statusValues.online')} - - ); + return {t('pages.nodes.statusValues.online')}; } // A sub-node's status is free text from its parent node: show it as unknown, not as a key. return ( @@ -153,13 +165,13 @@ function StatusLabel({ status, xrayState }: HealthProps) { ); } -function formatPct(p?: number, available = true): string { +function formatPct(p?: number | null, available = true): string { if (!available) return '—'; if (typeof p !== 'number' || Number.isNaN(p)) return '-'; return `${p.toFixed(1)}%`; } -function formatUptime(secs?: number, available = true): string { +function formatUptime(secs?: number | null, available = true): string { if (!available) return '—'; if (!secs) return '-'; const days = Math.floor(secs / 86400); @@ -188,32 +200,306 @@ function useRelativeTime() { ); } -function OnlineTag({ node, compact }: { node: NodeRecord; compact?: boolean }) { +function OnlineTag({ node }: { node: Pick }) { const { t } = useTranslation(); const counts = onlineCounts(node); if (!counts) return null; - const tag = compact ? ( - - {counts.label} - - ) : ( - - {counts.label} {t('online')} - + const title = + counts.total > counts.synced + ? t('pages.nodes.onlineOnNode', { synced: counts.synced, total: counts.total }) + : t('online'); + return ( + + {counts.label} + ); - if (counts.total > counts.synced) { - const title = t('pages.nodes.onlineOnNode', { synced: counts.synced, total: counts.total }); - return {tag}; - } - // The compact tag is a bare number, so it still needs to say what it counts. - return compact ? {tag} : tag; } +type FleetRow = + | { kind: 'remote'; key: string | number; node: NodeRecord; telemetry?: NodeTelemetry } + | { kind: 'master'; key: 'master'; host: NodeMasterView; telemetry?: NodeTelemetry } + | { + kind: 'fleet'; + key: 'fleet'; + counts: NodeFleetCounts; + telemetry: NodeTelemetry; + reporting: number; + registered: number; + cpuHosts: number; + memoryHosts: number; + panelVersions: string[]; + xrayVersions: string[]; + }; + +function HealthStatus({ + node, + relativeTime, +}: { + node: HealthProps & + Partial>; + relativeTime: (ts?: number) => string; +}) { + const { t } = useTranslation(); + const status = node.enable === false && node.status !== 'offline' ? 'disabled' : node.status; + const { tip, iconColor } = statusIssue(node); + return ( + +

{t('pages.nodes.fleet.connectionDetails')}

+ {node.id !== undefined && ( +
+
+
{t('pages.nodes.latency')}
+
{node.latencyMs ? node.latencyMs + ' ms' : '—'}
+
+
+
{t('pages.nodes.lastHeartbeat')}
+
{relativeTime(node.lastHeartbeat)}
+
+
+ )} + {node.xrayState && ( +
+ {t('pages.nodes.xrayVersion')} · {node.xrayState} +
+ )} + {tip &&
{tip}
} + + } + > + +
+ ); +} + +function Hardware({ + sample, + fleet, + system, +}: { + sample?: NodeTelemetry; + fleet: boolean; + system: boolean; +}) { + const { t, i18n } = useTranslation(); + const total = sample?.memTotalBytes; + const used = sample?.memUsedBytes; + const hasMemory = used != null && total != null && total > 0 && used <= total; + const memorySize = (value: number) => { + if (!total || total < SizeFormatter.ONE_GB) return SizeFormatter.sizeFormat(value); + const useTB = total >= SizeFormatter.ONE_TB; + return new Intl.NumberFormat(i18n.language, { + maximumFractionDigits: 1, + style: 'unit', + unit: useTB ? 'terabyte' : 'gigabyte', + unitDisplay: 'short', + }).format(value / (useTB ? SizeFormatter.ONE_TB : SizeFormatter.ONE_GB)); + }; + return ( +
+
+ {fleet ? t('pages.nodes.fleet.cpuAverage') : t('pages.nodes.cpu')}{' '} + {formatPct(sample?.cpuPct, sample?.cpuPct != null)} + {sample?.logicalCores != null && ( + <> · {t('pages.nodes.fleet.logicalCores', { cores: sample.logicalCores })} + )} +
+
+ RAM{' '} + {hasMemory ? ( + + {memorySize(used)} / {memorySize(total)} · {formatPct((100 * used) / total)} + + ) : ( + '—' + )} +
+ {system && hasMemory && ( + + {sample?.memAvailableBytes != null + ? t('pages.nodes.fleet.availableMemory', { + size: SizeFormatter.sizeFormat(sample?.memAvailableBytes), + }) + : t('pages.nodes.fleet.remainingMemory', { + size: SizeFormatter.sizeFormat(total - used), + })} + + )} +
+ ); +} + +function Connections({ sample, fleet }: { sample?: NodeTelemetry; fleet: boolean }) { + const { t, i18n } = useTranslation(); + const count = new Intl.NumberFormat(i18n.language); + return ( +
+ + TCP {sample?.tcpCount == null ? '—' : count.format(sample.tcpCount)} + + + UDP {sample?.udpCount == null ? '—' : count.format(sample.udpCount)} + + + {fleet ? t('pages.nodes.fleet.loadSum') : t('pages.nodes.fleet.load')}{' '} + + {[sample?.load1, sample?.load5, sample?.load15] + .map((v) => v?.toFixed(2) ?? '—') + .join(' / ')} + + +
+ ); +} + +function ClientCounts({ + counts, +}: { + counts: Pick< + NodeRecord, + | 'clientCount' + | 'activeCount' + | 'disabledCount' + | 'depletedCount' + | 'onlineCount' + | 'onlineTotalCount' + >; +}) { + const { t } = useTranslation(); + return ( +
+ + {counts.clientCount ?? 0} + + {!!counts.activeCount && ( + + {counts.activeCount} + + )} + {!!counts.disabledCount && ( + + {counts.disabledCount} + + )} + {!!counts.depletedCount && ( + + {counts.depletedCount} + + )} + +
+ ); +} + +function panelUrl(node: NodeRecord) { + if ( + (node.scheme !== 'https' && node.scheme !== 'http') || + !node.address || + !node.port || + !Number.isInteger(node.port) || + node.port < 1 || + node.port > 65535 || + /[\s/?#@\\]/.test(node.address) + ) + return undefined; + const address = + node.address.includes(':') && !node.address.startsWith('[') + ? '[' + node.address + ']' + : node.address; + try { + const origin = new URL(node.scheme + '://' + address + ':' + node.port); + const path = node.basePath || '/'; + if (!path.startsWith('/') || path.startsWith('//') || /[\\?#\p{Cc}]/u.test(path)) + return undefined; + return origin.origin + path; + } catch { + return undefined; + } +} + +function sampleVersions( + rows: (NodeRecord | NodeMasterView)[], + key: 'panelVersion' | 'xrayVersion', +) { + return [ + ...new Set(rows.map((row) => row[key]).filter((version): version is string => !!version)), + ]; +} + +const columnWidths = [ + { key: 'actions', px: 148 }, + { key: 'enabled', px: 52 }, + { key: 'node', px: 118 }, + { key: 'address', px: 54 }, + { key: 'status', px: 104 }, + { key: 'hardware', px: 160 }, + { key: 'traffic', px: 120 }, + { key: 'connections', px: 125 }, + { key: 'runtime', px: 145 }, + { key: 'clients', px: 200 }, +]; + +function RowAction({ + label, + icon, + disabled, + danger, + onClick, +}: { + label: string; + icon: ReactNode; + disabled?: boolean; + danger?: boolean; + onClick: () => void; +}) { + return ( + + ); +} + +const canSelect = (row: FleetRow) => + row.kind === 'remote' && !row.node.transitive && isUpdateEligible(row.node); + export default function NodeList({ nodes, + master, + fleet, nodesUpdatedAt, loading = false, - isMobile = false, latestVersion = '', selectedIds, onSelectionChange, @@ -228,718 +514,594 @@ export default function NodeList({ onRestart, restartingIds = noRestarts, }: NodeListProps) { - const { t } = useTranslation(); + const { t, i18n } = useTranslation(); + const { token } = theme.useToken(); const relativeTime = useRelativeTime(); - + const [search, setSearch] = useState(''); + const [filter, setFilter] = useState('all'); + const [opened, setOpened] = useState>(() => new Set()); const [showAddress, setShowAddress] = useState(false); - const [statsNodeId, setStatsNodeId] = useState(null); - const [expandedIds, setExpandedIds] = useState>(new Set()); - - const restartItems = useCallback( - (node: NodeRecord) => - (['xray', 'panel'] as const).map((target) => ({ - key: `restart-${target}`, - icon: , - label: t(`pages.nodes.${target === 'xray' ? 'restartXray' : 'restartPanel'}`), - disabled: !node.enable || !!node.transitive || restartingIds.has(node.id), - onClick: () => onRestart(node, target), - })), - [t, onRestart, restartingIds], + const hasNodes = nodes.length > 0; + const samples = useMemo( + () => (nodes.length ? [master?.telemetry, ...nodes.map((node) => node.telemetry)] : []), + [master, nodes], ); + const now = useTelemetryClock(samples, nodesUpdatedAt); - // Map a direct node's GUID to its display name so a transitive sub-node can show - // which parent it is reached through (#4983); the master walks one level only. - const nameByGuid = useMemo(() => { - const m = new Map(); - for (const n of nodes) if (n.guid && !n.transitive) m.set(n.guid, n.name || n.guid); - return m; - }, [nodes]); + const rows = useMemo(() => { + // Fleet monitoring, including Master, is shown only after a remote is registered. + if (!nodes.length) return []; + const masterTelemetry = freshTelemetry(master?.telemetry, now, nodesUpdatedAt); + const remote = nodes.map((node): FleetRow & { kind: 'remote' } => ({ + kind: 'remote', + key: node.transitive ? 't-' + node.guid : node.id, + node, + telemetry: + node.enable && node.status === 'online' + ? freshTelemetry(node.telemetry, now, nodesUpdatedAt) + : undefined, + })); + const results: FleetRow[] = []; + if (fleet) { + const reported = remote.filter((row) => reportingSample(row.telemetry)); + const reportedSamples = [masterTelemetry, ...reported.map((row) => row.telemetry)].filter( + reportingSample, + ); + const hosts = [ + ...reported.map((row) => row.node), + ...(master && reportingSample(masterTelemetry) ? [master] : []), + ]; + results.push({ + kind: 'fleet', + key: 'fleet', + counts: fleet, + registered: nodes.length + 1, + reporting: reportedSamples.length, + ...aggregateTelemetry(reportedSamples), + panelVersions: sampleVersions(hosts, 'panelVersion'), + xrayVersions: sampleVersions(hosts, 'xrayVersion'), + }); + } + if (master) + results.push({ kind: 'master', key: 'master', host: master, telemetry: masterTelemetry }); - // Order direct nodes first, each immediately followed by its transitive - // sub-nodes, so the table reads as a parent -> child tree without colliding - // with the per-row history expander (transitive nodes carry id 0). - const dataSource = useMemo(() => { - const toRow = (n: NodeRecord): NodeRow => ({ - ...n, - url: `${n.scheme}://${n.address}:${n.port}${n.basePath || '/'}`, - key: n.transitive ? `t-${n.guid || ''}` : n.id, - }); - const childrenByParent = new Map(); - for (const n of nodes) { - if (n.transitive && n.parentGuid) { - const arr = childrenByParent.get(n.parentGuid) || []; - arr.push(n); - childrenByParent.set(n.parentGuid, arr); + const word = search.trim().toLocaleLowerCase(); + const visible = remote.filter( + ({ node }) => + (filter === 'all' || + (node.enable === false ? 'disabled' : (node.status ?? 'unknown')) === filter) && + (!word || + [node.name, node.remark, ...(showAddress ? [node.address] : [])].some((value) => + value?.toLocaleLowerCase().includes(word), + )), + ); + const children = new Map(); + for (const row of visible) { + if (!row.node.transitive || !row.node.parentGuid) continue; + const group = children.get(row.node.parentGuid) ?? []; + group.push(row); + children.set(row.node.parentGuid, group); + } + const inserted = new Set(); + for (const row of visible) { + if (row.node.transitive) continue; + results.push(row); + if (!row.node.guid) continue; + for (const child of children.get(row.node.guid) ?? []) { + if (inserted.has(child.key)) continue; + results.push(child); + inserted.add(child.key); } } - const ordered: NodeRow[] = []; - const added = new Set(); - const push = (n: NodeRecord) => { - const row = toRow(n); - ordered.push(row); - added.add(String(row.key)); + results.push(...visible.filter((row) => row.node.transitive && !inserted.has(row.key))); + return results; + }, [fleet, master, nodes, nodesUpdatedAt, now, search, filter, showAddress]); + + const nameByGuid = useMemo( + () => + new Map(nodes.filter((n) => n.guid && !n.transitive).map((n) => [n.guid, n.name || n.guid])), + [nodes], + ); + + const table = useMemo(() => { + const nf = new Intl.NumberFormat(i18n.language); + const headers = [ + t('pages.nodes.actions'), + t('pages.nodes.enable'), + t('pages.nodes.fleet.node'), + t('pages.nodes.address'), + t('pages.nodes.status'), + t('pages.nodes.fleet.hardware'), + t('pages.inbounds.traffic'), + t('pages.nodes.fleet.connections'), + t('pages.nodes.fleet.runtime'), + t('clients'), + ]; + const selectableIds = rows + .filter(canSelect) + .map((row) => (row.kind === 'remote' ? row.node.id : 0)); + const allSelected = + selectableIds.length > 0 && selectableIds.every((id) => selectedIds.includes(id)); + const toggleAll = () => { + if (allSelected) onSelectionChange(selectedIds.filter((id) => !selectableIds.includes(id))); + else onSelectionChange([...new Set([...selectedIds, ...selectableIds])]); }; - for (const n of nodes) { - if (n.transitive) continue; - push(n); - if (n.guid) for (const child of childrenByParent.get(n.guid) || []) push(child); - } - // Transitive nodes whose parent isn't in the list still get shown. - for (const n of nodes) { - if (n.transitive && !added.has(`t-${n.guid || ''}`)) push(n); - } - return ordered; - }, [nodes]); - - const statsNode = - statsNodeId === null - ? undefined - : dataSource.find((node) => !node.transitive && node.id === statsNodeId); - - function toggleExpanded(id: number) { - setExpandedIds((prev) => { - const next = new Set(prev); - if (next.has(id)) next.delete(id); - else next.add(id); - return next; - }); - } - - const columns = useMemo>( - () => [ - { - title: t('pages.nodes.actions'), - align: 'center', - width: 190, - render: (_value, record) => - record.transitive ? ( - - } style={{ margin: 0 }}> - {t('pages.nodes.subNode')} - - - ) : ( - - - - - {selectedIds.length > 0 && ( - - )} - - - {isMobile ? ( - <> -
- {dataSource.length === 0 ? ( -
- -
{t('noData')}
-
- ) : ( - dataSource.map((record) => - record.transitive ? ( -
-
- - - {record.name} -
- } style={{ margin: 0 }}> - {t('pages.nodes.subNode')} - -
-
-
- ) : ( -
- {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events -- mouse click-to-expand mirrors the keyboard-accessible chevron disclosure button */} -
{ - if (!(e.target as HTMLElement).closest('.card-actions')) - toggleExpanded(record.id); - }} - > - toggleExpanded(record.id))} - /> - - {record.name} -
- - setStatsNodeId(record.id)} - onKeyDown={activateOnKey(() => setStatsNodeId(record.id))} - /> - - onToggleEnable(record, v)} - /> - - {t('pages.nodes.probe')} - - ), - onClick: () => onProbe(record), - }, - ...(isUpdateEligible(record) - ? [ - { - key: 'update', - label: ( - <> - {' '} - {t('pages.nodes.updatePanel')} - - ), - onClick: () => onUpdateNode(record), - }, - ] - : []), - { - key: 'edit', - label: ( - <> - {t('edit')} - - ), - onClick: () => onEdit(record), - }, - { - key: 'delete', - danger: true, - label: ( - <> - {t('delete')} - - ), - onClick: () => onDelete(record), - }, - ], - }} - > -
-
- - {expandedIds.has(record.id) && ( -
- -
- )} -
- ), - ) - )} -
- - setStatsNodeId(null)} +
+
+
+

{t('menu.nodes')}

+ {hasNodes &&

{t('pages.nodes.fleet.subtitle')}

} +
+
+ + +
+
+ {hasNodes && ( + <> +
+ } + aria-label={t('search')} + placeholder={t('pages.nodes.fleet.searchNodes')} + allowClear + value={search} + onChange={(event) => setSearch(event.target.value)} + /> + { + setPickerOpen(next); + if (!next) setSearch(''); + }} + showSearch={{ searchValue: search, onSearch: setSearch, filterOption: false }} + notFoundContent={{status}} + popupRender={(menu) => ( + <> + {menu} + {showStatusInMenu && status && ( +
+ {status} +
+ )} + + )} + options={options} + /> + + ); +} + export default function RuleFormModal({ open, rule, @@ -86,21 +153,6 @@ export default function RuleFormModal({ const { data: inboundOptions } = useInboundOptions(); const remarkByTag = useMemo(() => buildRemarkByTag(inboundOptions || []), [inboundOptions]); - const { - data: clientEmails = [], - isFetching: clientsLoading, - isError: clientsError, - } = useClientOptions(open); - const user = useWatch({ control: methods.control, name: 'user' }) ?? ''; - const selectedUsers = useMemo(() => csv(user), [user]); - const userOptions = useMemo( - () => - [...new Set([...clientEmails, ...selectedUsers])].map((email) => ({ - value: email, - label: email, - })), - [clientEmails, selectedUsers], - ); useEffect(() => { if (!open) return; @@ -286,33 +338,7 @@ export default function RuleFormModal({ - csv(typeof value === 'string' ? value : ''), - output: (value) => (Array.isArray(value) ? value.join(',') : ''), - }} - > - } - aria-label={t('search')} - placeholder={t('pages.nodes.fleet.searchNodes')} - allowClear - value={search} - onChange={(event) => setSearch(event.target.value)} - /> - } + aria-label={t('search')} + placeholder={t('pages.nodes.fleet.searchNodes')} + allowClear + value={search} + onChange={(event) => setSearch(event.target.value)} + /> + } aria-label={t('search')} placeholder={t('pages.nodes.fleet.searchNodes')} @@ -1071,6 +1060,7 @@ export default function NodeList({ onChange={(event) => setSearch(event.target.value)} />