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