mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-05 08:44:48 +03:00
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.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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}',
|
||||
},
|
||||
|
||||
@@ -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: [
|
||||
|
||||
@@ -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({
|
||||
<Tag color="green" className="client-count-tag">
|
||||
{clientCount[record.id].clients}
|
||||
</Tag>
|
||||
{clientCount[record.id].onlineAttribution &&
|
||||
clientCount[record.id].online.length === 0 && (
|
||||
<Tag>
|
||||
{t('online')}: {onlineStatusLabel(clientCount[record.id], t)}
|
||||
</Tag>
|
||||
)}
|
||||
{clientCount[record.id].online.length > 0 && (
|
||||
<Tag color="blue">
|
||||
{clientCount[record.id].online.length} {t('online')}
|
||||
{clientCount[record.id].onlineAttribution === 'node' &&
|
||||
` (${t('pages.inbounds.node')})`}
|
||||
</Tag>
|
||||
)}
|
||||
{clientCount[record.id].depleted.length > 0 && (
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ export interface ClientCountEntry {
|
||||
depleted: string[];
|
||||
expiring: string[];
|
||||
online: string[];
|
||||
onlineAttribution?: 'pending' | 'unavailable' | 'inbound' | 'node' | 'unsupported';
|
||||
}
|
||||
|
||||
export interface InboundSpeedEntry {
|
||||
|
||||
@@ -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({
|
||||
</Tag>
|
||||
</Popover>
|
||||
)}
|
||||
{cc.onlineAttribution && cc.online.length === 0 && (
|
||||
<Tag className="client-count-tag" style={{ margin: 0, padding: '0 2px' }}>
|
||||
{t('online')}: {onlineStatusLabel(cc, t)}
|
||||
</Tag>
|
||||
)}
|
||||
{cc.online.length > 0 && (
|
||||
<Popover
|
||||
title={t('online')}
|
||||
title={
|
||||
cc.onlineAttribution === 'node'
|
||||
? `${t('online')} (${t('pages.inbounds.node')})`
|
||||
: t('online')
|
||||
}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{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')})`}
|
||||
</Tag>
|
||||
</Popover>
|
||||
)}
|
||||
|
||||
@@ -54,6 +54,7 @@ interface ClientRollup {
|
||||
depleted: string[];
|
||||
expiring: string[];
|
||||
online: string[];
|
||||
onlineAttribution: 'pending' | 'unavailable' | 'inbound' | 'node' | 'unsupported';
|
||||
comments: Map<string, string>;
|
||||
}
|
||||
|
||||
@@ -101,12 +102,12 @@ async function fetchOnlineClientsByGuid(): Promise<Record<string, string[]>> {
|
||||
// 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<Record<string, string[]>> {
|
||||
async function fetchActiveInboundsByNode(): Promise<Record<string, string[] | null>> {
|
||||
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<string, string[]>)
|
||||
? (validated.obj as Record<string, string[] | null>)
|
||||
: {};
|
||||
}
|
||||
|
||||
@@ -119,13 +120,28 @@ function toGuidOnlineMap(data: Record<string, string[]>): Map<string, Set<string
|
||||
return map;
|
||||
}
|
||||
|
||||
function toActiveInboundMap(
|
||||
data: Record<string, string[] | null>,
|
||||
): Map<string, Set<string> | null> {
|
||||
const map = new Map<string, Set<string> | null>();
|
||||
for (const [key, tags] of Object.entries(data)) {
|
||||
if (tags === null) map.set(key, null);
|
||||
else if (Array.isArray(tags)) map.set(key, new Set(tags));
|
||||
}
|
||||
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<string, Set<string>>, b: Map<string, Set<string>>): boolean {
|
||||
function sameGuidSets(
|
||||
a: ReadonlyMap<string, Set<string> | null>,
|
||||
b: ReadonlyMap<string, Set<string> | null>,
|
||||
): boolean {
|
||||
if (a.size !== b.size) return false;
|
||||
for (const [key, set] of b) {
|
||||
const prev = a.get(key);
|
||||
if (!prev || 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<Map<string, Set<string>>>(() => 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<Map<string, Set<string>>>(() => new Map());
|
||||
// An explicit empty set is an idle node. A missing set has no usable activity sample.
|
||||
const [activeByGuid, setActiveByGuid] = useState<Map<string, Set<string> | null>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const onlinePending = onlinesByGuidQuery.isPending || activeInboundsQuery.isPending;
|
||||
|
||||
const [lastOnlineMap, setLastOnlineMap] = useState<Record<string, number>>({});
|
||||
|
||||
@@ -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<unknown>();
|
||||
if (activeInboundsQuery.data && activeInboundsQuery.data !== syncedActiveInbounds) {
|
||||
setSyncedActiveInbounds(activeInboundsQuery.data);
|
||||
setActiveByGuid(toGuidOnlineMap(activeInboundsQuery.data));
|
||||
setActiveByGuid(toActiveInboundMap(activeInboundsQuery.data));
|
||||
}
|
||||
|
||||
const [syncedLastOnline, setSyncedLastOnline] = useState<unknown>();
|
||||
@@ -443,7 +467,7 @@ export function useInbounds() {
|
||||
nodeTraffics?: TrafficDelta[];
|
||||
onlineClients?: string[];
|
||||
onlineByGuid?: Record<string, string[]>;
|
||||
activeInbounds?: Record<string, string[]>;
|
||||
activeInbounds?: Record<string, string[] | null>;
|
||||
lastOnlineMap?: Record<string, number>;
|
||||
};
|
||||
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') {
|
||||
|
||||
@@ -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 ?? {});
|
||||
|
||||
|
||||
@@ -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 }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
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<string, string[]>,
|
||||
activeInbounds: Record<string, string[] | null>,
|
||||
) => 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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+111
-82
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user