From 1ec55aed30cda887063d27ad85c2e4ec4b57bc7b Mon Sep 17 00:00:00 2001 From: Hamed Date: Sun, 29 Nov 2026 18:38:51 +0330 Subject: [PATCH] perf(node-sync): avoid redundant full inbound snapshots (#7014) Every five seconds the master fetched each node's complete inbound list, settings JSON and enrichment included, parsed it and reconciled every client, whether anything had changed or not. A node that advertises traffic-snapshot-v1 now answers a revisioned endpoint: counters and lifecycle state on every poll, inbound configuration and attachments only when its revision changed. The master skips structural parsing and client reconciliation while the node's revision, its own rows for that node, the lifecycle state and the full remote-to-central inbound mapping are all unchanged; anything else falls back to the full merge. Old and new panels keep talking through the previous endpoints. Revisions come from a hidden per-row token on inbounds and clients, maintained by database triggers on SQLite and PostgreSQL so that direct and background writes count too. Counter and timestamp updates leave it alone. The triggers are dropped before migrations and recreated after them, and the previous build runs unchanged on a database that carries them. Measured here at 20,000 clients on one node, per idle poll: master SQL statements 551 -> 44, node statements 55 -> 4, transfer 23.0 MB -> 4.8 MB. When every client is shared between nodes the ownership checks keep the full master merge, so only the node and the transfer get cheaper. The node still reads every membership and counter on each poll. Closes #7007 --- .github/workflows/ci.yml | 24 +- .../docs/en/reference/api/inbounds.mdx | 15 +- docs/public/openapi.json | 299 +++++ frontend/public/openapi.json | 299 +++++ frontend/src/generated/examples.ts | 72 ++ frontend/src/generated/schemas.ts | 217 ++++ frontend/src/generated/types.ts | 46 + frontend/src/generated/zod.ts | 53 + frontend/src/pages/api-docs/endpoints.ts | 16 + internal/database/db.go | 17 +- ..._preserve_client_traffic_migration_test.go | 10 + internal/database/model/model.go | 2 + internal/database/snapshot_revision.go | 91 ++ .../snapshot_revision_catalog_bench_test.go | 63 + .../database/snapshot_revision_ddl_test.go | 293 +++++ internal/database/snapshot_revision_test.go | 142 +++ internal/nodee2e/node_snapshot_test.go | 141 +++ internal/util/json_util/list.go | 53 + internal/util/json_util/list_count_test.go | 40 + internal/util/wirecodec/wirecodec.go | 4 +- internal/web/controller/api.go | 1 + internal/web/controller/inbound.go | 16 + internal/web/controller/node_snapshot_test.go | 64 + internal/web/job/node_traffic_sync_job.go | 11 +- internal/web/node_contract_test.go | 12 +- internal/web/runtime/node_snapshot.go | 245 ++++ .../web/runtime/node_snapshot_config_test.go | 20 + internal/web/runtime/node_snapshot_decode.go | 143 +++ .../web/runtime/node_snapshot_limits_test.go | 180 +++ .../runtime/node_snapshot_malformed_test.go | 73 ++ internal/web/runtime/remote.go | 38 +- internal/web/runtime/remote_snapshot_test.go | 196 ++++ internal/web/service/inbound.go | 12 +- internal/web/service/inbound_node.go | 1039 +++++++++-------- internal/web/service/node_snapshot.go | 127 ++ .../web/service/node_snapshot_alias_test.go | 224 ++++ .../service/node_snapshot_cycle_scale_test.go | 355 ++++++ internal/web/service/node_snapshot_merge.go | 179 +++ .../web/service/node_snapshot_scale_test.go | 149 +++ internal/web/service/node_snapshot_test.go | 306 +++++ tools/openapigen/main.go | 4 + 41 files changed, 4813 insertions(+), 478 deletions(-) create mode 100644 internal/database/snapshot_revision.go create mode 100644 internal/database/snapshot_revision_catalog_bench_test.go create mode 100644 internal/database/snapshot_revision_ddl_test.go create mode 100644 internal/database/snapshot_revision_test.go create mode 100644 internal/nodee2e/node_snapshot_test.go create mode 100644 internal/util/json_util/list_count_test.go create mode 100644 internal/web/controller/node_snapshot_test.go create mode 100644 internal/web/runtime/node_snapshot.go create mode 100644 internal/web/runtime/node_snapshot_config_test.go create mode 100644 internal/web/runtime/node_snapshot_decode.go create mode 100644 internal/web/runtime/node_snapshot_limits_test.go create mode 100644 internal/web/runtime/node_snapshot_malformed_test.go create mode 100644 internal/web/runtime/remote_snapshot_test.go create mode 100644 internal/web/service/node_snapshot.go create mode 100644 internal/web/service/node_snapshot_alias_test.go create mode 100644 internal/web/service/node_snapshot_cycle_scale_test.go create mode 100644 internal/web/service/node_snapshot_merge.go create mode 100644 internal/web/service/node_snapshot_scale_test.go create mode 100644 internal/web/service/node_snapshot_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 799b02296..e3a2bc683 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,8 @@ jobs: - name: Test run: | go list ./... | grep -v '/frontend/node_modules/' > /tmp/go-packages.txt - go test -shuffle=on -count=1 $(cat /tmp/go-packages.txt) + mapfile -t go_packages < /tmp/go-packages.txt + go test -shuffle=on -count=1 "${go_packages[@]}" postgres-durable-first: runs-on: ubuntu-latest @@ -193,6 +194,16 @@ jobs: exit 1 fi + - name: PostgreSQL node snapshot regressions + run: | + set -o pipefail + go test -p=1 ./internal/database ./internal/web/service -run '^(TestSnapshotRevisionsDirectWritesAndRollback|TestNodeSnapshotUnchangedAvoidsSettingsAndDetectsDirectEdits|TestNodeSnapshotMergeSkipsUnchangedStructureAndPreservesDeltas|TestNodeSnapshotReadDoesNotHoldTrafficWriter|TestNodeSnapshotCanceledReadReleasesConnection|TestNodeSnapshotReopenInvalidatesCatalog|TestNodeSnapshotCachedAliasPreservesTraffic|TestNodeSnapshotAliasInvalidCacheFallsBack|TestNodeSnapshotAliasValidatesEntireMapping|TestNodeSnapshotAliasQuotaDisableAndRenewal|TestSnapshotRevisionPostgresTypeDDL|TestSnapshotRevisionMigrationRecreationAndReopen)$' -count=1 -v | tee /tmp/postgres-node-snapshot.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-snapshot.log || true) + if [ "$passed" -ne 12 ]; then + echo "expected 12 passing node snapshot tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL schema and migration tests run: | set -o pipefail @@ -323,7 +334,8 @@ jobs: run: | go list ./... | grep -v '/frontend/node_modules/' > /tmp/go-packages.txt # internal/web/service runs ~10x slower under -race and overruns the 10m default. - go test -race -shuffle=on -count=1 -timeout 25m $(cat /tmp/go-packages.txt) + mapfile -t go_packages < /tmp/go-packages.txt + go test -race -shuffle=on -count=1 -timeout 25m "${go_packages[@]}" # A real master and node panel, each its own process, driven through node sync. # A SKIP here means the binary was never handed over, so it fails the job. @@ -335,6 +347,14 @@ jobs: with: go-version-file: go.mod cache: true + - name: Build legacy node protocol baseline + run: | + baseline_ref=c621ba9014a6aa21fd7c9ecf45655e44e24ebf13 + git fetch --no-tags --depth=1 origin "$baseline_ref" + baseline_src=$(mktemp -d) + git archive "$baseline_ref" Makefile go.mod go.sum main.go internal scripts/install-amneziawg-kernel.sh | tar -x -C "$baseline_src" + (cd "$baseline_src" && make dist-stub && go build -o "$RUNNER_TEMP/x-ui-node-baseline" .) + echo "XUI_NODE_E2E_OLD_BINARY=$RUNNER_TEMP/x-ui-node-baseline" >> "$GITHUB_ENV" - name: Master + node end to end run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/inbounds.mdx b/docs/content/docs/en/reference/api/inbounds.mdx index 4eefa83b1..165dc5fd8 100644 --- a/docs/content/docs/en/reference/api/inbounds.mdx +++ b/docs/content/docs/en/reference/api/inbounds.mdx @@ -16,6 +16,13 @@ _openapi: legacy callers that send them back as JSON-encoded strings are still accepted on write. url: '#list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write' + - depth: 2 + title: 'Internal node sync v1: complete raw local counters and online state on + every poll. Send the last validated revision to omit unchanged + structure. Omitted structure requires a matching cached catalog; a + present structure with empty arrays is authoritative. Uses admin, + node-admin or node-sync authorization.' + url: '#internal-node-sync-v1-complete-raw-local-counters-and-online-state-on-every-poll-send-the-last-validated-revision-to-omit-unchanged-structure-omitted-structure-requires-a-matching-cached-catalog-a-present-structure-with-empty-arrays-is-authoritative-uses-admin-node-admin-or-node-sync-authorization' - depth: 2 title: Same shape as /list but with settings.clients[] stripped down to {email, enable, comment} and ClientStats not enriched with UUID/SubId. Use this @@ -130,6 +137,12 @@ _openapi: legacy callers that send them back as JSON-encoded strings are still accepted on write. id: list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write + - content: 'Internal node sync v1: complete raw local counters and online state on + every poll. Send the last validated revision to omit unchanged + structure. Omitted structure requires a matching cached catalog; a + present structure with empty arrays is authoritative. Uses admin, + node-admin or node-sync authorization.' + id: internal-node-sync-v1-complete-raw-local-counters-and-online-state-on-every-poll-send-the-last-validated-revision-to-omit-unchanged-structure-omitted-structure-requires-a-matching-cached-catalog-a-present-structure-with-empty-arrays-is-authoritative-uses-admin-node-admin-or-node-sync-authorization - content: Same shape as /list but with settings.clients[] stripped down to {email, enable, comment} and ClientStats not enriched with UUID/SubId. Use this for list pages; fetch /get/:id when you need the full @@ -228,7 +241,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index bb735ee53..4877ccf2d 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -4587,6 +4587,105 @@ ], "type": "object" }, + "NodeClientTraffic": { + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "expiryTime": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "id": { + "example": 14825, + "type": "integer" + }, + "inboundId": { + "example": 1, + "type": "integer" + }, + "lastOnline": { + "example": 1735680000000, + "format": "int64", + "type": "integer" + }, + "reset": { + "type": "integer" + }, + "resetCount": { + "type": "integer" + }, + "resetDay": { + "type": "integer" + }, + "resetMax": { + "type": "integer" + }, + "resetWeekday": { + "type": "integer" + }, + "total": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "email", + "enable", + "expiryTime", + "id", + "inboundId", + "lastOnline", + "reset", + "resetCount", + "resetDay", + "resetMax", + "resetWeekday", + "total", + "up" + ], + "type": "object" + }, + "NodeInboundTraffic": { + "properties": { + "down": { + "format": "int64", + "type": "integer" + }, + "id": { + "example": 1, + "type": "integer" + }, + "up": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "id", + "up" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -4677,6 +4776,124 @@ ], "type": "object" }, + "NodeSnapshotAttachment": { + "properties": { + "email": { + "example": "user1", + "type": "string" + }, + "inboundId": { + "example": 1, + "type": "integer" + } + }, + "required": [ + "email", + "inboundId" + ], + "type": "object" + }, + "NodeSnapshotStructure": { + "properties": { + "attachments": { + "items": { + "$ref": "#/components/schemas/NodeSnapshotAttachment" + }, + "type": "array" + }, + "inbounds": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Inbound" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "attachments", + "inbounds" + ], + "type": "object" + }, + "NodeTrafficSnapshotV1": { + "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", + "properties": { + "activeInboundTree": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "clients": { + "items": { + "$ref": "#/components/schemas/NodeClientTraffic" + }, + "type": "array" + }, + "inboundTraffic": { + "items": { + "$ref": "#/components/schemas/NodeInboundTraffic" + }, + "type": "array" + }, + "lastOnlineMap": { + "additionalProperties": { + "format": "int64", + "type": "integer" + }, + "type": "object" + }, + "onlineEmails": { + "items": { + "type": "string" + }, + "type": "array" + }, + "onlineTree": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "revision": { + "example": "0000000000000000000000000000000000000000000000000000000000000001", + "type": "string" + }, + "structure": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeSnapshotStructure" + } + ], + "nullable": true + }, + "version": { + "example": 1, + "type": "integer" + } + }, + "required": [ + "activeInboundTree", + "clients", + "inboundTraffic", + "lastOnlineMap", + "onlineEmails", + "onlineTree", + "revision", + "version" + ], + "type": "object" + }, "NodeView": { "description": "NodeView is the browser/API read contract for nodes. Credentials are\nwrite-only: responses expose only whether a node has a token configured.", "properties": { @@ -6553,6 +6770,88 @@ } } }, + "/panel/api/inbounds/trafficSnapshot": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "Internal node sync v1: complete raw local counters and online state on every poll. Send the last validated revision to omit unchanged structure. Omitted structure requires a matching cached catalog; a present structure with empty arrays is authoritative. Uses admin, node-admin or node-sync authorization.", + "operationId": "get_panel_api_inbounds_trafficSnapshot", + "parameters": [ + { + "name": "revision", + "in": "query", + "required": false, + "description": "Opaque revision of the last validated complete catalog. Omit when no catalog is cached.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeTrafficSnapshotV1" + } + } + }, + "example": { + "success": true, + "obj": { + "activeInboundTree": {}, + "clients": [ + { + "down": 2097152, + "email": "user1", + "enable": true, + "expiryTime": 1735689600000, + "id": 14825, + "inboundId": 1, + "lastOnline": 1735680000000, + "reset": 0, + "resetCount": 0, + "resetDay": 0, + "resetMax": 0, + "resetWeekday": 0, + "total": 10737418240, + "up": 1048576 + } + ], + "inboundTraffic": [ + { + "down": 0, + "id": 1, + "up": 0 + } + ], + "lastOnlineMap": {}, + "onlineEmails": [ + "" + ], + "onlineTree": {}, + "revision": "0000000000000000000000000000000000000000000000000000000000000001", + "structure": null, + "version": 1 + } + } + } + } + } + } + } + }, "/panel/api/inbounds/list/slim": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index bb735ee53..4877ccf2d 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -4587,6 +4587,105 @@ ], "type": "object" }, + "NodeClientTraffic": { + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "expiryTime": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "id": { + "example": 14825, + "type": "integer" + }, + "inboundId": { + "example": 1, + "type": "integer" + }, + "lastOnline": { + "example": 1735680000000, + "format": "int64", + "type": "integer" + }, + "reset": { + "type": "integer" + }, + "resetCount": { + "type": "integer" + }, + "resetDay": { + "type": "integer" + }, + "resetMax": { + "type": "integer" + }, + "resetWeekday": { + "type": "integer" + }, + "total": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "email", + "enable", + "expiryTime", + "id", + "inboundId", + "lastOnline", + "reset", + "resetCount", + "resetDay", + "resetMax", + "resetWeekday", + "total", + "up" + ], + "type": "object" + }, + "NodeInboundTraffic": { + "properties": { + "down": { + "format": "int64", + "type": "integer" + }, + "id": { + "example": 1, + "type": "integer" + }, + "up": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "id", + "up" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -4677,6 +4776,124 @@ ], "type": "object" }, + "NodeSnapshotAttachment": { + "properties": { + "email": { + "example": "user1", + "type": "string" + }, + "inboundId": { + "example": 1, + "type": "integer" + } + }, + "required": [ + "email", + "inboundId" + ], + "type": "object" + }, + "NodeSnapshotStructure": { + "properties": { + "attachments": { + "items": { + "$ref": "#/components/schemas/NodeSnapshotAttachment" + }, + "type": "array" + }, + "inbounds": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Inbound" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "attachments", + "inbounds" + ], + "type": "object" + }, + "NodeTrafficSnapshotV1": { + "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", + "properties": { + "activeInboundTree": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "clients": { + "items": { + "$ref": "#/components/schemas/NodeClientTraffic" + }, + "type": "array" + }, + "inboundTraffic": { + "items": { + "$ref": "#/components/schemas/NodeInboundTraffic" + }, + "type": "array" + }, + "lastOnlineMap": { + "additionalProperties": { + "format": "int64", + "type": "integer" + }, + "type": "object" + }, + "onlineEmails": { + "items": { + "type": "string" + }, + "type": "array" + }, + "onlineTree": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "revision": { + "example": "0000000000000000000000000000000000000000000000000000000000000001", + "type": "string" + }, + "structure": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeSnapshotStructure" + } + ], + "nullable": true + }, + "version": { + "example": 1, + "type": "integer" + } + }, + "required": [ + "activeInboundTree", + "clients", + "inboundTraffic", + "lastOnlineMap", + "onlineEmails", + "onlineTree", + "revision", + "version" + ], + "type": "object" + }, "NodeView": { "description": "NodeView is the browser/API read contract for nodes. Credentials are\nwrite-only: responses expose only whether a node has a token configured.", "properties": { @@ -6553,6 +6770,88 @@ } } }, + "/panel/api/inbounds/trafficSnapshot": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "Internal node sync v1: complete raw local counters and online state on every poll. Send the last validated revision to omit unchanged structure. Omitted structure requires a matching cached catalog; a present structure with empty arrays is authoritative. Uses admin, node-admin or node-sync authorization.", + "operationId": "get_panel_api_inbounds_trafficSnapshot", + "parameters": [ + { + "name": "revision", + "in": "query", + "required": false, + "description": "Opaque revision of the last validated complete catalog. Omit when no catalog is cached.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeTrafficSnapshotV1" + } + } + }, + "example": { + "success": true, + "obj": { + "activeInboundTree": {}, + "clients": [ + { + "down": 2097152, + "email": "user1", + "enable": true, + "expiryTime": 1735689600000, + "id": 14825, + "inboundId": 1, + "lastOnline": 1735680000000, + "reset": 0, + "resetCount": 0, + "resetDay": 0, + "resetMax": 0, + "resetWeekday": 0, + "total": 10737418240, + "up": 1048576 + } + ], + "inboundTraffic": [ + { + "down": 0, + "id": 1, + "up": 0 + } + ], + "lastOnlineMap": {}, + "onlineEmails": [ + "" + ], + "onlineTree": {}, + "revision": "0000000000000000000000000000000000000000000000000000000000000001", + "structure": null, + "version": 1 + } + } + } + } + } + } + } + }, "/panel/api/inbounds/list/slim": { "get": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index c25602e7d..081067ac9 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1184,6 +1184,27 @@ export const EXAMPLES: Record = { "xrayState": "", "xrayVersion": "25.10.31" }, + "NodeClientTraffic": { + "down": 2097152, + "email": "user1", + "enable": true, + "expiryTime": 1735689600000, + "id": 14825, + "inboundId": 1, + "lastOnline": 1735680000000, + "reset": 0, + "resetCount": 0, + "resetDay": 0, + "resetMax": 0, + "resetWeekday": 0, + "total": 10737418240, + "up": 1048576 + }, + "NodeInboundTraffic": { + "down": 0, + "id": 1, + "up": 0 + }, "NodeMutationRequest": { "address": "", "allowPrivateAddress": false, @@ -1204,6 +1225,57 @@ export const EXAMPLES: Record = { "scheme": "http", "tlsVerifyMode": "verify" }, + "NodeSnapshotAttachment": { + "email": "user1", + "inboundId": 1 + }, + "NodeSnapshotStructure": { + "attachments": [ + { + "email": "user1", + "inboundId": 1 + } + ], + "inbounds": [ + null + ] + }, + "NodeTrafficSnapshotV1": { + "activeInboundTree": {}, + "clients": [ + { + "down": 2097152, + "email": "user1", + "enable": true, + "expiryTime": 1735689600000, + "id": 14825, + "inboundId": 1, + "lastOnline": 1735680000000, + "reset": 0, + "resetCount": 0, + "resetDay": 0, + "resetMax": 0, + "resetWeekday": 0, + "total": 10737418240, + "up": 1048576 + } + ], + "inboundTraffic": [ + { + "down": 0, + "id": 1, + "up": 0 + } + ], + "lastOnlineMap": {}, + "onlineEmails": [ + "" + ], + "onlineTree": {}, + "revision": "0000000000000000000000000000000000000000000000000000000000000001", + "structure": null, + "version": 1 + }, "NodeView": { "activeCount": 20, "address": "node.example.com", diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index f243fe1cb..e5b7085f6 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -4561,6 +4561,105 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeClientTraffic": { + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "expiryTime": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "id": { + "example": 14825, + "type": "integer" + }, + "inboundId": { + "example": 1, + "type": "integer" + }, + "lastOnline": { + "example": 1735680000000, + "format": "int64", + "type": "integer" + }, + "reset": { + "type": "integer" + }, + "resetCount": { + "type": "integer" + }, + "resetDay": { + "type": "integer" + }, + "resetMax": { + "type": "integer" + }, + "resetWeekday": { + "type": "integer" + }, + "total": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "email", + "enable", + "expiryTime", + "id", + "inboundId", + "lastOnline", + "reset", + "resetCount", + "resetDay", + "resetMax", + "resetWeekday", + "total", + "up" + ], + "type": "object" + }, + "NodeInboundTraffic": { + "properties": { + "down": { + "format": "int64", + "type": "integer" + }, + "id": { + "example": 1, + "type": "integer" + }, + "up": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "id", + "up" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -4651,6 +4750,124 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeSnapshotAttachment": { + "properties": { + "email": { + "example": "user1", + "type": "string" + }, + "inboundId": { + "example": 1, + "type": "integer" + } + }, + "required": [ + "email", + "inboundId" + ], + "type": "object" + }, + "NodeSnapshotStructure": { + "properties": { + "attachments": { + "items": { + "$ref": "#/components/schemas/NodeSnapshotAttachment" + }, + "type": "array" + }, + "inbounds": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/Inbound" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "attachments", + "inbounds" + ], + "type": "object" + }, + "NodeTrafficSnapshotV1": { + "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", + "properties": { + "activeInboundTree": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "clients": { + "items": { + "$ref": "#/components/schemas/NodeClientTraffic" + }, + "type": "array" + }, + "inboundTraffic": { + "items": { + "$ref": "#/components/schemas/NodeInboundTraffic" + }, + "type": "array" + }, + "lastOnlineMap": { + "additionalProperties": { + "format": "int64", + "type": "integer" + }, + "type": "object" + }, + "onlineEmails": { + "items": { + "type": "string" + }, + "type": "array" + }, + "onlineTree": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "revision": { + "example": "0000000000000000000000000000000000000000000000000000000000000001", + "type": "string" + }, + "structure": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeSnapshotStructure" + } + ], + "nullable": true + }, + "version": { + "example": 1, + "type": "integer" + } + }, + "required": [ + "activeInboundTree", + "clients", + "inboundTraffic", + "lastOnlineMap", + "onlineEmails", + "onlineTree", + "revision", + "version" + ], + "type": "object" + }, "NodeView": { "description": "NodeView is the browser/API read contract for nodes. Credentials are\nwrite-only: responses expose only whether a node has a token configured.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 04e1c4ff6..5bf30b7ce 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1,6 +1,7 @@ // Code generated by tools/openapigen. DO NOT EDIT. export type BlockerCode = string; export type GeoKind = string; +export type MasterClientCertProvider = unknown; export type OnlineAPISupport = number; export type ProcessState = string; export type Protocol = string; @@ -1036,6 +1037,29 @@ export interface Node { xrayVersion: string; } +export interface NodeClientTraffic { + down: number; + email: string; + enable: boolean; + expiryTime: number; + id: number; + inboundId: number; + lastOnline: number; + reset: number; + resetCount: number; + resetDay: number; + resetMax: number; + resetWeekday: number; + total: number; + up: number; +} + +export interface NodeInboundTraffic { + down: number; + id: number; + up: number; +} + export interface NodeMutationRequest { address: string; allowPrivateAddress: boolean; @@ -1055,6 +1079,28 @@ export interface NodeMutationRequest { tlsVerifyMode: string; } +export interface NodeSnapshotAttachment { + email: string; + inboundId: number; +} + +export interface NodeSnapshotStructure { + attachments: NodeSnapshotAttachment[]; + inbounds: Inbound | null[]; +} + +export interface NodeTrafficSnapshotV1 { + activeInboundTree: Record; + clients: NodeClientTraffic[]; + inboundTraffic: NodeInboundTraffic[]; + lastOnlineMap: Record; + onlineEmails: string[]; + onlineTree: Record; + revision: string; + structure?: NodeSnapshotStructure | null; + version: number; +} + export interface NodeView { activeCount: number; address: string; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 9f88ee452..91489537e 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -6,6 +6,9 @@ export type BlockerCode = z.infer; export const GeoKindSchema = z.string(); export type GeoKind = z.infer; +export const MasterClientCertProviderSchema = z.unknown(); +export type MasterClientCertProvider = z.infer; + export const OnlineAPISupportSchema = z.number().int(); export type OnlineAPISupport = z.infer; @@ -1100,6 +1103,31 @@ export const NodeSchema = z.object({ }); export type Node = z.infer; +export const NodeClientTrafficSchema = z.object({ + down: z.number().int(), + email: z.string(), + enable: z.boolean(), + expiryTime: z.number().int(), + id: z.number().int(), + inboundId: z.number().int(), + lastOnline: z.number().int(), + reset: z.number().int(), + resetCount: z.number().int(), + resetDay: z.number().int(), + resetMax: z.number().int(), + resetWeekday: z.number().int(), + total: z.number().int(), + up: z.number().int(), +}); +export type NodeClientTraffic = z.infer; + +export const NodeInboundTrafficSchema = z.object({ + down: z.number().int(), + id: z.number().int(), + up: z.number().int(), +}); +export type NodeInboundTraffic = z.infer; + export const NodeMutationRequestSchema = z.object({ address: z.string(), allowPrivateAddress: z.boolean(), @@ -1120,6 +1148,31 @@ export const NodeMutationRequestSchema = z.object({ }); export type NodeMutationRequest = z.infer; +export const NodeSnapshotAttachmentSchema = z.object({ + email: z.string(), + inboundId: z.number().int(), +}); +export type NodeSnapshotAttachment = z.infer; + +export const NodeSnapshotStructureSchema = z.object({ + attachments: z.array(z.lazy(() => NodeSnapshotAttachmentSchema)), + inbounds: z.array(z.lazy(() => InboundSchema).nullable()), +}); +export type NodeSnapshotStructure = z.infer; + +export const NodeTrafficSnapshotV1Schema = z.object({ + activeInboundTree: z.record(z.string(), z.array(z.string())), + clients: z.array(z.lazy(() => NodeClientTrafficSchema)), + inboundTraffic: z.array(z.lazy(() => NodeInboundTrafficSchema)), + lastOnlineMap: z.record(z.string(), z.number().int()), + onlineEmails: z.array(z.string()), + onlineTree: z.record(z.string(), z.array(z.string())), + revision: z.string(), + structure: z.lazy(() => NodeSnapshotStructureSchema).nullable().optional(), + version: z.number().int(), +}); +export type NodeTrafficSnapshotV1 = z.infer; + export const NodeViewSchema = z.object({ activeCount: z.number().int(), address: z.string(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 88748591e..8eb435b29 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -267,6 +267,22 @@ export const sections: readonly Section[] = [ responseSchema: 'Inbound', responseSchemaArray: true, }, + { + method: 'GET', + path: '/panel/api/inbounds/trafficSnapshot', + summary: + 'Internal node sync v1: complete raw local counters and online state on every poll. Send the last validated revision to omit unchanged structure. Omitted structure requires a matching cached catalog; a present structure with empty arrays is authoritative. Uses admin, node-admin or node-sync authorization.', + params: [ + { + name: 'revision', + in: 'query', + type: 'string', + optional: true, + desc: 'Opaque revision of the last validated complete catalog. Omit when no catalog is cached.', + }, + ], + responseSchema: 'NodeTrafficSnapshotV1', + }, { method: 'GET', path: '/panel/api/inbounds/list/slim', diff --git a/internal/database/db.go b/internal/database/db.go index ea4541bd5..666f737da 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -19,6 +19,7 @@ import ( "slices" "strconv" "strings" + "sync/atomic" "time" "github.com/mhsanaei/3x-ui/v3/internal/config" @@ -38,6 +39,11 @@ import ( var db *gorm.DB +var connectionGeneration atomic.Uint64 + +// ConnectionGeneration invalidates read histories when InitDB replaces the database pool. +func ConnectionGeneration() uint64 { return connectionGeneration.Load() } + var backupSQLiteTimeout = 2 * time.Minute const ( @@ -143,6 +149,9 @@ func migrateClientKeepAliveRangeColumn() error { } func initModels() error { + if err := dropSnapshotRevisionTriggers(db); err != nil { + return err + } if err := migrateClientKeepAliveRangeColumn(); err != nil { return err } @@ -247,7 +256,7 @@ func initModels() error { return err } } - return nil + return migrateSnapshotRevisions(db) } func postgresModelSettled(mdl any) bool { @@ -3575,7 +3584,11 @@ func InitDB(dbPath string) error { return err } } - return runSeeders(isUsersEmpty) + if err := runSeeders(isUsersEmpty); err != nil { + return err + } + connectionGeneration.Add(1) + return nil } func normalizeApiTokenCreatedAtSeconds() error { diff --git a/internal/database/inbound_preserve_client_traffic_migration_test.go b/internal/database/inbound_preserve_client_traffic_migration_test.go index c5f0f1b80..e798010e6 100644 --- a/internal/database/inbound_preserve_client_traffic_migration_test.go +++ b/internal/database/inbound_preserve_client_traffic_migration_test.go @@ -15,6 +15,9 @@ func TestMigrateInboundPreserveClientTrafficColumn(t *testing.T) { t.Cleanup(func() { tx.Rollback() }) // Recreate the previous schema in this transaction on SQLite or PostgreSQL. + if err := dropSnapshotRevisionTriggers(tx); err != nil { + t.Fatal(err) + } if err := tx.Exec("ALTER TABLE inbounds DROP COLUMN preserve_client_traffic").Error; err != nil { t.Fatal(err) } @@ -25,6 +28,9 @@ func TestMigrateInboundPreserveClientTrafficColumn(t *testing.T) { if err := migrateInboundPreserveClientTrafficColumn(tx); err != nil { t.Fatal(err) } + if err := migrateSnapshotRevisions(tx); err != nil { + t.Fatal(err) + } var stored model.Inbound if err := tx.Where("tag = ?", tag).First(&stored).Error; err != nil { t.Fatal(err) @@ -35,6 +41,7 @@ func TestMigrateInboundPreserveClientTrafficColumn(t *testing.T) { if stored.Up != 30 || stored.Down != 50 || stored.TrafficReset != "monthly" || stored.TrafficResetDay != 20 { t.Fatalf("legacy inbound after migration: up=%d down=%d schedule=%s day=%d", stored.Up, stored.Down, stored.TrafficReset, stored.TrafficResetDay) } + revision := stored.SnapshotRevision if err := tx.Model(&stored).Update("preserve_client_traffic", true).Error; err != nil { t.Fatal(err) } @@ -44,4 +51,7 @@ func TestMigrateInboundPreserveClientTrafficColumn(t *testing.T) { if err := tx.First(&stored, stored.Id).Error; err != nil || !stored.PreservesClientTraffic() { t.Fatalf("repeat migration lost the opt-in: preserve=%t, err=%v", stored.PreservesClientTraffic(), err) } + if revision == "" || stored.SnapshotRevision == "" || stored.SnapshotRevision == revision { + t.Fatalf("changing preserved traffic must update the snapshot revision: %q -> %q", revision, stored.SnapshotRevision) + } } diff --git a/internal/database/model/model.go b/internal/database/model/model.go index 9e733e5e0..8c1c6f657 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -51,6 +51,7 @@ type User struct { // Inbound represents an Xray inbound configuration with traffic statistics and settings. type Inbound struct { + SnapshotRevision string `json:"-" gorm:"->;not null;default:''"` Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement" example:"1"` // Unique identifier UserId int `json:"-"` // Associated user ID Up int64 `json:"up" form:"up"` // Upload traffic in bytes @@ -1037,6 +1038,7 @@ type Client struct { } type ClientRecord struct { + SnapshotRevision string `json:"-" gorm:"->;not null;default:''"` Id int `json:"id" gorm:"primaryKey;autoIncrement"` Email string `json:"email" gorm:"uniqueIndex;not null"` SubID string `json:"subId" gorm:"index;column:sub_id"` diff --git a/internal/database/snapshot_revision.go b/internal/database/snapshot_revision.go new file mode 100644 index 000000000..ce8182e1f --- /dev/null +++ b/internal/database/snapshot_revision.go @@ -0,0 +1,91 @@ +package database + +import ( + "fmt" + "strings" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +// SQLite trigger bodies can also refer to retired columns; clear old definitions before DDL. +func dropSnapshotRevisionTriggers(db *gorm.DB) error { + return db.Transaction(func(tx *gorm.DB) error { + for _, table := range []string{"inbounds", "clients"} { + name := "snapshot_revision_" + table + commands := []string{fmt.Sprintf(`DROP TRIGGER IF EXISTS %s_insert`, name), fmt.Sprintf(`DROP TRIGGER IF EXISTS %s_update`, name)} + if tx.Name() == DialectPostgres { + if !tx.Migrator().HasTable(table) { + continue + } + commands = []string{fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON %s`, name, table)} + } + for _, command := range commands { + if err := tx.Exec(command).Error; err != nil { + return err + } + } + } + return nil + }) +} + +// Database triggers cover direct SQL and background lifecycle edits, not just service writes. +func migrateSnapshotRevisions(db *gorm.DB) error { + return db.Transaction(func(tx *gorm.DB) error { + for _, entry := range []struct { + value any + table string + ignore map[string]bool + }{ + {&model.Inbound{}, "inbounds", map[string]bool{"up": true, "down": true}}, + {&model.ClientRecord{}, "clients", map[string]bool{"updated_at": true}}, + } { + stmt := &gorm.Statement{DB: tx} + if err := stmt.Parse(entry.value); err != nil { + return err + } + var comparisons []string + for _, col := range stmt.Schema.DBNames { + if col == "snapshot_revision" || entry.ignore[col] { + continue + } + quoted := `"` + col + `"` + if tx.Name() == DialectPostgres { + comparisons = append(comparisons, "NEW."+quoted+" IS DISTINCT FROM OLD."+quoted) + } else { + comparisons = append(comparisons, "NEW."+quoted+" IS NOT OLD."+quoted) + } + } + table := entry.table + name := "snapshot_revision_" + table + var commands []string + if tx.Name() == DialectPostgres { + commands = []string{ + fmt.Sprintf(`CREATE OR REPLACE FUNCTION %s() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF TG_OP = 'INSERT' THEN NEW.snapshot_revision := md5(random()::text || clock_timestamp()::text); ELSIF OLD.snapshot_revision = '' OR %s THEN NEW.snapshot_revision := md5(random()::text || clock_timestamp()::text); ELSE NEW.snapshot_revision := OLD.snapshot_revision; END IF; RETURN NEW; END $$`, name, strings.Join(comparisons, " OR ")), + fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON %s`, name, table), + fmt.Sprintf(`CREATE TRIGGER %s BEFORE INSERT OR UPDATE ON %s FOR EACH ROW EXECUTE FUNCTION %s()`, name, table, name), + } + } else { + commands = []string{ + fmt.Sprintf(`DROP TRIGGER IF EXISTS %s_insert`, name), fmt.Sprintf(`DROP TRIGGER IF EXISTS %s_update`, name), + fmt.Sprintf(`CREATE TRIGGER %s_insert AFTER INSERT ON %s BEGIN UPDATE %s SET snapshot_revision = lower(hex(randomblob(16))) WHERE id = NEW.id; END`, name, table, table), + fmt.Sprintf(`CREATE TRIGGER %s_update AFTER UPDATE ON %s WHEN %s BEGIN UPDATE %s SET snapshot_revision = lower(hex(randomblob(16))) WHERE id = NEW.id; END`, name, table, strings.Join(comparisons, " OR "), table), + } + } + tokenSQL := "lower(hex(randomblob(16)))" + if tx.Name() == DialectPostgres { + tokenSQL = "md5(random()::text || clock_timestamp()::text)" + } + commands = append(commands, fmt.Sprintf("UPDATE %s SET snapshot_revision = %s WHERE snapshot_revision = ''", table, tokenSQL)) + + for _, sql := range commands { + if err := tx.Exec(sql).Error; err != nil { + return err + } + } + } + return nil + }) +} diff --git a/internal/database/snapshot_revision_catalog_bench_test.go b/internal/database/snapshot_revision_catalog_bench_test.go new file mode 100644 index 000000000..746394c61 --- /dev/null +++ b/internal/database/snapshot_revision_catalog_bench_test.go @@ -0,0 +1,63 @@ +package database + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func BenchmarkSnapshotRevisionCatalogCounters(b *testing.B) { + clients := make([]model.Client, 2500) + for i := range clients { + clients[i] = model.Client{Email: fmt.Sprintf("client-%d", i), ID: fmt.Sprintf("uuid-%d", i), Enable: true, TotalGB: 1 << 30} + } + settings, err := json.Marshal(map[string]any{"clients": clients}) + if err != nil { + b.Fatal(err) + } + for _, dialect := range []string{DialectSQLite, DialectPostgres} { + b.Run(dialect, func(b *testing.B) { + for _, mode := range []string{"scoped-baseline", "generic"} { + b.Run(mode, func(b *testing.B) { + db, _ := snapshotRevisionDDLDB(b, dialect) + if mode == "scoped-baseline" { + var definition string + query := "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'snapshot_revision_inbounds_update'" + drop := "DROP TRIGGER snapshot_revision_inbounds_update" + if dialect == DialectPostgres { + query = "SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgname = 'snapshot_revision_inbounds' AND tgrelid = 'inbounds'::regclass" + drop = "DROP TRIGGER snapshot_revision_inbounds ON inbounds" + } + if err := db.Raw(query).Scan(&definition).Error; err != nil { + b.Fatal(err) + } + definition = strings.Replace(definition, "UPDATE ON", "UPDATE OF settings ON", 1) + if err := db.Exec(drop).Error; err != nil { + b.Fatal(err) + } + if err := db.Exec(definition).Error; err != nil { + b.Fatal(err) + } + } + for i := range 8 { + if err := db.Create(&model.Inbound{Tag: fmt.Sprintf("catalog-%d", i), Settings: string(settings)}).Error; err != nil { + b.Fatal(err) + } + } + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if err := db.Exec("UPDATE inbounds SET up = up + 1, down = down + 1").Error; err != nil { + b.Fatal(err) + } + } + b.ReportMetric(8, "rows/op") + b.ReportMetric(float64(8*len(settings)), "config-bytes/op") + }) + } + }) + } +} diff --git a/internal/database/snapshot_revision_ddl_test.go b/internal/database/snapshot_revision_ddl_test.go new file mode 100644 index 000000000..3b8f27b32 --- /dev/null +++ b/internal/database/snapshot_revision_ddl_test.go @@ -0,0 +1,293 @@ +package database + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/driver/postgres" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func snapshotRevisionDDLDB(t testing.TB, dialect string) (*gorm.DB, func() *gorm.DB) { + t.Helper() + driver := sqlite.Open(filepath.Join(t.TempDir(), "ddl.db")) + if dialect == DialectPostgres { + dsn := os.Getenv("XUI_TEST_PG_DSN") + if dsn == "" { + dsn = os.Getenv("XUI_DB_DSN") + } + if dsn == "" { + t.Skip("set XUI_TEST_PG_DSN for PostgreSQL DDL tests") + } + admin, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatal(err) + } + pool, err := admin.DB() + if err != nil { + t.Fatal(err) + } + schema := fmt.Sprintf("revision_ddl_%d", time.Now().UnixNano()) + if err := admin.Exec("CREATE SCHEMA " + schema).Error; err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = admin.Exec("DROP SCHEMA " + schema + " CASCADE").Error; _ = pool.Close() }) + driver = postgres.Open(dsn + " search_path=" + schema) + } + open := func() *gorm.DB { + db, err := gorm.Open(driver, &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatal(err) + } + pool, err := db.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pool.Close() }) + return db + } + db := open() + if err := db.AutoMigrate(&model.Inbound{}, &model.ClientRecord{}); err != nil { + t.Fatal(err) + } + if err := migrateSnapshotRevisions(db); err != nil { + t.Fatal(err) + } + return db, open +} + +func TestSnapshotRevisionPostgresTypeDDL(t *testing.T) { + db, _ := snapshotRevisionDDLDB(t, DialectPostgres) + for _, sql := range []string{ + "ALTER TABLE inbounds ALTER COLUMN remark TYPE VARCHAR(1024)", + "ALTER TABLE clients ALTER COLUMN comment TYPE VARCHAR(1024)", + } { + if err := db.Exec(sql).Error; err != nil { + t.Fatalf("revision trigger blocked DDL %q: %v", sql, err) + } + } + if err := migrateSnapshotRevisions(db); err != nil { + t.Fatal(err) + } + ib := model.Inbound{Tag: "after-ddl"} + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + var before, after string + if err := db.Model(&model.Inbound{}).Select("snapshot_revision").Where("id = ?", ib.Id).Scan(&before).Error; err != nil { + t.Fatal(err) + } + if err := db.Exec("UPDATE inbounds SET remark = 'changed' WHERE id = ?", ib.Id).Error; err != nil { + t.Fatal(err) + } + if err := db.Model(&model.Inbound{}).Select("snapshot_revision").Where("id = ?", ib.Id).Scan(&after).Error; err != nil { + t.Fatal(err) + } + if before == after || len(after) != 32 { + t.Fatalf("DDL lost revision invalidation: %q -> %q", before, after) + } +} + +func TestSnapshotRevisionMigrationRecreationAndReopen(t *testing.T) { + for _, dialect := range []string{DialectSQLite, DialectPostgres} { + t.Run(dialect, func(t *testing.T) { + db, reopen := snapshotRevisionDDLDB(t, dialect) + if dialect == DialectSQLite { + if err := db.Exec("PRAGMA recursive_triggers = ON").Error; err != nil { + t.Fatal(err) + } + } + ib := model.Inbound{Tag: "ddl-reopen"} + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + read := func(conn *gorm.DB) string { + var revision string + if err := conn.Model(&model.Inbound{}).Select("snapshot_revision").Where("id = ?", ib.Id).Scan(&revision).Error; err != nil { + t.Fatal(err) + } + return revision + } + original := read(db) + for _, table := range []string{"inbounds", "clients"} { + if err := db.Exec("ALTER TABLE " + table + " ADD COLUMN retired_snapshot_field TEXT").Error; err != nil { + t.Fatal(err) + } + } + if err := dropSnapshotRevisionTriggers(db); err != nil { + t.Fatal(err) + } + for _, table := range []string{"inbounds", "clients"} { + name := "snapshot_revision_" + table + sql := fmt.Sprintf(`CREATE TRIGGER %s_update AFTER UPDATE OF retired_snapshot_field ON %s WHEN NEW.retired_snapshot_field IS NOT OLD.retired_snapshot_field BEGIN UPDATE %s SET snapshot_revision = lower(hex(randomblob(16))) WHERE id = NEW.id; END`, name, table, table) + if dialect == DialectPostgres { + sql = fmt.Sprintf(`CREATE TRIGGER %s BEFORE UPDATE OF retired_snapshot_field ON %s FOR EACH ROW EXECUTE FUNCTION %s()`, name, table, name) + } + if err := db.Exec(sql).Error; err != nil { + t.Fatal(err) + } + } + migrate := func(tx *gorm.DB) error { + if err := dropSnapshotRevisionTriggers(tx); err != nil { + return err + } + for _, table := range []string{"inbounds", "clients"} { + if err := tx.Exec("ALTER TABLE " + table + " DROP COLUMN retired_snapshot_field").Error; err != nil { + return err + } + } + return migrateSnapshotRevisions(tx) + } + rollback := fmt.Errorf("roll back DDL") + if err := db.Transaction(func(tx *gorm.DB) error { + if err := migrate(tx); err != nil { + return err + } + return rollback + }); !errors.Is(err, rollback) { + t.Fatalf("DDL rollback: %v", err) + } + if !db.Migrator().HasColumn("inbounds", "retired_snapshot_field") || read(db) != original { + t.Fatal("DDL rollback lost schema or revision") + } + if err := db.Transaction(migrate); err != nil { + t.Fatalf("retired-column migration blocked: %v", err) + } + if db.Migrator().HasColumn("inbounds", "retired_snapshot_field") { + t.Fatal("retired column survived migration") + } + if err := db.Exec("UPDATE inbounds SET remark = 'migrated' WHERE id = ?", ib.Id).Error; err != nil { + t.Fatal(err) + } + changed := read(db) + if changed == original { + t.Fatal("recreated trigger missed direct SQL") + } + pool, err := db.DB() + if err != nil { + t.Fatal(err) + } + if err := pool.Close(); err != nil { + t.Fatal(err) + } + db = reopen() + if err := dropSnapshotRevisionTriggers(db); err != nil { + t.Fatal(err) + } + if err := db.AutoMigrate(&model.Inbound{}, &model.ClientRecord{}); err != nil { + t.Fatal(err) + } + if err := migrateSnapshotRevisions(db); err != nil { + t.Fatal(err) + } + if read(db) != changed { + t.Fatal("reopen/recreation changed durable revision") + } + if err := db.Exec("UPDATE inbounds SET up = up + 1, down = down + 1 WHERE id = ?", ib.Id).Error; err != nil { + t.Fatal(err) + } + if read(db) != changed { + t.Fatal("counter-only update invalidated reopened catalog") + } + if err := db.Exec("UPDATE inbounds SET remark = 'after reopen' WHERE id = ?", ib.Id).Error; err != nil { + t.Fatal(err) + } + if read(db) == changed { + t.Fatal("reopened trigger missed configuration change") + } + }) + } +} + +func BenchmarkSnapshotRevisionSteadyState(b *testing.B) { + for _, dialect := range []string{DialectSQLite, DialectPostgres} { + b.Run(dialect, func(b *testing.B) { + for _, mode := range []string{"scoped-baseline", "generic"} { + b.Run(mode, func(b *testing.B) { + db, _ := snapshotRevisionDDLDB(b, dialect) + for _, table := range []string{"inbounds", "clients"} { + if mode != "scoped-baseline" { + continue + } + var definition string + if dialect == DialectSQLite { + if err := db.Raw("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?", "snapshot_revision_"+table+"_update").Scan(&definition).Error; err != nil { + b.Fatal(err) + } + } else { + if err := db.Raw("SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgname = ? AND tgrelid = ?::regclass", "snapshot_revision_"+table, table).Scan(&definition).Error; err != nil { + b.Fatal(err) + } + } + var value any = &model.Inbound{} + if table == "clients" { + value = &model.ClientRecord{} + } + stmt := &gorm.Statement{DB: db} + if err := stmt.Parse(value); err != nil { + b.Fatal(err) + } + var columns []string + for _, col := range stmt.Schema.DBNames { + if col == "snapshot_revision" || (table == "inbounds" && (col == "up" || col == "down")) || (table == "clients" && col == "updated_at") { + continue + } + columns = append(columns, `"`+col+`"`) + } + definition = strings.Replace(definition, "UPDATE ON", "UPDATE OF "+strings.Join(columns, ",")+" ON", 1) + drop := "DROP TRIGGER snapshot_revision_" + table + "_update" + if dialect == DialectPostgres { + drop = "DROP TRIGGER snapshot_revision_" + table + " ON " + table + } + if err := db.Exec(drop).Error; err != nil { + b.Fatal(err) + } + if err := db.Exec(definition).Error; err != nil { + b.Fatal(err) + } + } + inbounds := make([]model.Inbound, 1000) + clients := make([]model.ClientRecord, 1000) + for i := range inbounds { + inbounds[i] = model.Inbound{Tag: fmt.Sprintf("bench-%d", i), Settings: `{"clients":[]}`} + clients[i] = model.ClientRecord{Email: fmt.Sprintf("bench-%d", i)} + } + if err := db.CreateInBatches(inbounds, 100).Error; err != nil { + b.Fatal(err) + } + if err := db.CreateInBatches(clients, 100).Error; err != nil { + b.Fatal(err) + } + for _, kind := range []string{"counters", "timestamps", "noop"} { + b.Run(kind, func(b *testing.B) { + statement := "UPDATE inbounds SET up = up + 1, down = down + 1" + if kind == "timestamps" { + statement = "UPDATE clients SET updated_at = updated_at + 1" + } + if kind == "noop" { + statement = "UPDATE inbounds SET settings = settings" + } + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if err := db.Exec(statement).Error; err != nil { + b.Fatal(err) + } + } + b.ReportMetric(1000, "rows/op") + }) + } + }) + } + }) + } +} diff --git a/internal/database/snapshot_revision_test.go b/internal/database/snapshot_revision_test.go new file mode 100644 index 000000000..6a0c1dc7e --- /dev/null +++ b/internal/database/snapshot_revision_test.go @@ -0,0 +1,142 @@ +package database + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "gorm.io/driver/postgres" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestSnapshotRevisionsDirectWritesAndRollback(t *testing.T) { + for _, dialect := range []string{"sqlite", "postgres"} { + t.Run(dialect, func(t *testing.T) { + driver := sqlite.Open(filepath.Join(t.TempDir(), "revisions.db")) + if dialect == "postgres" { + dsn := os.Getenv("XUI_TEST_PG_DSN") + if dsn == "" { + dsn = os.Getenv("XUI_DB_DSN") + } + if dsn == "" { + t.Skip("set XUI_TEST_PG_DSN for PostgreSQL") + } + driver = postgres.Open(dsn) + } + db, err := gorm.Open(driver, &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatal(err) + } + sqlDB, err := db.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = sqlDB.Close() }) + if err := db.AutoMigrate(&model.Inbound{}, &model.ClientRecord{}); err != nil { + t.Fatal(err) + } + legacy := model.Inbound{Tag: "revision-legacy"} + if err := db.Create(&legacy).Error; err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Where("id = ?", legacy.Id).Delete(&model.Inbound{}) }) + if err := db.Exec("UPDATE inbounds SET snapshot_revision = '' WHERE id = ?", legacy.Id).Error; err != nil { + t.Fatal(err) + } + if err := migrateSnapshotRevisions(db); err != nil { + t.Fatal(err) + } + var migrated model.Inbound + if err := db.First(&migrated, legacy.Id).Error; err != nil { + t.Fatal(err) + } + if len(migrated.SnapshotRevision) != 32 { + t.Fatalf("legacy row was not versioned: %q", migrated.SnapshotRevision) + } + ib := model.Inbound{Tag: "revision-test", Settings: `{"clients":[]}`} + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Where("id = ?", ib.Id).Delete(&model.Inbound{}) }) + read := func() string { + var row model.Inbound + if err := db.First(&row, ib.Id).Error; err != nil { + t.Fatal(err) + } + return row.SnapshotRevision + } + original := read() + if len(original) != 32 { + t.Fatalf("missing durable token %q", original) + } + if err := db.Exec("UPDATE inbounds SET up = ?, down = ? WHERE id = ?", 10, 20, ib.Id).Error; err != nil { + t.Fatal(err) + } + if got := read(); got != original { + t.Fatal("usage invalidated structure") + } + if err := db.Exec("UPDATE inbounds SET settings = settings WHERE id = ?", ib.Id).Error; err != nil { + t.Fatal(err) + } + if got := read(); got != original { + t.Fatal("no-op invalidated structure") + } + sentinel := errors.New("rollback") + err = db.Transaction(func(tx *gorm.DB) error { + if err := tx.Exec("UPDATE inbounds SET settings = ? WHERE id = ?", `{"clients":[{"email":"new"}]}`, ib.Id).Error; err != nil { + return err + } + return sentinel + }) + if !errors.Is(err, sentinel) || read() != original { + t.Fatalf("rollback changed structure: %v", err) + } + if err := db.Exec("UPDATE inbounds SET settings = ? WHERE id = ?", `{"clients":[{"email":"new"}]}`, ib.Id).Error; err != nil { + t.Fatal(err) + } + changed := read() + if changed == original { + t.Fatal("direct SQL settings edit missed") + } + if err := migrateSnapshotRevisions(db); err != nil { + t.Fatal(err) + } + if read() != changed { + t.Fatal("reinstall lost durable revision") + } + client := model.ClientRecord{Email: "snapshot-revision-test", UUID: "a"} + if err := db.Create(&client).Error; err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Where("id = ?", client.Id).Delete(&model.ClientRecord{}) }) + var record model.ClientRecord + if err := db.First(&record, client.Id).Error; err != nil { + t.Fatal(err) + } + before := record.SnapshotRevision + if err := db.Model(&record).UpdateColumn("updated_at", 999).Error; err != nil { + t.Fatal(err) + } + if err := db.First(&record, client.Id).Error; err != nil { + t.Fatal(err) + } + if record.SnapshotRevision != before { + t.Fatal("timestamp-only write invalidated structure") + } + if err := db.Exec("UPDATE clients SET enable = ? WHERE id = ?", false, client.Id).Error; err != nil { + t.Fatal(err) + } + if err := db.First(&record, client.Id).Error; err != nil { + t.Fatal(err) + } + if record.SnapshotRevision == before { + t.Fatal("automatic lifecycle write missed") + } + }) + } +} diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go new file mode 100644 index 000000000..6cf4f7388 --- /dev/null +++ b/internal/nodee2e/node_snapshot_test.go @@ -0,0 +1,141 @@ +package nodee2e + +import ( + "bytes" + "compress/gzip" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "strconv" + "sync/atomic" + "testing" +) + +func TestNodeSnapshotVersionCompatibility(t *testing.T) { + current := panelBinary(t) + old := os.Getenv("XUI_NODE_E2E_OLD_BINARY") + for _, version := range []struct { + name string + master, node string + compact bool + }{ + {"new-master-new-node", current, current, true}, + {"new-master-old-node", current, old, false}, + {"old-master-new-node", old, current, false}, + {"old-master-old-node", old, old, false}, + } { + t.Run(version.name, func(t *testing.T) { + if version.master == "" || version.node == "" { + t.Skip("set XUI_NODE_E2E_OLD_BINARY to a baseline panel binary") + } + t.Parallel() + master := newPanel(t, version.master, "master") + node := newPanel(t, version.node, "node") + token := node.mintToken("snapshot-link", "node-sync") + master.start() + node.start() + var lists, compact, full, unchanged atomic.Int32 + target, err := url.Parse(node.url()) + if err != nil { + t.Fatal(err) + } + proxy := httputil.NewSingleHostReverseProxy(target) + proxy.ModifyResponse = func(response *http.Response) error { + if response.Request.URL.Path != "/panel/api/inbounds/trafficSnapshot" || response.StatusCode != http.StatusOK { + return nil + } + data, err := io.ReadAll(response.Body) + _ = response.Body.Close() + if err != nil { + return err + } + response.Body = io.NopCloser(bytes.NewReader(data)) + if response.Header.Get("Content-Encoding") == "gzip" { + reader, err := gzip.NewReader(bytes.NewReader(data)) + if err != nil { + return err + } + decoded, readErr := io.ReadAll(reader) + _ = reader.Close() + if readErr != nil { + return readErr + } + data = decoded + } + var env struct { + Obj struct { + Structure json.RawMessage `json:"structure"` + } `json:"obj"` + } + if err := json.Unmarshal(data, &env); err != nil { + return err + } + if len(env.Obj.Structure) > 0 && string(env.Obj.Structure) != "null" { + full.Add(1) + } else { + unchanged.Add(1) + } + return nil + } + front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/list": + lists.Add(1) + case "/panel/api/inbounds/trafficSnapshot": + compact.Add(1) + } + proxy.ServeHTTP(w, req) + })) + t.Cleanup(front.Close) + address, err := url.Parse(front.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(address.Port()) + if err != nil { + t.Fatal(err) + } + inboundPort := freePort(t) + var source inboundView + if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { + t.Fatal(err) + } + master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) + eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { + ib, ok := master.inboundOnPort(inboundPort) + ready := lists.Load() >= 3 + if version.compact { + ready = unchanged.Load() >= 2 + } + return ok && hasAll(ib.emails(), "matrix-first") && ready, fmt.Sprintf("adopted=%v lists=%d compact=%d unchanged=%d", ok, lists.Load(), compact.Load(), unchanged.Load()) + }) + if !version.compact && compact.Load() != 0 { + t.Fatalf("legacy peer received compact calls: %d", compact.Load()) + } + before := full.Load() + node.call(http.MethodPost, "/panel/api/clients/add", map[string]any{"client": map[string]any{"email": "matrix-added", "enable": true}, "inboundIds": []int{source.Id}}) + eventually(t, settleTimeout, "node edit after unchanged polls reaches master", func() (bool, string) { + ib, ok := master.inboundOnPort(inboundPort) + return ok && hasAll(ib.emails(), "matrix-first", "matrix-added"), fmt.Sprint(ib.emails()) + }) + if version.compact && full.Load() <= before { + t.Fatal("node edit did not refresh catalog") + } + if version.compact { + before = full.Load() + node.stop() + node.start() + eventually(t, settleTimeout, "node restart invalidates the old catalog", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) }) + before = full.Load() + master.stop() + master.start() + eventually(t, settleTimeout, "master restart reacquires complete structure", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) }) + } + }) + } +} diff --git a/internal/util/json_util/list.go b/internal/util/json_util/list.go index 0e5edb112..25c162f45 100644 --- a/internal/util/json_util/list.go +++ b/internal/util/json_util/list.go @@ -10,6 +10,59 @@ import ( // ErrListTooLong is returned by DecodeCappedList for a list past its entry limit. var ErrListTooLong = errors.New("list exceeds entry limit") +// CountCappedList validates JSON, then counts top-level entries without allocating typed rows. +func CountCappedList(raw []byte, maxEntries int) (int, error) { + raw = bytes.Trim(raw, " \t\r\n") + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return 0, nil + } + if !json.Valid(raw) { + return 0, fmt.Errorf("invalid JSON array") + } + if raw[0] != '[' { + return 0, fmt.Errorf("expected a JSON array") + } + count, depth := 0, 0 + quoted, escaped, wantValue := false, false, true + for _, c := range raw[1 : len(raw)-1] { + if quoted { + if escaped { + escaped = false + } else if c == '\\' { + escaped = true + } else if c == '"' { + quoted = false + } + continue + } + if depth == 0 { + if c == ',' { + wantValue = true + continue + } + if c == ' ' || c == '\t' || c == '\r' || c == '\n' { + continue + } + if wantValue { + count++ + if count > maxEntries { + return 0, fmt.Errorf("%w (%d)", ErrListTooLong, maxEntries) + } + wantValue = false + } + } + switch c { + case '"': + quoted = true + case '[', '{': + depth++ + case ']', '}': + depth-- + } + } + return count, nil +} + // DecodeCappedList decodes a JSON array entry by entry and stops at the first entry past // maxEntries: each "{}" becomes a whole T, so a byte cap alone does not bound the result. func DecodeCappedList[T any](raw []byte, maxEntries int) ([]T, error) { diff --git a/internal/util/json_util/list_count_test.go b/internal/util/json_util/list_count_test.go new file mode 100644 index 000000000..3b81aaaef --- /dev/null +++ b/internal/util/json_util/list_count_test.go @@ -0,0 +1,40 @@ +package json_util + +import ( + "bytes" + "encoding/json" + "errors" + "testing" +) + +func FuzzCountCappedList(f *testing.F) { + for _, raw := range []string{`[]`, `[{},[],null,"comma, bracket ] quote \""]`, `[1,2]`, `[1`, `[1] [2]`, `{}`, `null`} { + f.Add(raw) + } + f.Fuzz(func(t *testing.T, raw string) { + if len(raw) > 4096 { + return + } + var rows []json.RawMessage + err := json.Unmarshal([]byte(raw), &rows) + if len(bytes.Trim([]byte(raw), " \t\r\n")) == 0 { + err = nil + } + count, gotErr := CountCappedList([]byte(raw), 16) + if err != nil { + if gotErr == nil { + t.Fatalf("accepted invalid array %q", raw) + } + return + } + if len(rows) > 16 { + if !errors.Is(gotErr, ErrListTooLong) { + t.Fatalf("count=%d error=%v, want list cap", count, gotErr) + } + return + } + if gotErr != nil || count != len(rows) { + t.Fatalf("%q: count=%d error=%v want %d", raw, count, gotErr, len(rows)) + } + }) +} diff --git a/internal/util/wirecodec/wirecodec.go b/internal/util/wirecodec/wirecodec.go index b4a66b24a..9f1ef8458 100644 --- a/internal/util/wirecodec/wirecodec.go +++ b/internal/util/wirecodec/wirecodec.go @@ -31,8 +31,10 @@ const ( // CapWireguardDevices marks a node that serves a WireGuard client's extra devices; // an older node ignores them and keeps only the client's first peer. CapWireguardDevices = "wg-devices" + // CapTrafficSnapshot marks a node that serves revisioned traffic snapshots. + CapTrafficSnapshot = "traffic-snapshot-v1" // NodeCaps is the full CapsHeader value this build advertises. - NodeCaps = CapZstd + "," + CapAmneziaWGKernel + "," + CapPreserveClientTraffic + "," + CapWireguardDevices + NodeCaps = CapZstd + "," + CapAmneziaWGKernel + "," + CapPreserveClientTraffic + "," + CapWireguardDevices + "," + CapTrafficSnapshot // maxDecodeBytes bounds in-memory decompression to defuse a zstd bomb from // an (authenticated) node-API caller. diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go index 8a2cb27f4..879b6e930 100644 --- a/internal/web/controller/api.go +++ b/internal/web/controller/api.go @@ -114,6 +114,7 @@ var monitorScopeAllow = map[string]struct{}{ var nodeSyncScopeAllow = map[string]map[string]struct{}{ "/server/status": {http.MethodGet: {}}, "/inbounds/list": {http.MethodGet: {}}, + "/inbounds/trafficSnapshot": {http.MethodGet: {}}, "/inbounds/add": {http.MethodPost: {}}, "/inbounds/del/:id": {http.MethodPost: {}}, "/inbounds/update/:id": {http.MethodPost: {}}, diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index c1387f7d9..ad4020ddf 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -77,6 +77,7 @@ func (a *InboundController) inboundServiceFor(c *gin.Context) *service.InboundSe // initRouter initializes the routes for inbound-related operations. func (a *InboundController) initRouter(g *gin.RouterGroup) { g.GET("/list", a.getInbounds) + g.GET("/trafficSnapshot", a.getTrafficSnapshot) g.GET("/list/slim", a.getInboundsSlim) g.GET("/options", a.getInboundOptions) g.GET("/allLinks", a.getAllInboundLinks) @@ -523,3 +524,18 @@ func (a *InboundController) setFallbacks(c *gin.Context) { a.xrayService.SetToNeedRestart() jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil) } + +func (a *InboundController) getTrafficSnapshot(c *gin.Context) { + user := session.GetLoginUser(c) + snapshot, err := a.inboundService.GetNodeTrafficSnapshot(c.Request.Context(), user.Id, c.Query("revision")) + if err != nil { + jsonObj(c, nil, err) + return + } + snapshot.OnlineTree = a.inboundService.GetOnlineClientsByGuid() + if len(snapshot.OnlineTree) == 0 { + snapshot.OnlineEmails = a.inboundService.GetOnlineClients() + } + snapshot.ActiveInboundTree = a.inboundService.GetActiveInboundsByGuid() + jsonObj(c, snapshot, nil) +} diff --git a/internal/web/controller/node_snapshot_test.go b/internal/web/controller/node_snapshot_test.go new file mode 100644 index 000000000..f90578497 --- /dev/null +++ b/internal/web/controller/node_snapshot_test.go @@ -0,0 +1,64 @@ +package controller + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/util/crypto" +) + +func TestNodeTrafficSnapshotScopeAndRevision(t *testing.T) { + router, api := newAPIAuthTestEngine(t) + NewInboundController(router.Group("/base/panel/api/inbounds", api.checkAPIAuth, api.enforceTokenScope)) + mtls := httptest.NewRequest(http.MethodGet, "/base/panel/api/inbounds/trafficSnapshot", nil) + mtls.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}} + mtlsResult := httptest.NewRecorder() + router.ServeHTTP(mtlsResult, mtls) + if mtlsResult.Code != http.StatusOK { + t.Fatalf("verified mTLS snapshot rejected: %d %s", mtlsResult.Code, mtlsResult.Body) + } + unauthenticated := httptest.NewRecorder() + router.ServeHTTP(unauthenticated, httptest.NewRequest(http.MethodGet, "/base/panel/api/inbounds/trafficSnapshot", nil)) + if unauthenticated.Code != http.StatusNotFound { + t.Fatalf("unauthenticated snapshot exposed: %d", unauthenticated.Code) + } + + for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin, model.ApiScopeMonitor} { + if err := database.GetDB().Create(&model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Enabled: true, Scope: scope}).Error; err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodGet, "/base/panel/api/inbounds/trafficSnapshot", nil) + request.Header.Set("Authorization", "Bearer "+scope) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if scope == model.ApiScopeMonitor { + if response.Code != http.StatusForbidden { + t.Fatalf("monitor status=%d", response.Code) + } + continue + } + if response.Code != http.StatusOK { + t.Fatalf("scope %s rejected: %d %s", scope, response.Code, response.Body) + } + var env struct { + Success bool `json:"success"` + Obj struct { + Version int `json:"version"` + Revision string `json:"revision"` + Structure json.RawMessage `json:"structure"` + } `json:"obj"` + } + if err := json.Unmarshal(response.Body.Bytes(), &env); err != nil { + t.Fatal(err) + } + if !env.Success || env.Obj.Version != 1 || len(env.Obj.Revision) != 64 || len(env.Obj.Structure) == 0 { + t.Fatalf("invalid first snapshot: %s", response.Body) + } + } +} diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index ccc1dd300..50be79292 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -103,6 +103,9 @@ func (j *NodeTrafficSyncJob) Run() { return } j.inboundService.RetainSyncedNodeOnlineClients(nodes) + if err := j.inboundService.RetainNodeSnapshotCaches(nodes); err != nil { + logger.Warning("node traffic sync: prune snapshot caches failed:", err) + } if len(nodes) == 0 { return } @@ -486,9 +489,11 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout) defer cancel() + fetchStarted := time.Now() snap, err := rt.FetchTrafficSnapshot(ctx) + prepareStarted := time.Now() if err != nil { - logger.Warningf("node traffic sync: fetch from %s failed: %v", n.Name, err) + logger.Warningf("node traffic sync: fetch from %s failed after %dms: %v", n.Name, prepareStarted.Sub(fetchStarted).Milliseconds(), err) j.inboundService.ClearNodeOnlineClients(n.Id) return nil } @@ -510,7 +515,11 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } } } + mergeStarted := time.Now() changed, err := j.inboundService.SetRemoteTraffic(n.Id, snap, dirty, justPushed) + logger.Debugf("node traffic sync timing: node_id=%d compact=%t fetch_ms=%d prepare_ms=%d merge_ms=%d", + n.Id, snap.StructuralRevision != "", prepareStarted.Sub(fetchStarted).Milliseconds(), + mergeStarted.Sub(prepareStarted).Milliseconds(), time.Since(mergeStarted).Milliseconds()) if err != nil { logger.Warningf("node traffic sync: merge for %s failed: %v", n.Name, err) return nil diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index bcc21d332..44c4e9870 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -278,8 +278,16 @@ func TestMasterNodeContract(t *testing.T) { } }}, {"FetchTrafficSnapshot reads every part of the snapshot", []string{"FetchTrafficSnapshot"}, func() error { - _, err := master.FetchTrafficSnapshot(ctx) - return err + for i := range 3 { + snapshot, err := master.FetchTrafficSnapshot(ctx) + if err != nil { + return err + } + if i > 0 && snapshot.StructuralRevision == "" { + return fmt.Errorf("node did not negotiate compact snapshots") + } + } + return nil }, nil}, {"PushGlobalClientTraffics is accepted", []string{"PushGlobalClientTraffics"}, func() error { return master.PushGlobalClientTraffics(ctx, "master-guid", []*xray.ClientTraffic{{Email: "c0", Up: 1, Down: 2}}) diff --git a/internal/web/runtime/node_snapshot.go b/internal/web/runtime/node_snapshot.go new file mode 100644 index 000000000..ac82098a1 --- /dev/null +++ b/internal/web/runtime/node_snapshot.go @@ -0,0 +1,245 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "strings" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/util/wirecodec" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type snapshotClientIdentity struct { + InboundID int + Email string +} + +type NodeSnapshotAttachment struct { + InboundID int `json:"inboundId" example:"1"` + Email string `json:"email" example:"user1"` +} + +type NodeSnapshotStructure struct { + Inbounds []*model.Inbound `json:"inbounds"` + Attachments []NodeSnapshotAttachment `json:"attachments"` +} + +type NodeInboundTraffic struct { + ID int `json:"id" example:"1"` + Up int64 `json:"up"` + Down int64 `json:"down"` +} + +type NodeClientTraffic struct { + ID int `json:"id" example:"14825"` + InboundID int `json:"inboundId" example:"1"` + Email string `json:"email" example:"user1"` + Enable bool `json:"enable" example:"true"` + Up int64 `json:"up" example:"1048576"` + Down int64 `json:"down" example:"2097152"` + Total int64 `json:"total" example:"10737418240"` + ExpiryTime int64 `json:"expiryTime" example:"1735689600000"` + Reset int `json:"reset"` + ResetDay int `json:"resetDay"` + ResetWeekday int `json:"resetWeekday"` + ResetMax int `json:"resetMax"` + ResetCount int `json:"resetCount"` + LastOnline int64 `json:"lastOnline" example:"1735680000000"` +} + +func (c NodeClientTraffic) traffic() xray.ClientTraffic { + return xray.ClientTraffic{Id: c.ID, InboundId: c.InboundID, Email: c.Email, Enable: c.Enable, Up: c.Up, Down: c.Down, Total: c.Total, ExpiryTime: c.ExpiryTime, Reset: c.Reset, ResetDay: c.ResetDay, ResetWeekday: c.ResetWeekday, ResetMax: c.ResetMax, ResetCount: c.ResetCount, LastOnline: c.LastOnline} +} + +// NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted. +type NodeTrafficSnapshotV1 struct { + Version int `json:"version" example:"1"` + Revision string `json:"revision" example:"0000000000000000000000000000000000000000000000000000000000000001"` + Structure *NodeSnapshotStructure `json:"structure,omitempty"` + InboundTraffic []NodeInboundTraffic `json:"inboundTraffic"` + Clients []NodeClientTraffic `json:"clients"` + OnlineEmails []string `json:"onlineEmails"` + OnlineTree map[string][]string `json:"onlineTree"` + ActiveInboundTree map[string][]string `json:"activeInboundTree"` + LastOnlineMap map[string]int64 `json:"lastOnlineMap"` +} + +func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) { + select { + case r.snapshotGate <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-r.snapshotGate }() + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + supported := slices.Contains(r.nodeCaps, wirecodec.CapTrafficSnapshot) + capsEpoch := r.snapshotCapsEpoch + r.mu.RUnlock() + if capsEpoch != r.snapshotSeenCapsEpoch { + r.snapshotSeenCapsEpoch = capsEpoch + r.snapshotGeneration++ + r.snapshotRevision = "" + r.snapshotStructure = nil + r.snapshotClients = nil + r.snapshotUnsupportedUntil = time.Time{} + } + if supported && time.Now().After(r.snapshotUnsupportedUntil) { + snap, err := r.fetchCompactSnapshot(ctx) + if err == nil { + return snap, nil + } + r.snapshotGeneration++ + r.snapshotRevision = "" + r.snapshotStructure = nil + r.snapshotClients = nil + var status *remoteHTTPError + if !errors.As(err, &status) || (status.code != http.StatusNotFound && status.code != http.StatusMethodNotAllowed) { + return nil, err + } + r.snapshotUnsupportedUntil = time.Now().Add(5 * time.Minute) + } + snap, err := r.fetchLegacyTrafficSnapshot(ctx) + if err == nil && ctx.Err() != nil { + snap = nil + err = ctx.Err() + } + if err != nil { + r.snapshotGeneration++ + r.snapshotRevision = "" + r.snapshotStructure = nil + r.snapshotClients = nil + } + return snap, err +} + +func (r *Remote) fetchCompactSnapshot(ctx context.Context) (*TrafficSnapshot, error) { + path := "panel/api/inbounds/trafficSnapshot?revision=" + url.QueryEscape(r.snapshotRevision) + env, err := r.do(ctx, http.MethodGet, path, nil) + if err != nil { + return nil, err + } + wire, err := decodeNodeTrafficSnapshot(env.Obj) + if err != nil { + return nil, fmt.Errorf("decode traffic snapshot: %w", err) + } + if wire.Version != 1 || wire.Revision == "" || wire.Clients == nil || wire.InboundTraffic == nil { + return nil, fmt.Errorf("incomplete or unsupported traffic snapshot") + } + structure := wire.Structure + if structure == nil { + if wire.Revision != r.snapshotRevision || r.snapshotStructure == nil { + return nil, fmt.Errorf("traffic snapshot has no matching structure") + } + if len(wire.Clients) != len(r.snapshotClients) { + return nil, fmt.Errorf("traffic snapshot omitted client counters") + } + for _, row := range wire.Clients { + if identity, ok := r.snapshotClients[row.ID]; !ok || identity.InboundID != row.InboundID || identity.Email != row.Email { + return nil, fmt.Errorf("traffic snapshot changed client roster without structure") + } + } + structure = r.snapshotStructure + } + snap, err := wire.expand(structure) + if err != nil { + return nil, err + } + snap.StructuralRevision = fmt.Sprintf("%p/%d/%s", r, r.snapshotGeneration, wire.Revision) + if wire.Structure != nil { + identities := make(map[int]snapshotClientIdentity, len(wire.Clients)) + for _, row := range wire.Clients { + if _, duplicate := identities[row.ID]; row.ID <= 0 || duplicate { + return nil, fmt.Errorf("invalid snapshot client identity") + } + identities[row.ID] = snapshotClientIdentity{InboundID: row.InboundID, Email: row.Email} + } + r.snapshotClients = identities + } + if err := ctx.Err(); err != nil { + return nil, err + } + r.snapshotRevision = wire.Revision + r.snapshotStructure = structure + return snap, nil +} + +func (w *NodeTrafficSnapshotV1) expand(structure *NodeSnapshotStructure) (*TrafficSnapshot, error) { + if structure.Inbounds == nil || structure.Attachments == nil { + return nil, fmt.Errorf("incomplete traffic snapshot structure") + } + snap := &TrafficSnapshot{Inbounds: make([]*model.Inbound, 0, len(structure.Inbounds)), OnlineEmails: w.OnlineEmails, OnlineTree: w.OnlineTree, ActiveInboundTree: w.ActiveInboundTree, LastOnlineMap: w.LastOnlineMap} + byID := make(map[int]*model.Inbound, len(structure.Inbounds)) + seen := make(map[int]map[string]bool, len(structure.Inbounds)) + for _, ib := range structure.Inbounds { + if ib == nil || byID[ib.Id] != nil { + return nil, fmt.Errorf("invalid or duplicate snapshot inbound") + } + copy := *ib + if ib.NodeID != nil { + nodeID := *ib.NodeID + copy.NodeID = &nodeID + } + if ib.FallbackParent != nil { + parent := *ib.FallbackParent + copy.FallbackParent = &parent + } + copy.ClientStats = make([]xray.ClientTraffic, 0) + byID[copy.Id] = © + seen[copy.Id] = map[string]bool{} + snap.Inbounds = append(snap.Inbounds, ©) + } + totals := make(map[int]bool, len(w.InboundTraffic)) + for _, counter := range w.InboundTraffic { + ib := byID[counter.ID] + if ib == nil || totals[counter.ID] { + return nil, fmt.Errorf("invalid snapshot inbound counters") + } + totals[counter.ID] = true + ib.Up = counter.Up + ib.Down = counter.Down + } + if len(totals) != len(byID) { + return nil, fmt.Errorf("missing snapshot inbound counters") + } + stats := make(map[string]xray.ClientTraffic, len(w.Clients)) + clientIDs := make(map[int]bool, len(w.Clients)) + for _, counter := range w.Clients { + row := counter.traffic() + if row.Id > 0 && clientIDs[row.Id] { + return nil, fmt.Errorf("duplicate snapshot client identity") + } + clientIDs[row.Id] = true + if _, duplicate := stats[row.Email]; row.Email != "" && duplicate { + return nil, fmt.Errorf("duplicate snapshot client counters") + } + stats[row.Email] = row + if home := byID[row.InboundId]; home != nil { + home.ClientStats = append(home.ClientStats, row) + seen[home.Id][strings.ToLower(row.Email)] = true + } + } + for _, attachment := range structure.Attachments { + if attachment.Email == "" { + continue + } + ib := byID[attachment.InboundID] + if ib == nil { + return nil, fmt.Errorf("snapshot attachment references an unknown inbound") + } + key := strings.ToLower(attachment.Email) + if row, ok := stats[attachment.Email]; ok && !seen[ib.Id][key] { + ib.ClientStats = append(ib.ClientStats, row) + seen[ib.Id][key] = true + } + } + return snap, nil +} diff --git a/internal/web/runtime/node_snapshot_config_test.go b/internal/web/runtime/node_snapshot_config_test.go new file mode 100644 index 000000000..054f89ff3 --- /dev/null +++ b/internal/web/runtime/node_snapshot_config_test.go @@ -0,0 +1,20 @@ +package runtime + +import ( + "encoding/json" + "testing" +) + +func TestSnapshotDecodeInboundConfigShapes(t *testing.T) { + for _, config := range []string{`{"clients":[]}`, `"{\"clients\":[]}"`} { + raw := `{"structure":{"inbounds":[{"id":7,"tag":"alias","port":443,"protocol":"vless","settings":` + config + `,"streamSettings":` + config + `,"sniffing":` + config + `,"clientStats":[{"email":"ignored","up":999}]}],"attachments":[]}}` + wire, err := decodeNodeTrafficSnapshot(json.RawMessage(raw)) + if err != nil { + t.Fatal(err) + } + ib := wire.Structure.Inbounds[0] + if ib.Id != 7 || ib.Tag != "alias" || ib.Port != 443 || string(ib.Protocol) != "vless" || ib.Settings != `{"clients":[]}` || ib.StreamSettings != ib.Settings || ib.Sniffing != ib.Settings || len(ib.ClientStats) != 0 { + t.Fatalf("inbound shape changed: %+v", ib) + } + } +} diff --git a/internal/web/runtime/node_snapshot_decode.go b/internal/web/runtime/node_snapshot_decode.go new file mode 100644 index 000000000..aa8c359e7 --- /dev/null +++ b/internal/web/runtime/node_snapshot_decode.go @@ -0,0 +1,143 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" +) + +// Counters and memberships allow million-client deployments; catalogs retain the legacy cap. +const maxNodeSnapshotClients = 1 << 20 + +// Count raw entries before allocating typed rows, including for an oversized list of empty objects. +func decodeSnapshotList[T any](raw json.RawMessage, limit int) ([]T, error) { + count, err := json_util.CountCappedList(raw, limit) + if err != nil { + return nil, err + } + if len(raw) == 0 || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return nil, nil + } + result := make([]T, 0, count) + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return result, nil +} + +func decodeSnapshotInbounds(raw json.RawMessage) ([]*model.Inbound, error) { + rows, err := json_util.DecodeCappedList[json.RawMessage](raw, maxNodeInbounds) + if err != nil { + return nil, err + } + if len(raw) == 0 || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return nil, nil + } + result := make([]*model.Inbound, len(rows)) + for i, row := range rows { + if bytes.Equal(bytes.TrimSpace(row), []byte("null")) { + continue + } + type inboundAlias model.Inbound + inbound := &model.Inbound{} + fields := struct { + *inboundAlias + Settings json.RawMessage `json:"settings"` + StreamSettings json.RawMessage `json:"streamSettings"` + Sniffing json.RawMessage `json:"sniffing"` + ClientStats json.RawMessage `json:"clientStats"` + }{inboundAlias: (*inboundAlias)(inbound)} + if err := json.Unmarshal(row, &fields); err != nil { + return nil, err + } + // These legacy stats are replaced by the separately bounded compact counters. + if _, err := json_util.CountCappedList(fields.ClientStats, maxNodeSnapshotClients); err != nil { + return nil, err + } + inbound.Settings = snapshotConfigString(fields.Settings) + inbound.StreamSettings = snapshotConfigString(fields.StreamSettings) + inbound.Sniffing = snapshotConfigString(fields.Sniffing) + result[i] = inbound + } + + return result, nil +} + +func snapshotConfigString(raw json.RawMessage) string { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return "" + } + if raw[0] == '"' { + var value string + if err := json.Unmarshal(raw, &value); err == nil { + return value + } + } + return string(raw) +} + +func decodeNodeTrafficSnapshot(raw json.RawMessage) (NodeTrafficSnapshotV1, error) { + var fields struct { + Version int `json:"version"` + Revision string `json:"revision"` + Structure json.RawMessage `json:"structure"` + InboundTraffic json.RawMessage `json:"inboundTraffic"` + Clients json.RawMessage `json:"clients"` + OnlineEmails json.RawMessage `json:"onlineEmails"` + OnlineTree json.RawMessage `json:"onlineTree"` + ActiveInboundTree json.RawMessage `json:"activeInboundTree"` + LastOnlineMap json.RawMessage `json:"lastOnlineMap"` + } + var wire NodeTrafficSnapshotV1 + if err := json.Unmarshal(raw, &fields); err != nil { + return wire, err + } + wire.Version, wire.Revision = fields.Version, fields.Revision + if len(fields.Structure) > 0 && !bytes.Equal(bytes.TrimSpace(fields.Structure), []byte("null")) { + var structure struct { + Inbounds json.RawMessage `json:"inbounds"` + Attachments json.RawMessage `json:"attachments"` + } + if err := json.Unmarshal(fields.Structure, &structure); err != nil { + return wire, err + } + wire.Structure = &NodeSnapshotStructure{} + var err error + if wire.Structure.Inbounds, err = decodeSnapshotInbounds(structure.Inbounds); err != nil { + return wire, fmt.Errorf("structure.inbounds: %w", err) + } + if wire.Structure.Attachments, err = decodeSnapshotList[NodeSnapshotAttachment](structure.Attachments, maxNodeSnapshotClients); err != nil { + return wire, fmt.Errorf("structure.attachments: %w", err) + } + } + var err error + if wire.Clients, err = decodeSnapshotList[NodeClientTraffic](fields.Clients, maxNodeSnapshotClients); err != nil { + return wire, fmt.Errorf("clients: %w", err) + } + if wire.InboundTraffic, err = decodeSnapshotList[NodeInboundTraffic](fields.InboundTraffic, maxNodeInbounds); err != nil { + return wire, fmt.Errorf("inboundTraffic: %w", err) + } + if wire.OnlineEmails, err = decodeSnapshotList[string](fields.OnlineEmails, maxNodeMapValues); err != nil { + return wire, fmt.Errorf("onlineEmails: %w", err) + } + for _, entry := range []struct { + name string + raw json.RawMessage + target any + }{ + {"onlineTree", fields.OnlineTree, &wire.OnlineTree}, + {"activeInboundTree", fields.ActiveInboundTree, &wire.ActiveInboundTree}, + {"lastOnlineMap", fields.LastOnlineMap, &wire.LastOnlineMap}, + } { + if len(entry.raw) > 0 { + if err := decodeCappedValues(entry.raw, entry.target, maxNodeMapValues); err != nil { + return wire, fmt.Errorf("%s: %w", entry.name, err) + } + } + } + return wire, nil +} diff --git a/internal/web/runtime/node_snapshot_limits_test.go b/internal/web/runtime/node_snapshot_limits_test.go new file mode 100644 index 000000000..b3bf4fbf5 --- /dev/null +++ b/internal/web/runtime/node_snapshot_limits_test.go @@ -0,0 +1,180 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestRemoteSnapshotCapsAndRecovers(t *testing.T) { + list := func(item string, count int) string { return "[" + strings.Repeat(item+",", count-1) + item + "]" } + for _, tc := range []struct{ name, field, value string }{ + {"catalog", "structure", `{"inbounds":` + list("{}", 65537) + `,"attachments":[]}`}, + {"embedded clients", "structure", `{"inbounds":[{"id":1,"CLIENTSTATS":` + list("{}", (1<<20)+1) + `}],"attachments":[]}`}, + {"attachments", "structure", `{"inbounds":[],"attachments":` + list("{}", (1<<20)+1) + `}`}, + {"clients", "clients", list("{}", (1<<20)+1)}, + {"inbound counters", "inboundTraffic", list("{}", 65537)}, + {"online emails", "onlineEmails", list(`""`, (1<<20)+1)}, + {"online tree", "onlineTree", `{"guid":` + list(`""`, 1<<20) + `}`}, + {"active tree", "activeInboundTree", `{"guid":` + list(`""`, 1<<20) + `}`}, + {"last online", "lastOnlineMap", `{"guid":` + list("0", 1<<20) + `}`}, + } { + t.Run(tc.name, func(t *testing.T) { + valid := `{"version":1,"revision":"one","structure":{"inbounds":[],"attachments":[]},"clients":[],"inboundTraffic":[]}` + tick, legacy := 0, 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + if req.URL.Path != "/panel/api/inbounds/trafficSnapshot" { + legacy++ + t.Errorf("unexpected fallback: %s", req.URL.Path) + } + tick++ + body := valid + if tick == 2 { + body = `{"version":1,"revision":"one","structure":{"inbounds":[],"attachments":[]},"clients":[],"inboundTraffic":[],"` + tc.field + `":` + tc.value + `}` + } + if tick == 3 && req.URL.Query().Get("revision") != "" { + t.Error("invalid snapshot retained history") + } + fmt.Fprint(w, `{"success":true,"obj":`+body+`}`) + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + first, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + bad, err := remote.FetchTrafficSnapshot(context.Background()) + if bad != nil || !errors.Is(err, errRemoteListTooLong) { + t.Fatalf("oversize %s: snapshot=%v error=%v, want list limit", tc.name, bad, err) + } + last, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil || last == nil || last.StructuralRevision == first.StructuralRevision || legacy != 0 { + t.Fatalf("failed closed recovery: %+v %v legacy=%d", last, err, legacy) + } + }) + } +} + +func TestSnapshotDecodeCollectionBoundaries(t *testing.T) { + for _, tc := range []struct { + name string + count int + field string + }{ + {"clients", maxNodeSnapshotClients, "clients"}, + {"attachments", maxNodeSnapshotClients, "attachments"}, + {"inbound counters", maxNodeInbounds, "inboundTraffic"}, + {"catalog", maxNodeInbounds, "inbounds"}, + {"online emails", maxNodeMapValues, "onlineEmails"}, + } { + t.Run(tc.name, func(t *testing.T) { + item := "{}" + if tc.field == "onlineEmails" { + item = `""` + } + list := "[" + strings.Repeat(item+",", tc.count-1) + item + "]" + raw := `{"` + tc.field + `":` + list + `}` + if tc.field == "inbounds" || tc.field == "attachments" { + raw = `{"structure":` + raw + `}` + } + wire, err := decodeNodeTrafficSnapshot(json.RawMessage(raw)) + if err != nil { + t.Fatalf("at-limit payload rejected: %v", err) + } + got := 0 + switch tc.field { + case "clients": + got = len(wire.Clients) + case "attachments": + got = len(wire.Structure.Attachments) + case "inboundTraffic": + got = len(wire.InboundTraffic) + case "inbounds": + got = len(wire.Structure.Inbounds) + case "onlineEmails": + got = len(wire.OnlineEmails) + } + if got != tc.count { + t.Fatalf("decoded %d entries, want %d", got, tc.count) + } + }) + } + for _, raw := range []string{`{"clients":[}`, `{"clients":{}}`, `{"structure":{"inbounds":[{"clientStats":{}}]}}`, `{"onlineTree":[]}`, `{"lastOnlineMap":{"guid":"bad"}}`, `{"clients":[]} trailing`} { + if _, err := decodeNodeTrafficSnapshot(json.RawMessage(raw)); err == nil { + t.Fatalf("accepted malformed compact payload: %s", raw) + } + } +} + +func TestRemoteSnapshotLargeValidDeployment(t *testing.T) { + wire := NodeTrafficSnapshotV1{Version: 1, Revision: "large", Structure: &NodeSnapshotStructure{Inbounds: []*model.Inbound{{Id: 1, Tag: "one"}, {Id: 2, Tag: "two"}}, Attachments: []NodeSnapshotAttachment{}}, InboundTraffic: []NodeInboundTraffic{{ID: 1}, {ID: 2}}} + for id := 1; id <= 20000; id++ { + email := fmt.Sprintf("client-%d", id) + wire.Clients = append(wire.Clients, NodeClientTraffic{ID: id, InboundID: 1, Email: email, Enable: true, Total: 1000}) + wire.Structure.Attachments = append(wire.Structure.Attachments, NodeSnapshotAttachment{InboundID: 1, Email: email}, NodeSnapshotAttachment{InboundID: 2, Email: email}) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + if req.URL.Path != "/panel/api/inbounds/trafficSnapshot" { + t.Errorf("legacy fallback: %s", req.URL.Path) + } + response := wire + if req.URL.Query().Get("revision") == wire.Revision { + response.Structure = nil + } + response.Clients[0].Up++ + if err := json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": response}); err != nil { + t.Error(err) + } + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + for tick := 1; tick <= 3; tick++ { + snap, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(snap.Inbounds) != 2 || len(snap.Inbounds[0].ClientStats) != 20000 || len(snap.Inbounds[1].ClientStats) != 20000 || snap.Inbounds[1].ClientStats[0].Up != int64(tick) { + t.Fatalf("large deployment lost counters or attachments on tick %d", tick) + } + } +} + +func BenchmarkCompactSnapshotDecode(b *testing.B) { + wire := NodeTrafficSnapshotV1{Version: 1, Revision: "benchmark", InboundTraffic: []NodeInboundTraffic{}} + for id := 1; id <= 20000; id++ { + wire.Clients = append(wire.Clients, NodeClientTraffic{ID: id, InboundID: 1, Email: fmt.Sprintf("client-%d", id), Up: 100, Total: 1000, Enable: true}) + } + raw, err := json.Marshal(wire) + if err != nil { + b.Fatal(err) + } + for _, mode := range []string{"unbounded-baseline", "bounded"} { + b.Run(mode, func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(raw))) + for range b.N { + var decoded NodeTrafficSnapshotV1 + var err error + if mode == "bounded" { + decoded, err = decodeNodeTrafficSnapshot(raw) + } else { + err = json.Unmarshal(raw, &decoded) + } + if err != nil || len(decoded.Clients) != 20000 { + b.Fatalf("decode: %v", err) + } + } + }) + } +} diff --git a/internal/web/runtime/node_snapshot_malformed_test.go b/internal/web/runtime/node_snapshot_malformed_test.go new file mode 100644 index 000000000..850d2215e --- /dev/null +++ b/internal/web/runtime/node_snapshot_malformed_test.go @@ -0,0 +1,73 @@ +package runtime + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestRemoteSnapshotMalformedResponseClearsHistory(t *testing.T) { + valid := `{"version":1,"revision":"one","structure":{"inbounds":[],"attachments":[]},"clients":[],"inboundTraffic":[]}` + for _, bad := range []string{ + `{"version":2,"revision":"one","clients":[],"inboundTraffic":[]}`, + `{"version":1,"revision":"one","clients":null,"inboundTraffic":[]}`, + `{"version":1,"revision":"one","clients":{},"inboundTraffic":[]}`, + `{"version":1,"revision":"one","clients":[null],"inboundTraffic":[]}`, + `{"version":1,"revision":"one","clients":[],"inboundTraffic":[],"onlineTree":[]}`, + `{"version":1,"revision":"one","structure":{"inbounds":null,"attachments":[]},"clients":[],"inboundTraffic":[]}`, + `{"version":1,"revision":"one","clients":[}`, + } { + t.Run(bad, func(t *testing.T) { + tick := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + if req.URL.Path != "/panel/api/inbounds/trafficSnapshot" { + t.Errorf("malformed response triggered legacy fallback: %s", req.URL.Path) + } + tick++ + body := valid + if tick == 2 { + body = bad + } + if tick == 3 && req.URL.Query().Get("revision") != "" { + t.Error("malformed response retained revision") + } + fmt.Fprint(w, `{"success":true,"obj":`+body+`}`) + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + first, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + if snap, err := remote.FetchTrafficSnapshot(context.Background()); err == nil || snap != nil { + t.Fatalf("accepted malformed response: %+v %v", snap, err) + } + last, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil || last == nil || last.StructuralRevision == first.StructuralRevision { + t.Fatalf("failed recovery: %+v %v", last, err) + } + }) + } +} + +func TestSnapshotDecodeMapValueBoundary(t *testing.T) { + values := `[` + strings.Repeat(`"",`, maxNodeMapValues-3) + `""]` + for _, field := range []string{"onlineTree", "activeInboundTree"} { + wire, err := decodeNodeTrafficSnapshot([]byte(`{"` + field + `":{"guid":` + values + `}}`)) + if err != nil { + t.Fatalf("at-limit %s rejected: %v", field, err) + } + tree := wire.OnlineTree + if field == "activeInboundTree" { + tree = wire.ActiveInboundTree + } + if len(tree["guid"]) != maxNodeMapValues-2 { + t.Fatalf("lost %s values: %d", field, len(tree["guid"])) + } + } +} diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 07b16d5ed..ada3d9d75 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -75,6 +75,13 @@ type envelope struct { Obj json.RawMessage `json:"obj"` } +type remoteHTTPError struct { + code int + err error +} + +func (e *remoteHTTPError) Error() string { return e.err.Error() } + // remoteAPIError is a node-panel envelope failure (HTTP 200, success=false), // distinct from transport/HTTP-status errors so callers can trust its message. type remoteAPIError struct{ msg string } @@ -94,7 +101,15 @@ type Remote struct { // supportsZstd is learned from the node's X-3x-Node-Caps response header; once // seen, config pushes to this node are zstd-compressed. Old nodes never set // it, so they keep receiving plain bodies (mixed-version safe). - supportsZstd bool + supportsZstd bool + snapshotGate chan struct{} + snapshotCapsEpoch uint64 + snapshotSeenCapsEpoch uint64 + snapshotRevision string + snapshotGeneration uint64 + snapshotUnsupportedUntil time.Time + snapshotStructure *NodeSnapshotStructure + snapshotClients map[int]snapshotClientIdentity // nodeCaps is nil until the first response, even if that response advertises no capabilities. nodeCaps []string @@ -119,6 +134,7 @@ type RemoteInboundOption struct { func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { return &Remote{ node: n, + snapshotGate: make(chan struct{}, 1), remoteIDByTag: make(map[string]int), adoptedAliases: make(map[string]string), pushedFP: make(map[string]string), @@ -140,6 +156,9 @@ func (r *Remote) recordCaps(h http.Header) { caps := strings.Split(h.Get(wirecodec.CapsHeader), ",") r.mu.Lock() defer r.mu.Unlock() + if slices.Contains(caps, wirecodec.CapTrafficSnapshot) != slices.Contains(r.nodeCaps, wirecodec.CapTrafficSnapshot) { + r.snapshotCapsEpoch++ + } r.nodeCaps = caps if slices.Contains(caps, wirecodec.CapZstd) { r.supportsZstd = true @@ -375,7 +394,9 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo return nil, fmt.Errorf("%s %s: %w", method, path, err) } defer resp.Body.Close() - r.recordCaps(resp.Header) + if resp.StatusCode == http.StatusOK { + r.recordCaps(resp.Header) + } // Validate status before reading a success payload: a non-OK response's // body is never used beyond a short diagnostic, so don't let a node force us @@ -385,9 +406,9 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo if msg := bytes.TrimSpace(snippet); len(msg) > 0 { // %q quotes/escapes the untrusted node body so control characters or // newlines in it can't garble or inject into the error/log output. - return nil, fmt.Errorf("%s %s: HTTP %d: %q", method, path, resp.StatusCode, msg) + return nil, &remoteHTTPError{code: resp.StatusCode, err: fmt.Errorf("%s %s: HTTP %d: %q", method, path, resp.StatusCode, msg)} } - return nil, fmt.Errorf("%s %s: HTTP %d", method, path, resp.StatusCode) + return nil, &remoteHTTPError{code: resp.StatusCode, err: fmt.Errorf("%s %s: HTTP %d", method, path, resp.StatusCode)} } // Fast-fail on an honestly-declared oversize body; the LimitReader below is @@ -895,9 +916,10 @@ func (r *Remote) ResetInboundTraffic(ctx context.Context, ib *model.Inbound) err } type TrafficSnapshot struct { - Inbounds []*model.Inbound - OnlineEmails []string - ManagedAliases []string + StructuralRevision string + Inbounds []*model.Inbound + OnlineEmails []string + ManagedAliases []string // OnlineTree is the node's GUID-keyed online subtree (its own clients under // its panelGuid plus every descendant under theirs). Preferred over the flat // OnlineEmails so the master can attribute deeply nested clients to the real @@ -929,7 +951,7 @@ func (r *Remote) FetchHostGroups(ctx context.Context) ([]*entity.HostGroup, erro return groups, nil } -func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) { +func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) { snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}} envList, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) diff --git a/internal/web/runtime/remote_snapshot_test.go b/internal/web/runtime/remote_snapshot_test.go new file mode 100644 index 000000000..b3cddb33b --- /dev/null +++ b/internal/web/runtime/remote_snapshot_test.go @@ -0,0 +1,196 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestRemoteSnapshotNegotiatesUnchangedStructure(t *testing.T) { + full, compact := 0, 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + switch r.URL.Path { + case "/panel/api/inbounds/list": + full++ + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"edge","settings":{"clients":[]},"clientStats":[]}]}`) + case "/panel/api/inbounds/trafficSnapshot": + compact++ + structure := `{"inbounds":[{"id":7,"tag":"edge","settings":{"clients":[]}}],"attachments":[]}` + if r.URL.Query().Get("revision") == "revision1" { + structure = "null" + } + fmt.Fprintf(w, `{"success":true,"obj":{"version":1,"revision":"revision1","structure":%s,"inboundTraffic":[{"id":7,"up":%d,"down":0}],"clients":[],"lastOnlineMap":{},"onlineTree":{},"activeInboundTree":{}}}`, structure, compact) + default: + fmt.Fprint(w, `{"success":true,"obj":{}}`) + } + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + for i := range 3 { + snapshot, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(snapshot.Inbounds) != 1 || snapshot.Inbounds[0].Tag != "edge" { + t.Fatalf("lost structure: %+v", snapshot) + } + if i > 0 && snapshot.Inbounds[0].Up != int64(i) { + t.Fatalf("stale counters: %+v", snapshot.Inbounds[0]) + } + snapshot.Inbounds[0].Tag = "caller-modified" + } + if full != 1 || compact != 2 { + t.Fatalf("full=%d compact=%d, want 1 full then 2 compact snapshots", full, compact) + } +} + +func TestRemoteSnapshotOnlyUnsupportedFallsBack(t *testing.T) { + for _, code := range []int{404, 405, 401, 403, 500} { + t.Run(fmt.Sprint(code), func(t *testing.T) { + full, compact := 0, 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + switch req.URL.Path { + case "/panel/api/inbounds/trafficSnapshot": + compact++ + http.Error(w, "blocked", code) + case "/panel/api/inbounds/list": + full++ + fmt.Fprint(w, `{"success":true,"obj":[]}`) + default: + fmt.Fprint(w, `{"success":true,"obj":{}}`) + } + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + for range 3 { + snap, err := remote.FetchTrafficSnapshot(context.Background()) + if code == 404 || code == 405 { + if err != nil || len(snap.Inbounds) != 0 { + t.Fatalf("fallback: %v %+v", err, snap) + } + } else { + var status *remoteHTTPError + if snap != nil || !errors.As(err, &status) || status.code != code { + t.Fatalf("masked error: %+v %v", snap, err) + } + } + } + if code == 404 || code == 405 { + if compact != 1 || full != 3 { + t.Fatalf("404 storm or no fallback: compact=%d full=%d", compact, full) + } + } else if full != 0 || compact != 3 { + t.Fatalf("auth/server error downgraded: compact=%d full=%d", compact, full) + } + }) + } +} + +func TestRemoteSnapshotRejectsUnknownPartialAndRecovers(t *testing.T) { + var tick atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + switch tick.Add(1) { + case 1: + fmt.Fprint(w, `{"success":true,"obj":{"version":1,"revision":"one","structure":{"inbounds":[],"attachments":[]},"clients":[],"inboundTraffic":[]}}`) + case 2: + fmt.Fprint(w, `{"success":true,"obj":{"version":1,"revision":"unknown","clients":[],"inboundTraffic":[]}}`) + default: + if req.URL.Query().Get("revision") != "" { + t.Error("failed snapshot retained revision") + } + fmt.Fprint(w, `{"success":true,"obj":{"version":1,"revision":"two","structure":{"inbounds":[],"attachments":[]},"clients":[],"inboundTraffic":[]}}`) + } + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + first, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil || first.Inbounds == nil || len(first.Inbounds) != 0 { + t.Fatalf("valid empty rejected: %+v %v", first, err) + } + bad, err := remote.FetchTrafficSnapshot(context.Background()) + if bad != nil || err == nil || !strings.Contains(err.Error(), "no matching structure") { + t.Fatalf("unknown partial trusted: %+v %v", bad, err) + } + last, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil || last.Inbounds == nil || last.StructuralRevision == first.StructuralRevision { + t.Fatalf("recovery failed: %+v %v", last, err) + } +} + +func TestRemoteSnapshotConcurrentWaitHonorsDeadline(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + close(entered) + <-release + fmt.Fprint(w, `{"success":true,"obj":{"version":1,"revision":"one","structure":{"inbounds":[],"attachments":[]},"clients":[],"inboundTraffic":[]}}`) + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + done := make(chan error, 1) + go func() { _, err := remote.FetchTrafficSnapshot(context.Background()); done <- err }() + <-entered + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + snap, err := remote.FetchTrafficSnapshot(ctx) + close(release) + if snap != nil || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("wait ignored cancellation: %+v %v", snap, err) + } + if err := <-done; err != nil { + t.Fatal(err) + } +} + +func TestSnapshotExpansionRequiresCompleteCounters(t *testing.T) { + structure := &NodeSnapshotStructure{Inbounds: []*model.Inbound{{Id: 1}, {Id: 2}}, Attachments: []NodeSnapshotAttachment{{InboundID: 2, Email: "shared"}}} + wire := NodeTrafficSnapshotV1{InboundTraffic: []NodeInboundTraffic{{ID: 1}}, Clients: []NodeClientTraffic{}} + if snap, err := wire.expand(structure); snap != nil || err == nil || err.Error() != "missing snapshot inbound counters" { + t.Fatalf("incomplete accepted: %+v %v", snap, err) + } + wire.InboundTraffic = append(wire.InboundTraffic, NodeInboundTraffic{ID: 2}) + wire.Clients = []NodeClientTraffic{{InboundID: 1, Email: "shared", Up: 50}, {InboundID: 1, Email: ""}, {InboundID: 2, Email: ""}} + snap, err := wire.expand(structure) + if err != nil { + t.Fatal(err) + } + if len(snap.Inbounds[0].ClientStats) != 2 || len(snap.Inbounds[1].ClientStats) != 2 || snap.Inbounds[1].ClientStats[1].Up != 50 { + t.Fatalf("lost shared/orphan stats: %+v", snap.Inbounds) + } +} + +func TestRemoteSnapshotRejectsTruncatedUnchangedCounters(t *testing.T) { + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + if calls.Add(1) == 1 { + fmt.Fprint(w, `{"success":true,"obj":{"version":1,"revision":"one","structure":{"inbounds":[{"id":1,"tag":"edge","settings":{"clients":[]}}],"attachments":[]},"inboundTraffic":[{"id":1}],"clients":[{"id":1,"inboundId":1,"email":"one","up":100}]}}`) + } else { + fmt.Fprint(w, `{"success":true,"obj":{"version":1,"revision":"one","inboundTraffic":[{"id":1}],"clients":[]}}`) + } + })) + defer server.Close() + remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil) + remote.recordCaps(http.Header{"X-3x-Node-Caps": []string{"traffic-snapshot-v1"}}) + first, err := remote.FetchTrafficSnapshot(context.Background()) + if err != nil || len(first.Inbounds[0].ClientStats) != 1 { + t.Fatalf("initial counters: %+v %v", first, err) + } + partial, err := remote.FetchTrafficSnapshot(context.Background()) + if partial != nil || err == nil || err.Error() != "traffic snapshot omitted client counters" { + t.Fatalf("partial counters could reach full merge: %+v %v", partial, err) + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index b962941f2..4761e279d 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -34,6 +34,7 @@ import ( ) type InboundService struct { + snapshotMerges map[int]*nodeMergeCache clientService ClientService fallbackService FallbackService // FromNodeSync marks a master push: the row was validated where the operator @@ -190,7 +191,15 @@ func normalizeInboundShareAddressColumns(tx *gorm.DB) error { // GetInbounds retrieves all inbounds for a specific user with client stats. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { - db := database.GetDB() + inbounds, err := s.getInboundsFromDB(database.GetDB(), userId) + if err != nil { + return nil, err + } + s.annotateLocalOriginGuid(inbounds) + return inbounds, nil +} + +func (s *InboundService) getInboundsFromDB(db *gorm.DB, userId int) ([]*model.Inbound, error) { var inbounds []*model.Inbound err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error if err == nil { @@ -201,7 +210,6 @@ func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { } s.enrichClientStats(db, inbounds) s.annotateFallbackParents(db, inbounds) - s.annotateLocalOriginGuid(inbounds) return inbounds, nil } diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 604d0e5e8..6f855bda0 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -567,6 +567,8 @@ func snapshotAttachedEmails(settings string) (map[string]struct{}, bool) { } func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { + nodeSnapshotMergeMu.Lock() + defer nodeSnapshotMergeMu.Unlock() if snap == nil || nodeID <= 0 { return false, nil } @@ -601,12 +603,37 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi return selfKey } - var central []model.Inbound - if err := db.Model(model.Inbound{}). - Where("node_id = ?", nodeID). - Find(¢ral).Error; err != nil { + masterRevision, versions, err := masterSnapshotRevision(db, nodeID, snap, &nodeRow, selfKey) + if err != nil { return false, err } + cached := s.snapshotMerges[nodeID] + skipStructure := !dirty && !justPushed && masterRevision != "" && cached != nil && cached.db == db && cached.revision == masterRevision + var central []model.Inbound + var cachedAliases map[string]*model.Inbound + if skipStructure { + central = append([]model.Inbound(nil), cached.central...) + totals := make(map[int]snapshotInboundVersion, len(versions)) + for _, v := range versions { + totals[v.ID] = v + } + for i := range central { + central[i].Up = totals[central[i].Id].Up + central[i].Down = totals[central[i].Id].Down + } + var valid bool + cachedAliases, valid = cached.restoreInboundAliases(nodeID, snap, central) + if !valid { + skipStructure = false + delete(s.snapshotMerges, nodeID) + } + } + if !skipStructure { + if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(¢ral).Error; err != nil { + return false, err + } + } + // Index under the stored tag and its prefix-flipped form so a snap matches // whether the n- prefix lives on the node side, the central side, or // neither — a mismatch must never spawn a duplicate central inbound. @@ -629,12 +656,25 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi for i := range central { ids = append(ids, central[i].Id) } - if err := db.Model(xray.ClientTraffic{}). - Where("inbound_id IN ?", ids). - Find(¢ralClientStats).Error; err != nil { + query := db.Model(xray.ClientTraffic{}).Where("inbound_id IN ?", ids) + if masterRevision != "" { + query = query.Order("id") + } + if err := query.Find(¢ralClientStats).Error; err != nil { return false, err } } + lifecycleRevision := "" + if masterRevision != "" { + lifecycleRevision = snapshotLifecycleRevision(centralClientStats) + } + if skipStructure && cached.lifecycleRevision != lifecycleRevision { + skipStructure = false + } + if skipStructure { + maps.Copy(tagToCentral, cachedAliases) + } + type csKey struct { inboundID int email string @@ -709,7 +749,11 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } nodeEmailTotals[email] = cur } - if clients, err := s.GetClients(snapIb); err == nil { + if skipStructure { + for email := range cached.attached[snapIb.Id] { + reportedEmails[email] = struct{}{} + } + } else if clients, err := s.GetClients(snapIb); err == nil { for _, client := range clients { reportedEmails[client.Email] = struct{}{} } @@ -757,17 +801,20 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } }() - claims, err := loadNodeClientClaims(tx, nodeID, snap) - if err != nil { - return false, err - } - // The raw blob stays for the usage-only lookup: those entries are refused from the stored - // settings, yet the node's usage under them still counts. + claims := &nodeClientClaims{} rawSettings := make(map[*model.Inbound]string, len(snap.Inbounds)) - for _, snapIb := range snap.Inbounds { - if snapIb != nil { - rawSettings[snapIb] = snapIb.Settings - snapIb.Settings = claims.apply(snapIb.Settings) + if !skipStructure { + claims, err = loadNodeClientClaims(tx, nodeID, snap) + if err != nil { + return false, err + } + // The raw blob stays for the usage-only lookup: those entries are refused from the stored + // settings, yet the node's usage under them still counts. + for _, snapIb := range snap.Inbounds { + if snapIb != nil { + rawSettings[snapIb] = snapIb.Settings + snapIb.Settings = claims.apply(snapIb.Settings) + } } } @@ -787,319 +834,337 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi newInboundIDs := make(map[int]struct{}) - // Every pass below walks a central inbound's clients once per snapshot entry that - // resolves to it, so only the first such entry is merged; repeats are dropped. - mergedCentral := make(map[int]struct{}, len(central)) + if !skipStructure { + // Every pass below walks a central inbound's clients once per snapshot entry that + // resolves to it, so only the first such entry is merged; repeats are dropped. + mergedCentral := make(map[int]struct{}, len(central)) - snapTags := make(map[string]struct{}, len(snap.Inbounds)) - oversizeTags := map[string]string{} - for snapIdx, snapIb := range snap.Inbounds { - if snapIb == nil { - continue - } - snapTags[snapIb.Tag] = struct{}{} - // Record the prefix-flipped form too so the orphan sweep below keeps a - // central inbound whether its tag carries the n- prefix or not. - if prefix != "" { - if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found { - snapTags[stripped] = struct{}{} - } else { - snapTags[prefix+snapIb.Tag] = struct{}{} + snapTags := make(map[string]struct{}, len(snap.Inbounds)) + oversizeTags := map[string]string{} + for snapIdx, snapIb := range snap.Inbounds { + if snapIb == nil { + continue } - } - - c, ok := tagToCentral[snapIb.Tag] - if !ok { - origin := originGuidFor(snapIb) - var compatible []*model.Inbound - for i := range central { - candidate := ¢ral[i] - // An empty origin is a master-created inbound not yet tag-matched: hosted here. - candidateOrigin := candidate.OriginNodeGuid - if candidateOrigin == "" { - candidateOrigin = selfKey - } - if candidateOrigin == origin && - candidate.Port == snapIb.Port && - candidate.Protocol == snapIb.Protocol && - strings.TrimSpace(candidate.Listen) == strings.TrimSpace(snapIb.Listen) { - compatible = append(compatible, candidate) + snapTags[snapIb.Tag] = struct{}{} + // Record the prefix-flipped form too so the orphan sweep below keeps a + // central inbound whether its tag carries the n- prefix or not. + if prefix != "" { + if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found { + snapTags[stripped] = struct{}{} + } else { + snapTags[prefix+snapIb.Tag] = struct{}{} } } - switch len(compatible) { - case 1: - c, ok = compatible[0], true - tagToCentral[snapIb.Tag] = c - snapTags[c.Tag] = struct{}{} - case 0: - // A genuinely new inbound follows the normal adoption path. - default: - return false, fmt.Errorf("setRemoteTraffic: inbound %q has ambiguous compatible central aliases", snapIb.Tag) + + c, ok := tagToCentral[snapIb.Tag] + if !ok { + origin := originGuidFor(snapIb) + var compatible []*model.Inbound + for i := range central { + candidate := ¢ral[i] + // An empty origin is a master-created inbound not yet tag-matched: hosted here. + candidateOrigin := candidate.OriginNodeGuid + if candidateOrigin == "" { + candidateOrigin = selfKey + } + if candidateOrigin == origin && + candidate.Port == snapIb.Port && + candidate.Protocol == snapIb.Protocol && + strings.TrimSpace(candidate.Listen) == strings.TrimSpace(snapIb.Listen) { + compatible = append(compatible, candidate) + } + } + switch len(compatible) { + case 1: + c, ok = compatible[0], true + tagToCentral[snapIb.Tag] = c + snapTags[c.Tag] = struct{}{} + case 0: + // A genuinely new inbound follows the normal adoption path. + default: + return false, fmt.Errorf("setRemoteTraffic: inbound %q has ambiguous compatible central aliases", snapIb.Tag) + } } - } - if ok { - if _, merged := mergedCentral[c.Id]; merged { + if ok { + if _, merged := mergedCentral[c.Id]; merged { + snap.Inbounds[snapIdx] = nil + continue + } + mergedCentral[c.Id] = struct{}{} + } + if reason := oversizeNodeInbound(snapIb); reason != "" { + oversizeTags[snapIb.Tag] = reason snap.Inbounds[snapIdx] = nil continue } - mergedCentral[c.Id] = struct{}{} - } - if reason := oversizeNodeInbound(snapIb); reason != "" { - oversizeTags[snapIb.Tag] = reason - snap.Inbounds[snapIdx] = nil - continue - } - if !ok { - if dirty { - continue - } - // Try snap.Tag first; on collision fall back to the n- - // prefixed form so local+node can both own the same port. - pickFreeTag := func() (string, error) { - candidates := []string{snapIb.Tag} - if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) { - candidates = append(candidates, prefix+snapIb.Tag) + if !ok { + if dirty { + continue } - for _, t := range candidates { - var owner model.Inbound - err := tx.Where("tag = ?", t).First(&owner).Error - if errors.Is(err, gorm.ErrRecordNotFound) { - return t, nil + // Try snap.Tag first; on collision fall back to the n- + // prefixed form so local+node can both own the same port. + pickFreeTag := func() (string, error) { + candidates := []string{snapIb.Tag} + if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) { + candidates = append(candidates, prefix+snapIb.Tag) } - if err != nil { - return "", err + for _, t := range candidates { + var owner model.Inbound + err := tx.Where("tag = ?", t).First(&owner).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return t, nil + } + if err != nil { + return "", err + } } + return "", nil } - return "", nil - } - chosenTag, err := pickFreeTag() - if err != nil { - logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err) - continue - } - if chosenTag == "" { - key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag) - if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen { - logger.Warningf( - "setRemoteTraffic: tag %q from node %d collides with an existing inbound even after the n%d- prefix — skipping (rename one side to remove the duplicate)", - snapIb.Tag, nodeID, nodeID, - ) + chosenTag, err := pickFreeTag() + if err != nil { + logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err) + continue } - continue - } - reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)) - newIb := model.Inbound{ - UserId: defaultUserId, - NodeID: &nodeID, - OriginNodeGuid: originGuidFor(snapIb), - Tag: chosenTag, - Listen: snapIb.Listen, - Port: snapIb.Port, - Protocol: snapIb.Protocol, - Settings: snapIb.Settings, - StreamSettings: snapIb.StreamSettings, - Sniffing: snapIb.Sniffing, - TrafficReset: snapIb.TrafficReset, - TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay), - LastTrafficResetTime: snapIb.LastTrafficResetTime, - Enable: snapIb.Enable, - Remark: snapIb.Remark, - SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex), - ExcludeFromSub: snapIb.ExcludeFromSub, - Total: snapIb.Total, - ExpiryTime: snapIb.ExpiryTime, - Up: snapIb.Up, - Down: snapIb.Down, - ShareAddrStrategy: "node", - DisableFlow: snapIb.DisableFlow, - - PreserveClientTraffic: snapIb.PreserveClientTraffic, - } - if err := tx.Create(&newIb).Error; err != nil { - logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err) - continue - } - tagToCentral[snapIb.Tag] = &newIb - if newIb.Tag != snapIb.Tag { - tagToCentral[newIb.Tag] = &newIb - } - rows, skipped := adoptedHostRows(hostGroups, snapIb.Id, newIb.Id, hostRowBudget) - hostGroupsSkipped += skipped - if len(rows) > 0 { - if err := tx.Create(&rows).Error; err != nil { - logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err) - } else { - hostRowBudget -= len(rows) - } - } - newInboundIDs[newIb.Id] = struct{}{} - pendingAdopts[newIb.Id] = pendingAdopt{wireSettings: snapIb.Settings} - mergedCentral[newIb.Id] = struct{}{} - structuralChange = true - continue - } - - inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs - - // Adopting the node's settings verbatim would re-add a client the master - // deleted moments ago if this snapshot was fetched before the deletion - // push landed — filter just-deleted emails out while their tombstone lives. - adoptedSettings := snapIb.Settings - if stripped, changed := stripTombstonedClients(adoptedSettings); changed { - adoptedSettings = stripped - } - if deduped, changed := dedupeSettingsClients(adoptedSettings); changed { - adoptedSettings = deduped - } - updates := map[string]any{} - if !dirty && snapshotDropsEveryHubClient(tx, c.Id, adoptedSettings) { - degradedInbounds[c.Id] = c.Tag - } else if !dirty { - pendingAdopts[c.Id] = pendingAdopt{wireSettings: adoptedSettings, config: nodeInboundConfigUpdates(c, snapIb)} - } - if (snapIb.Up != c.Up || snapIb.Down != c.Down) && (!inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down)) { - updates["up"] = snapIb.Up - updates["down"] = snapIb.Down - } - // Physical-home attribution is independent of config-dirty state, so - // keep it current even while the node has pending offline edits. Writes - // once to backfill an existing row, then stays equal (#4983). - if og := originGuidFor(snapIb); c.OriginNodeGuid != og { - updates["origin_node_guid"] = og - } - - if len(updates) > 0 { - if err := tx.Model(model.Inbound{}). - Where("id = ?", c.Id). - Updates(updates).Error; err != nil { - return false, err - } - } - } - - logOversizeNodeInbounds(nodeID, oversizeTags) - if hostGroupsSkipped > 0 { - logger.Warningf( - "setRemoteTraffic: node %d: left out %d host group adoption(s) — a group is limited to %d bytes and the node's inbounds to %d host rows", - nodeID, hostGroupsSkipped, maxAdoptedHostGroupBytes, maxAdoptedHostRows, - ) - } - - // The inbound each reported email now lives under, so a swept inbound's - // accumulator rows follow the email instead of being dropped and re-seeded at 0. - snapEmailHome := make(map[string]int, len(snapEmailsAll)) - for _, snapIb := range snap.Inbounds { - if snapIb == nil { - continue - } - home, ok := tagToCentral[snapIb.Tag] - if !ok { - continue - } - for i := range snapIb.ClientStats { - if _, taken := snapEmailHome[snapIb.ClientStats[i].Email]; !taken { - snapEmailHome[snapIb.ClientStats[i].Email] = home.Id - } - } - } - - for _, c := range central { - if dirty { - continue - } - // A node inbound created disabled is never delivered, so its absence from the snapshot - // is ambiguous; a copy the node once reported (it has an origin) is not. - if !c.Enable && c.OriginNodeGuid == "" { - continue - } - if len(snapTags) == 0 { - // A node mid-restart or with a transient DB error can return an empty - // inbound list with success=true. Treat "zero inbounds reported" as - // "nothing to say", not "delete all my inbounds" — otherwise a blip - // wipes the node's central inbounds and every client on them (and - // resets traffic history on re-create). A real per-inbound deletion - // still sweeps, because the node keeps reporting its other inbounds. - continue - } - if _, kept := snapTags[c.Tag]; kept { - continue - } - if unmanagedTag(c.Tag) { - continue - } - // This drops the central inbound and its unreported clients' history, so say - // so: silent removal is indistinguishable from an inbound never arriving. - logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port) - var goneEmails []string - if err := tx.Model(xray.ClientTraffic{}). - Where("inbound_id = ?", c.Id). - Pluck("email", &goneEmails).Error; err != nil { - return false, err - } - if len(goneEmails) > 0 { - // Baselines are per (node, email), not per inbound: keep them for - // emails the snapshot still reports under a sibling inbound (#5202). - baselineGone := make([]string, 0, len(goneEmails)) - for _, e := range goneEmails { - if _, still := snapEmailsAll[e]; !still { - baselineGone = append(baselineGone, e) - } - } - // Chunk to avoid SQLite bind var limit when a node has many clients - // removed (e.g. after API bulk delete or structural change on node inbound). - for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) { - if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch). - Delete(&model.NodeClientTraffic{}).Error; err != nil { - return false, err - } - } - // The per-email row is the shared accumulator across every inbound - // (and node) the email is attached to. Only drop it when this was the - // email's last inbound — wiping it while a sibling still feeds it - // loses the summed history, and the next node sync would re-seed the - // row with that node's counter alone. - sharedEmails, sErr := s.emailsUsedByOtherInbounds(tx, goneEmails, c.Id) - if sErr != nil { - return false, sErr - } - delEmails := make([]string, 0, len(goneEmails)) - rehome := make(map[int][]string) - for _, e := range goneEmails { - if home, still := snapEmailHome[e]; still { - rehome[home] = append(rehome[home], e) - if row, ok := centralCS[csKey{c.Id, e}]; ok { - delete(centralCS, csKey{c.Id, e}) - row.InboundId = home - centralCS[csKey{home, e}] = row + if chosenTag == "" { + key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag) + if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen { + logger.Warningf( + "setRemoteTraffic: tag %q from node %d collides with an existing inbound even after the n%d- prefix — skipping (rename one side to remove the duplicate)", + snapIb.Tag, nodeID, nodeID, + ) } continue } - if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] { - delEmails = append(delEmails, e) + reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)) + newIb := model.Inbound{ + UserId: defaultUserId, + NodeID: &nodeID, + OriginNodeGuid: originGuidFor(snapIb), + Tag: chosenTag, + Listen: snapIb.Listen, + Port: snapIb.Port, + Protocol: snapIb.Protocol, + Settings: snapIb.Settings, + StreamSettings: snapIb.StreamSettings, + Sniffing: snapIb.Sniffing, + TrafficReset: snapIb.TrafficReset, + TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay), + LastTrafficResetTime: snapIb.LastTrafficResetTime, + Enable: snapIb.Enable, + Remark: snapIb.Remark, + SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex), + ExcludeFromSub: snapIb.ExcludeFromSub, + Total: snapIb.Total, + ExpiryTime: snapIb.ExpiryTime, + Up: snapIb.Up, + Down: snapIb.Down, + ShareAddrStrategy: "node", + DisableFlow: snapIb.DisableFlow, + PreserveClientTraffic: snapIb.PreserveClientTraffic, + } + if err := tx.Create(&newIb).Error; err != nil { + logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err) + continue + } + tagToCentral[snapIb.Tag] = &newIb + if newIb.Tag != snapIb.Tag { + tagToCentral[newIb.Tag] = &newIb + } + rows, skipped := adoptedHostRows(hostGroups, snapIb.Id, newIb.Id, hostRowBudget) + hostGroupsSkipped += skipped + if len(rows) > 0 { + if err := tx.Create(&rows).Error; err != nil { + logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err) + } else { + hostRowBudget -= len(rows) + } + } + newInboundIDs[newIb.Id] = struct{}{} + pendingAdopts[newIb.Id] = pendingAdopt{wireSettings: snapIb.Settings} + mergedCentral[newIb.Id] = struct{}{} + structuralChange = true + continue + } + + inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs + + // Adopting the node's settings verbatim would re-add a client the master + // deleted moments ago if this snapshot was fetched before the deletion + // push landed — filter just-deleted emails out while their tombstone lives. + adoptedSettings := snapIb.Settings + if stripped, changed := stripTombstonedClients(adoptedSettings); changed { + adoptedSettings = stripped + } + if deduped, changed := dedupeSettingsClients(adoptedSettings); changed { + adoptedSettings = deduped + } + updates := map[string]any{} + if !dirty && snapshotDropsEveryHubClient(tx, c.Id, adoptedSettings) { + degradedInbounds[c.Id] = c.Tag + } else if !dirty { + pendingAdopts[c.Id] = pendingAdopt{wireSettings: adoptedSettings, config: nodeInboundConfigUpdates(c, snapIb)} + } + if (snapIb.Up != c.Up || snapIb.Down != c.Down) && (!inGrace || snapIb.Up+snapIb.Down <= c.Up+c.Down) { + updates["up"] = snapIb.Up + updates["down"] = snapIb.Down + } + // Physical-home attribution is independent of config-dirty state, so + // keep it current even while the node has pending offline edits. Writes + // once to backfill an existing row, then stays equal (#4983). + if og := originGuidFor(snapIb); c.OriginNodeGuid != og { + updates["origin_node_guid"] = og + } + + if len(updates) > 0 { + if err := tx.Model(model.Inbound{}). + Where("id = ?", c.Id). + Updates(updates).Error; err != nil { + return false, err } } - for home, emails := range rehome { - for _, batch := range chunkStrings(emails, sqliteMaxVars) { - if err := tx.Model(xray.ClientTraffic{}). - Where("inbound_id = ? AND email IN ?", c.Id, batch). - Update("inbound_id", home).Error; err != nil { + } + + logOversizeNodeInbounds(nodeID, oversizeTags) + if hostGroupsSkipped > 0 { + logger.Warningf( + "setRemoteTraffic: node %d: left out %d host group adoption(s) — a group is limited to %d bytes and the node's inbounds to %d host rows", + nodeID, hostGroupsSkipped, maxAdoptedHostGroupBytes, maxAdoptedHostRows, + ) + } + + // The inbound each reported email now lives under, so a swept inbound's + // accumulator rows follow the email instead of being dropped and re-seeded at 0. + snapEmailHome := make(map[string]int, len(snapEmailsAll)) + for _, snapIb := range snap.Inbounds { + if snapIb == nil { + continue + } + home, ok := tagToCentral[snapIb.Tag] + if !ok { + continue + } + for i := range snapIb.ClientStats { + if _, taken := snapEmailHome[snapIb.ClientStats[i].Email]; !taken { + snapEmailHome[snapIb.ClientStats[i].Email] = home.Id + } + } + } + + for _, c := range central { + if dirty { + continue + } + // A node inbound created disabled is never delivered, so its absence from the snapshot + // is ambiguous; a copy the node once reported (it has an origin) is not. + if !c.Enable && c.OriginNodeGuid == "" { + continue + } + if len(snapTags) == 0 { + // A node mid-restart or with a transient DB error can return an empty + // inbound list with success=true. Treat "zero inbounds reported" as + // "nothing to say", not "delete all my inbounds" — otherwise a blip + // wipes the node's central inbounds and every client on them (and + // resets traffic history on re-create). A real per-inbound deletion + // still sweeps, because the node keeps reporting its other inbounds. + continue + } + if _, kept := snapTags[c.Tag]; kept { + continue + } + if unmanagedTag(c.Tag) { + continue + } + // This drops the central inbound and its unreported clients' history, so say + // so: silent removal is indistinguishable from an inbound never arriving. + logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port) + var goneEmails []string + if err := tx.Model(xray.ClientTraffic{}). + Where("inbound_id = ?", c.Id). + Pluck("email", &goneEmails).Error; err != nil { + return false, err + } + if len(goneEmails) > 0 { + // Baselines are per (node, email), not per inbound: keep them for + // emails the snapshot still reports under a sibling inbound (#5202). + baselineGone := make([]string, 0, len(goneEmails)) + for _, e := range goneEmails { + if _, still := snapEmailsAll[e]; !still { + baselineGone = append(baselineGone, e) + } + } + // Chunk to avoid SQLite bind var limit when a node has many clients + // removed (e.g. after API bulk delete or structural change on node inbound). + for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) { + if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch). + Delete(&model.NodeClientTraffic{}).Error; err != nil { + return false, err + } + } + // The per-email row is the shared accumulator across every inbound + // (and node) the email is attached to. Only drop it when this was the + // email's last inbound — wiping it while a sibling still feeds it + // loses the summed history, and the next node sync would re-seed the + // row with that node's counter alone. + sharedEmails, sErr := s.emailsUsedByOtherInbounds(tx, goneEmails, c.Id) + if sErr != nil { + return false, sErr + } + delEmails := make([]string, 0, len(goneEmails)) + rehome := make(map[int][]string) + for _, e := range goneEmails { + if home, still := snapEmailHome[e]; still { + rehome[home] = append(rehome[home], e) + if row, ok := centralCS[csKey{c.Id, e}]; ok { + delete(centralCS, csKey{c.Id, e}) + row.InboundId = home + centralCS[csKey{home, e}] = row + } + continue + } + if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] { + delEmails = append(delEmails, e) + } + } + for home, emails := range rehome { + for _, batch := range chunkStrings(emails, sqliteMaxVars) { + if err := tx.Model(xray.ClientTraffic{}). + Where("inbound_id = ? AND email IN ?", c.Id, batch). + Update("inbound_id", home).Error; err != nil { + return false, err + } + } + } + for _, batch := range chunkStrings(delEmails, sqliteMaxVars) { + if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch). + Delete(&xray.ClientTraffic{}).Error; err != nil { return false, err } } } - for _, batch := range chunkStrings(delEmails, sqliteMaxVars) { - if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch). - Delete(&xray.ClientTraffic{}).Error; err != nil { + if err := s.deleteInboundRow(tx, c.Id); err != nil { + return false, err + } + delete(tagToCentral, c.Tag) + sweptTags = append(sweptTags, c.Tag) + structuralChange = true + } + + } else { + for _, ib := range snap.Inbounds { + if ib == nil { + continue + } + c := tagToCentral[ib.Tag] + if c == nil { + continue + } + inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs + if !inGrace || ib.Up+ib.Down <= c.Up+c.Down { + if err := tx.Model(&model.Inbound{}).Where("id = ?", c.Id).Updates(map[string]any{"up": ib.Up, "down": ib.Down}).Error; err != nil { return false, err } } } - if err := s.deleteInboundRow(tx, c.Id); err != nil { - return false, err - } - delete(tagToCentral, c.Tag) - sweptTags = append(sweptTags, c.Tag) - structuralChange = true } for _, snapIb := range snap.Inbounds { @@ -1113,7 +1178,13 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi snapEmails := make(map[string]struct{}, len(snapIb.ClientStats)) // Parsed once per inbound on the first renewal candidate, not per client. var snapExpiries map[string]int64 - attachedOnNode, membershipKnown := snapshotAttachedEmails(snapIb.Settings) + var attachedOnNode map[string]struct{} + var membershipKnown bool + if skipStructure { + attachedOnNode, membershipKnown = cached.attached[snapIb.Id] + } else { + attachedOnNode, membershipKnown = snapshotAttachedEmails(snapIb.Settings) + } usageOnly := claims.usageOnlyIn(rawSettings[snapIb]) if membershipKnown { maps.Copy(attachedOnNode, usageOnly) @@ -1298,6 +1369,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + if skipStructure { + continue + } for k, existing := range centralCS { if dirty { continue @@ -1340,182 +1414,184 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - type oldSet struct { - inboundID int - emails map[string]struct{} - } - var perInboundOld []oldSet syncFailedInbounds := map[int]struct{}{} - for _, snapIb := range snap.Inbounds { - if snapIb == nil { - continue + if !skipStructure || structuralChange { + type oldSet struct { + inboundID int + emails map[string]struct{} } - c, ok := tagToCentral[snapIb.Tag] - if !ok { - continue - } - if dirty { - continue - } - var oldEmailsRows []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", c.Id). - Pluck("email", &oldEmailsRows).Error; err == nil { - oldEmails := make(map[string]struct{}, len(oldEmailsRows)) - for _, e := range oldEmailsRows { - if e != "" { - oldEmails[e] = struct{}{} - } - } - perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails}) - } - - clients, gcErr := s.GetClients(snapIb) - if gcErr != nil { - logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr) - syncFailedInbounds[c.Id] = struct{}{} - continue - } - csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats)) - for _, cs := range snapIb.ClientStats { - csByEmail[cs.Email] = cs - } - filtered := clients[:0] - for i := range clients { - if isClientEmailTombstoned(clients[i].Email) { + var perInboundOld []oldSet + for _, snapIb := range snap.Inbounds { + if snapIb == nil { continue } - existing := statByEmail[clients[i].Email] - var csPtr *xray.ClientTraffic - if cs, hit := csByEmail[clients[i].Email]; hit { - csCopy := cs - csPtr = &csCopy + c, ok := tagToCentral[snapIb.Tag] + if !ok { + continue } - applyMasterClientLifecycle(&clients[i], existing, csPtr) - filtered = append(filtered, clients[i]) - } - // A degraded node (reset/restart/removal) reports zero clients for an inbound the - // hub populates; adopting it empties links and ReapSyncOrphans deletes shared clients (#6734). - if _, degraded := degradedInbounds[c.Id]; degraded { - logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub has %d attached — keeping them and re-pushing", nodeID, snapIb.Tag, len(oldEmailsRows)) - syncFailedInbounds[c.Id] = struct{}{} - continue - } - localEmails := make([]string, 0, len(filtered)) - for i := range filtered { - if filtered[i].Email != "" { - localEmails = append(localEmails, filtered[i].Email) - } - } - commentByEmail := make(map[string]string, len(localEmails)) - for _, batch := range chunkStrings(localEmails, sqlInChunk) { - var localMeta []struct { - Email string - Comment string `gorm:"column:comment"` + if dirty { + continue } + var oldEmailsRows []string if err := tx.Table("clients"). - Select("email, comment"). - Where("email IN ?", batch). - Find(&localMeta).Error; err != nil { + Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). + Where("client_inbounds.inbound_id = ?", c.Id). + Pluck("email", &oldEmailsRows).Error; err == nil { + oldEmails := make(map[string]struct{}, len(oldEmailsRows)) + for _, e := range oldEmailsRows { + if e != "" { + oldEmails[e] = struct{}{} + } + } + perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails}) + } + + clients, gcErr := s.GetClients(snapIb) + if gcErr != nil { + logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr) + syncFailedInbounds[c.Id] = struct{}{} continue } - for _, m := range localMeta { - commentByEmail[m.Email] = m.Comment + csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats)) + for _, cs := range snapIb.ClientStats { + csByEmail[cs.Email] = cs } - } - for i := range filtered { - if cmt, ok := commentByEmail[filtered[i].Email]; ok { - filtered[i].Comment = cmt + filtered := clients[:0] + for i := range clients { + if isClientEmailTombstoned(clients[i].Email) { + continue + } + existing := statByEmail[clients[i].Email] + var csPtr *xray.ClientTraffic + if cs, hit := csByEmail[clients[i].Email]; hit { + csCopy := cs + csPtr = &csCopy + } + applyMasterClientLifecycle(&clients[i], existing, csPtr) + filtered = append(filtered, clients[i]) } - } - p := pendingAdopts[c.Id] - _, isNew := newInboundIDs[c.Id] - adoptedSettings := p.wireSettings - liftChanged := false - if !isNew { - // Use the traffic deltas just applied to this transaction (#6228). - if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed { - adoptedSettings, liftChanged = lifted, true + // A degraded node (reset/restart/removal) reports zero clients for an inbound the + // hub populates; adopting it empties links and ReapSyncOrphans deletes shared clients (#6734). + if _, degraded := degradedInbounds[c.Id]; degraded { + logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub has %d attached — keeping them and re-pushing", nodeID, snapIb.Tag, len(oldEmailsRows)) + syncFailedInbounds[c.Id] = struct{}{} + continue } - } - updates := p.config - settingsChanged := c.Settings != adoptedSettings - if settingsChanged { - if updates == nil { - updates = make(map[string]any, 1) - } - updates["settings"] = adoptedSettings - } - rejected, err := withClientSyncSavepoint(tx, func() error { - if len(updates) > 0 { - if err := tx.Model(model.Inbound{}).Where("id = ?", c.Id).Updates(updates).Error; err != nil { - return err + localEmails := make([]string, 0, len(filtered)) + for i := range filtered { + if filtered[i].Email != "" { + localEmails = append(localEmails, filtered[i].Email) } } - return s.clientService.SyncInbound(tx, c.Id, filtered) - }) - if err != nil { - return false, err - } - if rejected != nil { - logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, rejected) - syncFailedInbounds[c.Id] = struct{}{} - // The row holds what the node reported: pushing it back gets refused there and keeps the node dirty. - if isNew { + commentByEmail := make(map[string]string, len(localEmails)) + for _, batch := range chunkStrings(localEmails, sqlInChunk) { + var localMeta []struct { + Email string + Comment string `gorm:"column:comment"` + } + if err := tx.Table("clients"). + Select("email, comment"). + Where("email IN ?", batch). + Find(&localMeta).Error; err != nil { + continue + } + for _, m := range localMeta { + commentByEmail[m.Email] = m.Comment + } + } + for i := range filtered { + if cmt, ok := commentByEmail[filtered[i].Email]; ok { + filtered[i].Comment = cmt + } + } + p, adopt := pendingAdopts[c.Id] + _, isNew := newInboundIDs[c.Id] + adoptedSettings := p.wireSettings + liftChanged := false + if adopt && !isNew { + // Use the traffic deltas just applied to this transaction (#6228). + if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed { + adoptedSettings, liftChanged = lifted, true + } + } + updates := p.config + settingsChanged := adopt && c.Settings != adoptedSettings + if settingsChanged { + if updates == nil { + updates = make(map[string]any, 1) + } + updates["settings"] = adoptedSettings + } + rejected, err := withClientSyncSavepoint(tx, func() error { + if len(updates) > 0 { + if err := tx.Model(model.Inbound{}).Where("id = ?", c.Id).Updates(updates).Error; err != nil { + return err + } + } + return s.clientService.SyncInbound(tx, c.Id, filtered) + }) + if err != nil { + return false, err + } + if rejected != nil { + logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, rejected) + syncFailedInbounds[c.Id] = struct{}{} + // The row holds what the node reported: pushing it back gets refused there and keeps the node dirty. + if isNew { + adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, p.wireSettings)) + } + continue + } + if len(updates) > 0 { + structuralChange = true + } + adoptedSettingsChanged = adoptedSettingsChanged || settingsChanged + lifecycleLifted = lifecycleLifted || liftChanged + // Stamp the un-lifted wire blob so reconciliation can push lifecycle lifts. + if adopt && !isNew && (liftChanged || c.Settings != p.wireSettings || adoptedWireConfigChanged(c, snapIb)) { adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, p.wireSettings)) } - continue } - if len(updates) > 0 { - structuralChange = true - } - adoptedSettingsChanged = adoptedSettingsChanged || settingsChanged - lifecycleLifted = lifecycleLifted || liftChanged - // Stamp the un-lifted wire blob so reconciliation can push lifecycle lifts. - if !isNew && (liftChanged || c.Settings != p.wireSettings || adoptedWireConfigChanged(c, snapIb)) { - adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, p.wireSettings)) - } - } - for _, old := range perInboundOld { - // The sweep's premise is that links were just rebuilt from the snapshot, - // which is exactly what a failed SyncInbound violates. - if _, failed := syncFailedInbounds[old.inboundID]; failed { - continue - } - var stillAttached []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", old.inboundID). - Pluck("email", &stillAttached).Error; err != nil { - continue - } - stillSet := make(map[string]struct{}, len(stillAttached)) - for _, e := range stillAttached { - stillSet[e] = struct{}{} - } - for email := range old.emails { - if _, kept := stillSet[email]; kept { + for _, old := range perInboundOld { + // The sweep's premise is that links were just rebuilt from the snapshot, + // which is exactly what a failed SyncInbound violates. + if _, failed := syncFailedInbounds[old.inboundID]; failed { continue } - var attachmentCount int64 - if err := tx.Table("client_inbounds"). - Joins("JOIN clients ON clients.id = client_inbounds.client_id"). - Where("clients.email = ?", email). - Count(&attachmentCount).Error; err != nil { + var stillAttached []string + if err := tx.Table("clients"). + Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). + Where("client_inbounds.inbound_id = ?", old.inboundID). + Pluck("email", &stillAttached).Error; err != nil { continue } - if attachmentCount > 0 { - continue + stillSet := make(map[string]struct{}, len(stillAttached)) + for _, e := range stillAttached { + stillSet[e] = struct{}{} } - // "Ended the merge unattached" is true for a real remote deletion and - // equally true for a bad merge, so record a strike instead of deleting. - if err := markSyncOrphan(tx, email, nodeID, now); err != nil { - logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err) - continue + for email := range old.emails { + if _, kept := stillSet[email]; kept { + continue + } + var attachmentCount int64 + if err := tx.Table("client_inbounds"). + Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Where("clients.email = ?", email). + Count(&attachmentCount).Error; err != nil { + continue + } + if attachmentCount > 0 { + continue + } + // "Ended the merge unattached" is true for a real remote deletion and + // equally true for a bad merge, so record a strike instead of deleting. + if err := markSyncOrphan(tx, email, nodeID, now); err != nil { + logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err) + continue + } + structuralChange = true } - structuralChange = true } } @@ -1533,6 +1609,48 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi InvalidateSubData() } + delete(s.snapshotMerges, nodeID) + // Filtered memberships omit refused usage-only clients, so these claims + // must be validated again on each tick even when the catalog is unchanged. + cacheableClaims := len(claims.refused) == 0 && len(claims.shared) == 0 && len(claims.storedSubID) == 0 + if cacheableClaims && masterRevision != "" && !dirty && !justPushed && !structuralChange && len(degradedInbounds) == 0 && len(adoptedInbounds) == 0 && len(syncFailedInbounds) == 0 { + after, _, err := masterSnapshotRevision(db, nodeID, snap, &nodeRow, selfKey) + if err == nil && after == masterRevision { + attached := make(map[int]map[string]struct{}, len(snap.Inbounds)) + if skipStructure { + attached = cached.attached + } + valid := true + if !skipStructure { + for _, ib := range snap.Inbounds { + if ib == nil { + continue + } + if tagToCentral[ib.Tag] == nil { + valid = false + break + } + members, known := snapshotAttachedEmails(ib.Settings) + if !known { + valid = false + break + } + attached[ib.Id] = members + } + } + if valid && !skipStructure { + valid = snapshotMembershipMatches(db, nodeID, snap, tagToCentral, attached) + } + ids, mapped := snapshotInboundMapping(snap, tagToCentral) + if valid && mapped { + if s.snapshotMerges == nil { + s.snapshotMerges = make(map[int]*nodeMergeCache) + } + s.snapshotMerges[nodeID] = &nodeMergeCache{db: db, revision: masterRevision, lifecycleRevision: lifecycleRevision, central: append([]model.Inbound(nil), central...), attached: attached, inboundIDs: ids} + } + } + } + if len(degradedInbounds) > 0 { if mgr := runtime.GetManager(); mgr != nil { if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil { @@ -1910,7 +2028,10 @@ func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) m } func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) { - db := database.GetDB() + return clientsLastOnline(database.GetDB()) +} + +func clientsLastOnline(db *gorm.DB) (map[string]int64, error) { var rows []xray.ClientTraffic err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { diff --git a/internal/web/service/node_snapshot.go b/internal/web/service/node_snapshot.go new file mode 100644 index 000000000..ebb361b67 --- /dev/null +++ b/internal/web/service/node_snapshot.go @@ -0,0 +1,127 @@ +package service + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +var nodeSnapshotBootID = uuid.NewString() + +type snapshotInboundVersion struct { + ID int + SnapshotRevision string + Up int64 + Down int64 +} + +type snapshotMembershipVersion struct { + model.ClientInbound + SnapshotRevision string +} + +func (s *InboundService) GetNodeTrafficSnapshot(ctx context.Context, userID int, knownRevision string) (*runtime.NodeTrafficSnapshotV1, error) { + return nodeTrafficSnapshot(database.GetDB().WithContext(ctx), userID, knownRevision, s.panelGuid()) +} + +func nodeTrafficSnapshot(db *gorm.DB, userID int, knownRevision, guid string) (*runtime.NodeTrafficSnapshotV1, error) { + result := &runtime.NodeTrafficSnapshotV1{Version: 1, Clients: make([]runtime.NodeClientTraffic, 0), InboundTraffic: make([]runtime.NodeInboundTraffic, 0)} + err := readNodeSnapshot(db, func(tx *gorm.DB) error { + var versions []snapshotInboundVersion + if err := tx.Table("inbounds").Select("id, snapshot_revision, up, down").Where("user_id = ?", userID).Order("id").Scan(&versions).Error; err != nil { + return err + } + var memberships []snapshotMembershipVersion + if err := tx.Table("client_inbounds ci").Select("ci.*, c.snapshot_revision").Joins("JOIN clients c ON c.id = ci.client_id").Joins("JOIN inbounds ib ON ib.id = ci.inbound_id").Where("ib.user_id = ?", userID).Order("ci.inbound_id, ci.client_id").Scan(&memberships).Error; err != nil { + return err + } + owned := tx.Table("inbounds").Select("id").Where("user_id = ?", userID) + attached := tx.Table("clients c").Select("c.email").Joins("JOIN client_inbounds ci ON ci.client_id = c.id").Joins("JOIN inbounds ib ON ib.id = ci.inbound_id").Where("ib.user_id = ? AND c.email <> ?", userID, "") + if err := tx.Model(&xray.ClientTraffic{}).Select("id, inbound_id, email, enable, up, down, total, expiry_time, reset, reset_day, reset_weekday, reset_max, reset_count, last_online").Where("inbound_id IN (?) OR email IN (?)", owned, attached).Order("id").Find(&result.Clients).Error; err != nil { + return err + } + hash := sha256.New() + encoder := json.NewEncoder(hash) + for _, value := range []any{nodeSnapshotBootID, database.ConnectionGeneration(), guid, userID, memberships} { + if err := encoder.Encode(value); err != nil { + return err + } + } + for _, v := range versions { + result.InboundTraffic = append(result.InboundTraffic, runtime.NodeInboundTraffic{ID: v.ID, Up: v.Up, Down: v.Down}) + v.Up = 0 + v.Down = 0 + if err := encoder.Encode(v); err != nil { + return err + } + } + // Lifecycle changes invalidate structural reconciliation; usage and online timestamps do not. + for _, cs := range result.Clients { + cs.Up = 0 + cs.Down = 0 + cs.LastOnline = 0 + if err := encoder.Encode(cs); err != nil { + return err + } + } + result.Revision = hex.EncodeToString(hash.Sum(nil)) + if result.Revision != knownRevision { + structure := &runtime.NodeSnapshotStructure{Inbounds: make([]*model.Inbound, 0), Attachments: make([]runtime.NodeSnapshotAttachment, 0)} + if err := tx.Model(&model.Inbound{}).Where("user_id = ?", userID).Order("id").Find(&structure.Inbounds).Error; err != nil { + return err + } + if err := tx.Table("client_inbounds ci").Select("ci.inbound_id, c.email").Joins("JOIN clients c ON c.id = ci.client_id").Joins("JOIN inbounds ib ON ib.id = ci.inbound_id").Where("ib.user_id = ?", userID).Order("ci.inbound_id, c.id").Scan(&structure.Attachments).Error; err != nil { + return err + } + for _, ib := range structure.Inbounds { + ib.Up = 0 + ib.Down = 0 + if ib.OriginNodeGuid == "" && ib.NodeID == nil { + ib.OriginNodeGuid = guid + } + } + result.Structure = structure + } + var err error + result.LastOnlineMap, err = clientsLastOnline(tx) + return err + }) + return result, err +} + +// SQLite's default write transaction is IMMEDIATE; snapshots need a deferred WAL reader. +func readNodeSnapshot(db *gorm.DB, read func(*gorm.DB) error) error { + if db.Name() != database.DialectSQLite { + return db.Transaction(read, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true}) + } + return db.Connection(func(conn *gorm.DB) error { + conn = conn.Session(&gorm.Session{NewDB: true}) + if err := conn.Exec("BEGIN DEFERRED").Error; err != nil { + return err + } + committed := false + defer func() { + if !committed { + _ = conn.WithContext(context.Background()).Exec("ROLLBACK").Error + } + }() + if err := read(conn); err != nil { + return err + } + if err := conn.Exec("COMMIT").Error; err != nil { + return err + } + committed = true + return nil + }) +} diff --git a/internal/web/service/node_snapshot_alias_test.go b/internal/web/service/node_snapshot_alias_test.go new file mode 100644 index 000000000..2eaf6e65d --- /dev/null +++ b/internal/web/service/node_snapshot_alias_test.go @@ -0,0 +1,224 @@ +package service + +import ( + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func cachedAliasFixture(t *testing.T) (*gorm.DB, *InboundService, *runtime.TrafficSnapshot, int) { + t.Helper() + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "alias.db")) + nodeID := 1 + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "alias", Guid: "node-guid", Address: "127.0.0.1", Port: 2096, ApiToken: "token", Enable: true}) + settings := `{"clients":[{"email":"alias-client","enable":true,"totalGB":1000,"expiryTime":0}]}` + central := model.Inbound{UserId: 1, NodeID: &nodeID, OriginNodeGuid: "node-guid", Tag: "desired-name", Enable: true, Port: 8443, Protocol: model.VLESS, Settings: settings} + if err := db.Create(¢ral).Error; err != nil { + t.Fatal(err) + } + if err := (&ClientService{}).SyncInbound(db, central.Id, []model.Client{{Email: "alias-client", Enable: true, TotalGB: 1000}}); err != nil { + t.Fatal(err) + } + if err := db.Create(&xray.ClientTraffic{InboundId: central.Id, Email: "alias-client", Enable: true, Total: 1000}).Error; err != nil { + t.Fatal(err) + } + svc := &InboundService{} + ib := central + ib.Id, ib.Tag, ib.NodeID = 77, "already-deployed", nil + ib.ClientStats = []xray.ClientTraffic{{Email: "alias-client", Enable: true, Total: 1000}} + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{&ib}, StructuralRevision: "alias-revision"} + for range 4 { + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + } + if svc.snapshotMerges[nodeID] == nil { + t.Fatal("converged alias never became cacheable") + } + return db, svc, snap, central.Id +} + +func TestNodeSnapshotCachedAliasPreservesTraffic(t *testing.T) { + db, svc, snap, centralID := cachedAliasFixture(t) + ib := snap.Inbounds[0] + nodeID := 1 + log := &snapshotReadLog{Interface: logger.Discard} + oldLog := db.Logger + db.Logger = log + t.Cleanup(func() { db.Logger = oldLog }) + for _, up := range []int64{100, 150, 150, 5, 15} { + ib.Up, ib.Down = up, up*2 + ib.ClientStats[0].Up, ib.ClientStats[0].Down = up, up*2 + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + var got model.Inbound + if err := db.Select("id", "tag", "up", "down").First(&got, centralID).Error; err != nil { + t.Fatal(err) + } + if got.Tag != "desired-name" || got.Up != up || got.Down != up*2 { + t.Fatalf("alias counters = %+v, want %d/%d on original central row", got, up, up*2) + } + } + assertUpDown(t, readTraffic(t, db, "alias-client"), 160, 320, "cached alias including counter reset") + for _, q := range log.statements { + lower := strings.ToLower(q) + if strings.Contains(lower, "select * from `inbounds`") || strings.Contains(lower, "select * from \"inbounds\"") || strings.Contains(lower, "select * from `clients`") || strings.Contains(lower, "select * from \"clients\"") { + t.Fatalf("unchanged alias rebuilt catalog: %s", q) + } + } +} + +func TestNodeSnapshotAliasInvalidCacheFallsBack(t *testing.T) { + for _, broken := range []string{"missing binding", "wrong target", "extra binding", "missing membership", "master metadata"} { + t.Run(broken, func(t *testing.T) { + db, svc, snap, centralID := cachedAliasFixture(t) + cache := svc.snapshotMerges[1] + switch broken { + case "missing binding": + delete(cache.inboundIDs, 77) + case "wrong target": + cache.inboundIDs[77] = centralID + 1000 + case "extra binding": + cache.inboundIDs[78] = centralID + case "missing membership": + delete(cache.attached, 77) + case "master metadata": + if err := db.Exec("UPDATE inbounds SET remark = 'master edit' WHERE id = ?", centralID).Error; err != nil { + t.Fatal(err) + } + } + log := &snapshotReadLog{Interface: logger.Discard} + previous := db.Logger + db.Logger = log + t.Cleanup(func() { db.Logger = previous }) + snap.Inbounds[0].Up, snap.Inbounds[0].ClientStats[0].Up = 90, 90 + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + assertUpDown(t, readTraffic(t, db, "alias-client"), 90, 0, "fallback preserved alias delta") + var ib model.Inbound + if err := db.Select("id", "up").First(&ib, centralID).Error; err != nil { + t.Fatal(err) + } + if ib.Up != 90 { + t.Fatalf("inbound up=%d, want 90", ib.Up) + } + rebuilt := false + for _, q := range log.statements { + if strings.Contains(q, "SELECT * FROM `inbounds`") || strings.Contains(q, "SELECT * FROM \"inbounds\"") { + rebuilt = true + } + } + if !rebuilt { + t.Fatal("invalid cache did not fall back to catalog reconciliation") + } + }) + } +} + +func TestNodeSnapshotAliasQuotaDisableAndRenewal(t *testing.T) { + db, svc, snap, centralID := cachedAliasFixture(t) + ib := snap.Inbounds[0] + oldExpiry := time.Now().Add(24 * time.Hour).UnixMilli() + // A lifecycle change forces a full merge, then the stable disabled state becomes cacheable. + if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", "alias-client").Update("expiry_time", oldExpiry).Error; err != nil { + t.Fatal(err) + } + ib.ClientStats[0].Up, ib.ClientStats[0].Enable, ib.ClientStats[0].ExpiryTime = 1200, false, oldExpiry + ib.Settings = fmt.Sprintf(`{"clients":[{"email":"alias-client","enable":false,"totalGB":1000,"expiryTime":%d}]}`, oldExpiry) + for range 4 { + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + } + if got := readTraffic(t, db, "alias-client"); got.Enable || got.Up != 1200 || got.Total != 1000 { + t.Fatalf("quota latch=%+v", got) + } + if svc.snapshotMerges[1] == nil { + t.Fatal("disabled alias did not converge to cache") + } + ib.ClientStats[0].Up = 1250 + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + if got := readTraffic(t, db, "alias-client"); got.Enable || got.Up != 1250 { + t.Fatalf("disabled cached usage=%+v", got) + } + newExpiry := oldExpiry + int64(24*time.Hour/time.Millisecond) + ib.ClientStats[0].Reset = 30 + ib.ClientStats[0].Up, ib.ClientStats[0].Enable, ib.ClientStats[0].ExpiryTime, ib.ClientStats[0].Total = 5, true, newExpiry, 2000 + ib.Settings = fmt.Sprintf(`{"clients":[{"email":"alias-client","enable":true,"totalGB":2000,"expiryTime":%d}]}`, newExpiry) + snap.StructuralRevision = "renewed-alias" + for range 4 { + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + } + if got := readTraffic(t, db, "alias-client"); !got.Enable || got.Up != 5 || got.Total != 2000 || got.ExpiryTime != newExpiry { + t.Fatalf("renewal=%+v", got) + } + if svc.snapshotMerges[1] == nil { + t.Fatal("renewed alias did not converge to cache") + } + ib.ClientStats[0].Up = 25 + ib.Up = 25 + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + if got := readTraffic(t, db, "alias-client"); !got.Enable || got.Up != 25 { + t.Fatalf("post-renewal cached usage=%+v", got) + } + var count int64 + db.Model(&model.Inbound{}).Where("id = ? AND tag = ?", centralID, "desired-name").Count(&count) + if count != 1 { + t.Fatalf("lost adopted central alias: %d", count) + } +} + +func TestNodeSnapshotAliasValidatesEntireMapping(t *testing.T) { + db, svc, snap, centralID := cachedAliasFixture(t) + nodeID := 1 + second := model.Inbound{UserId: 1, NodeID: &nodeID, OriginNodeGuid: "node-guid", Tag: "second-desired", Enable: true, Port: 9443, Protocol: model.VLESS, Settings: `{"clients":[]}`} + if err := db.Create(&second).Error; err != nil { + t.Fatal(err) + } + remote := second + remote.Id, remote.Tag, remote.NodeID = 88, "second-deployed", nil + snap.Inbounds = append(snap.Inbounds, &remote) + for range 4 { + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + } + if cache := svc.snapshotMerges[1]; cache == nil || len(cache.inboundIDs) != 2 { + t.Fatal("two aliases did not converge to cache") + } + svc.snapshotMerges[1].inboundIDs[88] = centralID + snap.Inbounds[0].Up, snap.Inbounds[0].ClientStats[0].Up, remote.Up = 25, 25, 75 + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + for _, want := range []struct { + id int + up int64 + }{{centralID, 25}, {second.Id, 75}} { + var got model.Inbound + if err := db.Select("id", "up").First(&got, want.id).Error; err != nil { + t.Fatal(err) + } + if got.Up != want.up { + t.Fatalf("partial cached merge on inbound %d: up=%d want %d", want.id, got.Up, want.up) + } + } + assertUpDown(t, readTraffic(t, db, "alias-client"), 25, 0, "full fallback preserved first alias") +} diff --git a/internal/web/service/node_snapshot_cycle_scale_test.go b/internal/web/service/node_snapshot_cycle_scale_test.go new file mode 100644 index 000000000..b6497857f --- /dev/null +++ b/internal/web/service/node_snapshot_cycle_scale_test.go @@ -0,0 +1,355 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "runtime/pprof" + "sort" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + noderuntime "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func snapshotSourceFixture(t *testing.T, n, inbounds int) (*gorm.DB, scaleDataset) { + t.Helper() + path := filepath.Join(t.TempDir(), "node.db") + t.Setenv("XUI_SCALE_DB_PATH", path) + setupScaleDB(t) + ds := seedScaleDataset(t, n, inbounds) + source := database.GetDB() + shareSnapshotScaleClients(t, source, ds, n, inbounds) + reader, err := gorm.Open(source.Dialector, &gorm.Config{Logger: logger.Discard, DisableForeignKeyConstraintWhenMigrating: true}) + if err != nil { + t.Fatal(err) + } + pool, err := reader.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pool.Close() }) + // The node has its own connection pool; replacing the global DB below opens the master. + if source.Name() == database.DialectPostgres { + schema := fmt.Sprintf("snapshot_master_%d", time.Now().UnixNano()) + if err := reader.Exec("CREATE SCHEMA " + schema).Error; err != nil { + t.Fatal(err) + } + t.Cleanup(func() { reader.Exec("DROP SCHEMA " + schema + " CASCADE") }) + t.Setenv("XUI_DB_DSN", os.Getenv("XUI_DB_DSN")+" search_path="+schema) + } + if err := database.InitDB(filepath.Join(t.TempDir(), "master.db")); err != nil { + t.Fatal(err) + } + if _, _, err := database.EnsureFirstUser(); err != nil { + t.Fatal(err) + } + return reader, ds +} + +func seedSnapshotMaster(t *testing.T, source *gorm.DB, nodeCount int) { + t.Helper() + db := database.GetDB() + var inbounds []model.Inbound + var records []model.ClientRecord + var links []model.ClientInbound + var stats []xray.ClientTraffic + for _, step := range []struct { + table string + dst any + }{{"inbounds", &inbounds}, {"clients", &records}, {"client_inbounds", &links}, {"client_traffics", &stats}} { + if err := source.Table(step.table).Find(step.dst).Error; err != nil { + t.Fatal(err) + } + } + sourceRecordIDs := make([]int, len(records)) + for i := range records { + sourceRecordIDs[i] = records[i].Id + records[i].Id = 0 + } + if err := db.CreateInBatches(&records, 500).Error; err != nil { + t.Fatal(err) + } + clientIDs := make(map[int]int, len(records)) + for i := range records { + clientIDs[sourceRecordIDs[i]] = records[i].Id + } + for node := 1; node <= nodeCount; node++ { + nid := node + seedNodeRow(t, db, &model.Node{Id: node, Name: fmt.Sprint("bench-", node), Address: "127.0.0.1", Port: 2096, ApiToken: "token", Enable: true, Guid: fmt.Sprint("bench-guid-", node)}) + mapping := map[int]int{} + for _, ib := range inbounds { + old := ib.Id + ib.Id = 0 + ib.NodeID = &nid + ib.OriginNodeGuid = fmt.Sprint("bench-guid-", node) + ib.Tag = fmt.Sprintf("n%d-%s", node, ib.Tag) + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + mapping[old] = ib.Id + } + localLinks := append([]model.ClientInbound(nil), links...) + for i := range localLinks { + localLinks[i].InboundId = mapping[localLinks[i].InboundId] + localLinks[i].ClientId = clientIDs[localLinks[i].ClientId] + } + if err := db.CreateInBatches(localLinks, 1000).Error; err != nil { + t.Fatal(err) + } + if node == 1 { + for i := range stats { + stats[i].Id = 0 + stats[i].InboundId = mapping[stats[i].InboundId] + stats[i].Up = 0 + stats[i].Down = 0 + } + if err := db.CreateInBatches(stats, 1000).Error; err != nil { + t.Fatal(err) + } + } + } +} + +// Opt-in scale run exercises HTTP, Remote decoding and the real serialized traffic writer. +func TestNodeSnapshotCycleScale(t *testing.T) { + for _, n := range scaleSizes(t, 1000, 10000, 20000) { + for _, inbounds := range []int{1, 8} { + for _, nodes := range []int{1, 2} { + t.Run(fmt.Sprintf("%d/%d/%d", n, inbounds, nodes), func(t *testing.T) { + source, _ := snapshotSourceFixture(t, n, inbounds) + db := database.GetDB() + for _, mode := range []string{"legacy", "compact"} { + if selected := os.Getenv("XUI_SNAPSHOT_MODE"); selected != "" && mode != selected { + continue + } + resetScaleTables(t, db, "inbounds", "clients", "client_inbounds", "client_traffics", "nodes", "node_client_traffics") + if err := source.Exec("UPDATE client_traffics SET up = 0, down = 0").Error; err != nil { + t.Fatal(err) + } + seedSnapshotMaster(t, source, nodes) + svc := &InboundService{} + nodeSQL := &snapshotQueryMeter{Interface: logger.Discard} + masterSQL := &snapshotQueryMeter{Interface: logger.Discard} + oldLogger := db.Logger + db.Logger = masterSQL + var bytes, full, encodeNanos atomic.Int64 + var servers []*httptest.Server + var remotes []*noderuntime.Remote + for node := 1; node <= nodes; node++ { + guid := fmt.Sprint("bench-guid-", node) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if mode == "compact" { + w.Header().Set("X-3x-Node-Caps", "traffic-snapshot-v1") + } + measured := source.Session(&gorm.Session{Logger: nodeSQL}) + var value any + var err error + switch req.URL.Path { + case "/panel/api/inbounds/list": + var rows []*model.Inbound + rows, err = svc.getInboundsFromDB(measured, 1) + for _, ib := range rows { + ib.OriginNodeGuid = guid + } + value = rows + full.Add(1) + case "/panel/api/inbounds/trafficSnapshot": + var snap *noderuntime.NodeTrafficSnapshotV1 + snap, err = nodeTrafficSnapshot(measured, 1, req.URL.Query().Get("revision"), guid) + value = snap + if err == nil && snap.Structure != nil { + full.Add(1) + } + case "/panel/api/clients/lastOnline": + value, err = clientsLastOnline(measured) + case "/panel/api/clients/onlines": + value = []string{} + default: + value = map[string][]string{} + } + if err != nil { + t.Errorf("snapshot HTTP: %v", err) + http.Error(w, "snapshot failed", http.StatusInternalServerError) + return + } + start := time.Now() + wire, err := json.Marshal(struct { + Success bool `json:"success"` + Obj any `json:"obj"` + }{true, value}) + encodeNanos.Add(time.Since(start).Nanoseconds()) + if err != nil { + t.Error(err) + return + } + bytes.Add(int64(len(wire))) + _, _ = w.Write(wire) + })) + servers = append(servers, server) + host, port, _ := net.SplitHostPort(server.Listener.Addr().String()) + number, _ := strconv.Atoi(port) + remotes = append(remotes, noderuntime.NewRemote(&model.Node{Id: node, Address: host, Port: number, AllowPrivateAddress: true, Scheme: "http", BasePath: "/", ApiToken: "token"}, nil)) + } + cycle := func() { + snapshots := make([]*noderuntime.TrafficSnapshot, nodes) + errors := make([]error, nodes) + var wg sync.WaitGroup + for i, remote := range remotes { + wg.Go(func() { snapshots[i], errors[i] = remote.FetchTrafficSnapshot(context.Background()) }) + } + wg.Wait() + for i, snap := range snapshots { + if errors[i] != nil { + t.Fatal(errors[i]) + } + if _, err := svc.SetRemoteTraffic(i+1, snap, false, false); err != nil { + t.Fatal(err) + } + } + } + for range 5 { + cycle() + } + measurePG := source.Name() == database.DialectPostgres && os.Getenv("XUI_SNAPSHOT_PG_STATS") == "1" + for _, scenario := range []string{"idle", "counters"} { + if measurePG { + if err := source.Exec("SELECT public.pg_stat_statements_reset()").Error; err != nil { + t.Fatal(err) + } + } + beforeStructural := masterSQL.fullSettingsReads + beforeMasterRead, beforeMasterWritten := masterSQL.readRows, masterSQL.writtenRows + beforeNodeCount, beforeNodeRows, beforeNodeTime := nodeSQL.count, nodeSQL.rows, nodeSQL.elapsed + beforeMasterCount, beforeMasterRows, beforeMasterTime := masterSQL.count, masterSQL.rows, masterSQL.elapsed + beforeBytes, beforeFull, beforeEncode := bytes.Load(), full.Load(), encodeNanos.Load() + var profile *os.File + if dir := os.Getenv("XUI_SNAPSHOT_PROFILE_DIR"); dir != "" { + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + var err error + profile, err = os.Create(filepath.Join(dir, fmt.Sprintf("%s-%s-%d-%d-%d.cpu", mode, scenario, n, inbounds, nodes))) + if err != nil { + t.Fatal(err) + } + if err := pprof.StartCPUProfile(profile); err != nil { + t.Fatal(err) + } + } + var times []float64 + var allocated, allocs uint64 + for range 12 { + if scenario == "counters" { + if err := source.Exec("/*snapshot-fixture*/ UPDATE client_traffics SET up = up + 100, down = down + 200 WHERE id IN (SELECT id FROM client_traffics ORDER BY id LIMIT 100)").Error; err != nil { + t.Fatal(err) + } + } + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + start := time.Now() + cycle() + times = append(times, float64(time.Since(start).Microseconds())/1000) + runtime.ReadMemStats(&after) + allocated += after.TotalAlloc - before.TotalAlloc + allocs += after.Mallocs - before.Mallocs + } + if profile != nil { + pprof.StopCPUProfile() + _ = profile.Close() + } + sort.Float64s(times) + serverMS := 0.0 + serverMetric := "n/a" + if measurePG { + if err := source.Raw("SELECT COALESCE(SUM(total_exec_time),0) FROM public.pg_stat_statements WHERE dbid=(SELECT oid FROM pg_database WHERE datname=current_database()) AND query NOT LIKE '%pg_stat_statements%' AND query NOT LIKE '%snapshot-fixture%'").Scan(&serverMS).Error; err != nil { + t.Fatal(err) + } + serverMS /= 12 + serverMetric = fmt.Sprintf("%.2f", serverMS) + } + t.Logf("CYCLE scenario=%s mode=%s n=%d inbounds=%d nodes=%d samples=12 node_sql=%.1f node_rows=%.0f node_query_scan_ms=%.2f master_sql=%.1f master_rows=%.0f master_rows_read=%.0f master_rows_affected=%.0f master_query_scan_ms=%.2f bytes=%d encode_ms=%.2f allocs=%d allocated=%d full_fetches=%d structural_polls=%d pg_exec_ms=%s p50_ms=%.2f p95_ms=%.2f", scenario, mode, n, inbounds, nodes, float64(nodeSQL.count-beforeNodeCount)/12, float64(nodeSQL.rows-beforeNodeRows)/12, float64((nodeSQL.elapsed-beforeNodeTime).Microseconds())/12000, float64(masterSQL.count-beforeMasterCount)/12, float64(masterSQL.rows-beforeMasterRows)/12, float64(masterSQL.readRows-beforeMasterRead)/12, float64(masterSQL.writtenRows-beforeMasterWritten)/12, float64((masterSQL.elapsed-beforeMasterTime).Microseconds())/12000, (bytes.Load()-beforeBytes)/12, float64(encodeNanos.Load()-beforeEncode)/12000000, allocs/12, allocated/12, full.Load()-beforeFull, masterSQL.fullSettingsReads-beforeStructural, serverMetric, times[5], times[11]) + } + + var eventInbound model.Inbound + if err := source.Order("id").First(&eventInbound).Error; err != nil { + t.Fatal(err) + } + var config struct { + Clients []model.Client `json:"clients"` + } + if err := json.Unmarshal([]byte(eventInbound.Settings), &config); err != nil { + t.Fatal(err) + } + added := model.Client{Email: "snapshot-event-added", ID: "00000000-0000-4000-8000-000000000777", Enable: true} + for _, event := range []string{"add", "remove", "config"} { + if err := source.Transaction(func(tx *gorm.DB) error { + switch event { + case "add": + record := added.ToRecord() + if err := tx.Create(record).Error; err != nil { + return err + } + if err := tx.Create(&model.ClientInbound{ClientId: record.Id, InboundId: eventInbound.Id}).Error; err != nil { + return err + } + if err := tx.Create(&xray.ClientTraffic{Email: added.Email, InboundId: eventInbound.Id, Enable: true}).Error; err != nil { + return err + } + return tx.Model(&model.Inbound{}).Where("id = ?", eventInbound.Id).Update("settings", clientsSettings(t, append(append([]model.Client(nil), config.Clients...), added))).Error + case "remove": + if err := tx.Where("client_id IN (?)", tx.Model(&model.ClientRecord{}).Select("id").Where("email = ?", added.Email)).Delete(&model.ClientInbound{}).Error; err != nil { + return err + } + if err := tx.Where("email = ?", added.Email).Delete(&model.ClientRecord{}).Error; err != nil { + return err + } + if err := tx.Where("email = ?", added.Email).Delete(&xray.ClientTraffic{}).Error; err != nil { + return err + } + return tx.Model(&model.Inbound{}).Where("id = ?", eventInbound.Id).Update("settings", eventInbound.Settings).Error + default: + return tx.Model(&model.Inbound{}).Where("id = ?", eventInbound.Id).Update("remark", eventInbound.Remark+" changed").Error + } + }); err != nil { + t.Fatal(err) + } + previousFull, previousBytes := full.Load(), bytes.Load() + previousSQL := nodeSQL.count + masterSQL.count + start := time.Now() + cycle() + if full.Load()-previousFull != int64(nodes) { + t.Fatalf("%s did not refresh every affected peer: full=%d", event, full.Load()-previousFull) + } + t.Logf("EVENT mode=%s n=%d inbounds=%d nodes=%d change=%s latency_ms=%.2f bytes=%d sql=%d full_fetches=%d", mode, n, inbounds, nodes, event, float64(time.Since(start).Microseconds())/1000, bytes.Load()-previousBytes, nodeSQL.count+masterSQL.count-previousSQL, full.Load()-previousFull) + } + if err := source.Model(&model.Inbound{}).Where("id = ?", eventInbound.Id).Update("remark", eventInbound.Remark).Error; err != nil { + t.Fatal(err) + } + + for _, server := range servers { + server.Close() + } + db.Logger = oldLogger + } + }) + } + } + } +} diff --git a/internal/web/service/node_snapshot_merge.go b/internal/web/service/node_snapshot_merge.go new file mode 100644 index 000000000..01e102aff --- /dev/null +++ b/internal/web/service/node_snapshot_merge.go @@ -0,0 +1,179 @@ +package service + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "slices" + "strings" + "sync" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +var nodeSnapshotMergeMu sync.Mutex + +type nodeMergeCache struct { + db *gorm.DB + revision string + lifecycleRevision string + central []model.Inbound + attached map[int]map[string]struct{} + inboundIDs map[int]int +} + +func snapshotInboundMapping(snap *runtime.TrafficSnapshot, central map[string]*model.Inbound) (map[int]int, bool) { + ids := make(map[int]int, len(snap.Inbounds)) + seen := make(map[int]bool, len(snap.Inbounds)) + for _, ib := range snap.Inbounds { + if ib == nil || ib.Id <= 0 || ids[ib.Id] != 0 { + return nil, false + } + c := central[ib.Tag] + if c == nil || seen[c.Id] { + return nil, false + } + ids[ib.Id], seen[c.Id] = c.Id, true + } + return ids, true +} + +// Resolve the whole association before using any cached counters; tags may be deployed aliases. +func (c *nodeMergeCache) restoreInboundAliases(nodeID int, snap *runtime.TrafficSnapshot, central []model.Inbound) (map[string]*model.Inbound, bool) { + if len(c.inboundIDs) != len(snap.Inbounds) || len(c.attached) != len(snap.Inbounds) { + return nil, false + } + byID := make(map[int]*model.Inbound, len(central)) + for i := range central { + byID[central[i].Id] = ¢ral[i] + } + aliases := make(map[string]*model.Inbound, len(snap.Inbounds)) + seenIDs, seenCentral := map[int]bool{}, map[int]bool{} + for _, ib := range snap.Inbounds { + if ib == nil || ib.Id <= 0 || seenIDs[ib.Id] { + return nil, false + } + stored := byID[c.inboundIDs[ib.Id]] + if stored == nil || stored.NodeID == nil || *stored.NodeID != nodeID || seenCentral[stored.Id] { + return nil, false + } + if _, known := c.attached[ib.Id]; !known { + return nil, false + } + if _, duplicate := aliases[ib.Tag]; duplicate { + return nil, false + } + if stored.Port != ib.Port || stored.Protocol != ib.Protocol || strings.TrimSpace(stored.Listen) != strings.TrimSpace(ib.Listen) { + return nil, false + } + aliases[ib.Tag], seenIDs[ib.Id], seenCentral[stored.Id] = stored, true, true + } + return aliases, true +} + +// Database revisions validate both sides before a structural cache can be reused. +func masterSnapshotRevision(db *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot, node *model.Node, selfKey string) (string, []snapshotInboundVersion, error) { + if snap.StructuralRevision == "" { + return "", nil, nil + } + var versions []snapshotInboundVersion + if err := db.Table("inbounds").Select("id, snapshot_revision, up, down").Where("node_id = ?", nodeID).Order("id").Scan(&versions).Error; err != nil { + return "", nil, err + } + var links []snapshotMembershipVersion + if err := db.Table("client_inbounds ci").Select("ci.*, c.snapshot_revision").Joins("JOIN clients c ON c.id = ci.client_id").Joins("JOIN inbounds ib ON ib.id = ci.inbound_id").Where("ib.node_id = ?", nodeID).Order("ci.inbound_id, ci.client_id").Scan(&links).Error; err != nil { + return "", nil, err + } + hash := sha256.New() + enc := json.NewEncoder(hash) + ids := make([]int, 0, len(snap.Inbounds)) + for _, ib := range snap.Inbounds { + if ib != nil { + ids = append(ids, ib.Id) + } + } + structural := append([]snapshotInboundVersion(nil), versions...) + for i := range structural { + structural[i].Up = 0 + structural[i].Down = 0 + } + aliases := append([]string(nil), snap.ManagedAliases...) + slices.Sort(aliases) + for _, v := range []any{snap.StructuralRevision, node.Guid, node.InboundSyncMode, node.InboundTags, selfKey, ids, aliases, structural, links} { + if err := enc.Encode(v); err != nil { + return "", nil, err + } + } + return hex.EncodeToString(hash.Sum(nil)), versions, nil +} + +func snapshotLifecycleRevision(rows []xray.ClientTraffic) string { + hash := sha256.New() + enc := json.NewEncoder(hash) + for _, cs := range rows { + cs.Up = 0 + cs.Down = 0 + cs.LastOnline = 0 + cs.LastSubFetch = 0 + _ = enc.Encode(cs) + } + return hex.EncodeToString(hash.Sum(nil)) +} + +func snapshotMembershipMatches(db *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot, central map[string]*model.Inbound, attached map[int]map[string]struct{}) bool { + var rows []struct { + InboundID int + Email string + } + if err := db.Table("client_inbounds ci").Select("ci.inbound_id, c.email").Joins("JOIN clients c ON c.id = ci.client_id").Joins("JOIN inbounds ib ON ib.id = ci.inbound_id").Where("ib.node_id = ?", nodeID).Scan(&rows).Error; err != nil { + return false + } + byInbound := make(map[int]map[string]struct{}) + for _, row := range rows { + if byInbound[row.InboundID] == nil { + byInbound[row.InboundID] = make(map[string]struct{}) + } + byInbound[row.InboundID][strings.ToLower(row.Email)] = struct{}{} + } + for _, ib := range snap.Inbounds { + if ib == nil { + continue + } + c := central[ib.Tag] + if c == nil { + return false + } + want := attached[ib.Id] + got := byInbound[c.Id] + if len(want) != len(got) { + return false + } + for email := range want { + if _, ok := got[email]; !ok { + return false + } + } + } + return true +} + +func (s *InboundService) RetainNodeSnapshotCaches(nodes []*model.Node) error { + active := make(map[int]bool, len(nodes)) + for _, node := range nodes { + active[node.Id] = node.Enable && node.Status == "online" + } + return submitTrafficWrite(func() error { + nodeSnapshotMergeMu.Lock() + defer nodeSnapshotMergeMu.Unlock() + for id := range s.snapshotMerges { + if !active[id] { + delete(s.snapshotMerges, id) + } + } + return nil + }) +} diff --git a/internal/web/service/node_snapshot_scale_test.go b/internal/web/service/node_snapshot_scale_test.go new file mode 100644 index 000000000..9f690a0c1 --- /dev/null +++ b/internal/web/service/node_snapshot_scale_test.go @@ -0,0 +1,149 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "os" + "runtime" + "sort" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + noderuntime "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type snapshotQueryMeter struct { + logger.Interface + mu sync.Mutex + count, rows int64 + readRows, writtenRows int64 + fullSettingsReads int64 + elapsed time.Duration +} + +func (m *snapshotQueryMeter) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { + m.mu.Lock() + defer m.mu.Unlock() + q, rows := fc() + if q == "BEGIN DEFERRED" || q == "COMMIT" || q == "ROLLBACK" { + return + } + if strings.Contains(q, "SELECT * FROM `inbounds`") || strings.Contains(q, "SELECT * FROM \"inbounds\"") { + m.fullSettingsReads++ + } + m.count++ + m.rows += max(rows, 0) + if strings.HasPrefix(strings.ToUpper(strings.TrimSpace(q)), "SELECT") { + m.readRows += max(rows, 0) + } else { + m.writtenRows += max(rows, 0) + } + m.elapsed += time.Since(begin) +} + +// TestNodeSnapshotScale compares identical local-counter fixtures; opt in with XUI_SCALE_TEST=1. +func TestNodeSnapshotScale(t *testing.T) { + setupScaleDB(t) + for _, n := range scaleSizes(t, 1000, 10000, 20000) { + for _, inboundCount := range []int{1, 8} { + t.Run(fmt.Sprintf("%d/%d", n, inboundCount), func(t *testing.T) { + ds := seedScaleDataset(t, n, inboundCount) + db := database.GetDB() + shareSnapshotScaleClients(t, db, ds, n, inboundCount) + svc := &InboundService{} + for _, mode := range []string{"legacy", "compact"} { + if os.Getenv("XUI_SNAPSHOT_BASELINE") == "1" && mode != "legacy" { + continue + } + meter := &snapshotQueryMeter{Interface: logger.Discard} + measured := db.Session(&gorm.Session{Logger: meter}) + revision := "" + load := func() any { + if mode == "legacy" { + rows, err := svc.getInboundsFromDB(measured, 1) + if err != nil { + t.Fatal(err) + } + return rows + } + snap, err := nodeTrafficSnapshot(measured, 1, revision, "scale-node") + if err != nil { + t.Fatal(err) + } + revision = snap.Revision + return snap + } + _ = load() + var times []float64 + var bytes, allocs, allocated uint64 + var encode, decode time.Duration + *meter = snapshotQueryMeter{Interface: logger.Discard} + for range 12 { + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + start := time.Now() + value := load() + at := time.Now() + wire, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + encode += time.Since(at) + at = time.Now() + if mode == "legacy" { + var dst []*model.Inbound + if err := json.Unmarshal(wire, &dst); err != nil { + t.Fatal(err) + } + } else { + var dst noderuntime.NodeTrafficSnapshotV1 + if err := json.Unmarshal(wire, &dst); err != nil { + t.Fatal(err) + } + } + decode += time.Since(at) + times = append(times, float64(time.Since(start).Microseconds())/1000) + runtime.ReadMemStats(&after) + bytes += uint64(len(wire)) + allocs += after.Mallocs - before.Mallocs + allocated += after.TotalAlloc - before.TotalAlloc + } + sort.Float64s(times) + t.Logf("SNAPSHOT mode=%s n=%d inbounds=%d samples=12 sql=%.1f rows=%.0f query_scan_ms=%.2f bytes=%d encode_ms=%.2f decode_ms=%.2f allocs=%d allocated=%d p50_ms=%.2f p95_ms=%.2f", mode, n, inboundCount, float64(meter.count)/12, float64(meter.rows)/12, float64(meter.elapsed.Microseconds())/12000, bytes/12, float64(encode.Microseconds())/12000, float64(decode.Microseconds())/12000, allocs/12, allocated/12, times[5], times[11]) + } + }) + } + } +} + +func shareSnapshotScaleClients(t testing.TB, db *gorm.DB, ds scaleDataset, n, inbounds int) { + t.Helper() + if inbounds <= 1 { + return + } + var links []model.ClientInbound + if err := db.Find(&links).Error; err != nil { + t.Fatal(err) + } + for i := range links { + links[i].InboundId = ds.inboundIds[(i/(n/inbounds)+1)%inbounds] + } + if err := db.CreateInBatches(links, 1000).Error; err != nil { + t.Fatal(err) + } + for i, id := range ds.inboundIds { + clients := append(append([]model.Client(nil), ds.perInbound[i]...), ds.perInbound[(i+inbounds-1)%inbounds]...) + if err := db.Model(&model.Inbound{}).Where("id = ?", id).Update("settings", clientsSettings(t, clients)).Error; err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/web/service/node_snapshot_test.go b/internal/web/service/node_snapshot_test.go new file mode 100644 index 000000000..ca031523f --- /dev/null +++ b/internal/web/service/node_snapshot_test.go @@ -0,0 +1,306 @@ +package service + +import ( + "context" + "errors" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type snapshotReadLog struct { + logger.Interface + statements []string +} + +func (l *snapshotReadLog) Trace(_ context.Context, _ time.Time, fc func() (string, int64), _ error) { + q, _ := fc() + l.statements = append(l.statements, q) +} + +func TestNodeSnapshotUnchangedAvoidsSettingsAndDetectsDirectEdits(t *testing.T) { + initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "snapshot.db")) + db := database.GetDB() + ib := model.Inbound{UserId: 1, Tag: "snapshot", Protocol: model.VLESS, Port: 443, Settings: `{"clients":[{"id":"uuid","email":"client","enable":true}]}`} + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + client := model.ClientRecord{Email: "client", UUID: "uuid", Enable: true} + if err := db.Create(&client).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&xray.ClientTraffic{Email: "client", InboundId: ib.Id, Enable: true, Up: 10}).Error; err != nil { + t.Fatal(err) + } + first, err := nodeTrafficSnapshot(db, 1, "", "node") + if err != nil { + t.Fatal(err) + } + log := &snapshotReadLog{Interface: logger.Discard} + measured := db.Session(&gorm.Session{Logger: log}) + if err := db.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("up", 20).Error; err != nil { + t.Fatal(err) + } + second, err := nodeTrafficSnapshot(measured, 1, first.Revision, "node") + if err != nil { + t.Fatal(err) + } + if second.Structure != nil || second.Revision != first.Revision || second.InboundTraffic[0].Up != 20 { + t.Fatalf("unchanged structure/counters: %+v", second) + } + for _, q := range log.statements { + lower := strings.ToLower(q) + if strings.Contains(lower, "select * from `inbounds`") || strings.Contains(lower, "select * from \"inbounds\"") || strings.Contains(lower, "settings") { + t.Fatalf("unchanged poll loaded configuration: %s", q) + } + } + for _, change := range []struct { + name, sql string + args []any + }{ + {"direct settings", "UPDATE inbounds SET settings = ? WHERE id = ?", []any{`{"clients":[{"id":"uuid2","email":"client","enable":true}]}`, ib.Id}}, + {"canonical identity", "UPDATE clients SET uuid = ? WHERE id = ?", []any{"uuid3", client.Id}}, + {"lifecycle", "UPDATE client_traffics SET enable = ? WHERE email = ?", []any{false, "client"}}, + {"detach", "DELETE FROM client_inbounds WHERE client_id = ?", []any{client.Id}}, + } { + t.Run(change.name, func(t *testing.T) { + if err := db.Exec(change.sql, change.args...).Error; err != nil { + t.Fatal(err) + } + changed, err := nodeTrafficSnapshot(db, 1, second.Revision, "node") + if err != nil { + t.Fatal(err) + } + if changed.Structure == nil || changed.Revision == second.Revision { + t.Fatalf("missed %s", change.name) + } + second = changed + }) + } +} + +func TestNodeSnapshotMergeSkipsUnchangedStructureAndPreservesDeltas(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "merge.db")) + seedNodeRow(t, db, &model.Node{Id: 1, Name: "snapshot", Address: "127.0.0.1", Port: 2096, ApiToken: "token", Enable: true}) + svc := &InboundService{} + snap := snapshotWithClients(t, "snapshot", `{"clients":[{"email":"client","enable":true}]}`, xray.ClientTraffic{Email: "client", Enable: true, Up: 100}) + snap.Inbounds[0].Id = 1 + snap.Inbounds[0].Protocol = model.VLESS + snap.Inbounds[0].Port = 443 + snap.Inbounds[0].Enable = true + snap.StructuralRevision = "remote-1" + snap.ManagedAliases = []string{"second", "first"} + for range 4 { + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatal(err) + } + } + log := &snapshotReadLog{Interface: logger.Discard} + old := db.Logger + db.Logger = log + t.Cleanup(func() { db.Logger = old }) + for _, up := range []int64{120, 120, 5, 15} { + snap.Inbounds[0].ClientStats[0].Up = up + if up%2 == 0 { + snap.ManagedAliases = []string{"first", "second"} + } else { + snap.ManagedAliases = []string{"second", "first"} + } + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatal(err) + } + } + for _, q := range log.statements { + lower := strings.ToLower(q) + if strings.Contains(lower, "select * from `inbounds`") || strings.Contains(lower, "select * from \"inbounds\"") || strings.Contains(lower, "select * from `clients`") || strings.Contains(lower, "select * from \"clients\"") { + t.Fatalf("unchanged merge rebuilt configuration: %s", q) + } + } + assertUpDown(t, readTraffic(t, db, "client"), 130, 0, "duplicate and lower reset") + // A local metadata edit must force reconciliation even when the remote revision is unchanged. + if err := db.Exec("UPDATE clients SET comment = ? WHERE email = ?", "master edit", "client").Error; err != nil { + t.Fatal(err) + } + log.statements = nil + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatal(err) + } + rebuilt := false + for _, q := range log.statements { + if strings.Contains(q, "SELECT * FROM `inbounds`") || strings.Contains(q, "SELECT * FROM \"inbounds\"") { + rebuilt = true + } + } + if !rebuilt { + t.Fatal("local edit did not invalidate merge cache") + } + var record model.ClientRecord + if err := db.Where("email = ?", "client").First(&record).Error; err != nil { + t.Fatal(err) + } + if record.Comment != "master edit" { + t.Fatalf("lost master comment: %q", record.Comment) + } + if err := svc.RetainNodeSnapshotCaches(nil); err != nil { + t.Fatal(err) + } + log.statements = nil + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + refreshed := false + for _, q := range log.statements { + if strings.Contains(q, "SELECT * FROM `inbounds`") || strings.Contains(q, "SELECT * FROM \"inbounds\"") { + refreshed = true + } + } + if !refreshed { + t.Fatal("removed/offline node retained structural cache") + } +} + +func TestNodeSnapshotReadDoesNotHoldTrafficWriter(t *testing.T) { + initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "wal.db")) + db := database.GetDB() + ib := model.Inbound{Tag: "wal", UserId: 1, Settings: `{"clients":[]}`} + if err := db.Create(&ib).Error; err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- readNodeSnapshot(db, func(tx *gorm.DB) error { + var row model.Inbound + if err := tx.First(&row, ib.Id).Error; err != nil { + return err + } + close(entered) + <-release + return nil + }) + }() + <-entered + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + err := db.WithContext(ctx).Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("up", 42).Error + close(release) + if err != nil { + t.Fatalf("snapshot blocked traffic writer: %v", err) + } + if err := <-done; err != nil { + t.Fatal(err) + } + var row model.Inbound + if err := db.First(&row, ib.Id).Error; err != nil { + t.Fatal(err) + } + if row.Up != 42 { + t.Fatalf("lost concurrent traffic: %d", row.Up) + } +} + +func TestNodeSnapshotCanceledReadReleasesConnection(t *testing.T) { + initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "cancel.db")) + db := database.GetDB() + pool, err := db.DB() + if err != nil { + t.Fatal(err) + } + pool.SetMaxOpenConns(1) + ctx, cancel := context.WithCancel(context.Background()) + err = readNodeSnapshot(db.WithContext(ctx), func(tx *gorm.DB) error { + var count int64 + if err := tx.Model(&model.Inbound{}).Count(&count).Error; err != nil { + return err + } + cancel() + return ctx.Err() + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled read returned %v", err) + } + snapshot, err := nodeTrafficSnapshot(db, 1, "", "node") + if err != nil || snapshot.Structure == nil || len(snapshot.InboundTraffic) != 0 { + t.Fatalf("cancellation leaked transaction: %+v %v", snapshot, err) + } +} + +func TestNodeSnapshotReopenInvalidatesCatalog(t *testing.T) { + file := filepath.Join(t.TempDir(), "reopen.db") + initNodeSnapshotDB(t, file) + if err := database.GetDB().Create(&model.Inbound{Tag: "reopen", UserId: 1, Settings: `{"clients":[]}`}).Error; err != nil { + t.Fatal(err) + } + before, err := nodeTrafficSnapshot(database.GetDB(), 1, "", "node") + if err != nil { + t.Fatal(err) + } + if err := database.InitDB(file); err != nil { + t.Fatal(err) + } + after, err := nodeTrafficSnapshot(database.GetDB(), 1, before.Revision, "node") + if err != nil { + t.Fatal(err) + } + if after.Structure == nil || after.Revision == before.Revision { + t.Fatal("database reopen reused catalog history") + } + if len(after.Structure.Inbounds) != 1 || after.Structure.Inbounds[0].Tag != "reopen" { + t.Fatalf("reopen lost structure: %+v", after) + } +} + +func initNodeSnapshotDB(t *testing.T, path string) *gorm.DB { + t.Helper() + cleanup, err := testpg.IsolatePackage("node_snapshot") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + dbtest.InitDB(t, path) + return database.GetDB() +} + +func TestNodeSnapshotRefusedClaimsKeepUsageAcrossUnchangedTicks(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "claims.db")) + svc := &InboundService{} + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true}) + master := seedMasterInbound(t, db, "master-in", 40001, `{"email":"victim@x","id":"11111111-1111-4111-8111-111111111111","subId":"victim-sub","enable":true}`) + if err := db.Create(&xray.ClientTraffic{InboundId: master.Id, Email: "victim@x", Enable: true}).Error; err != nil { + t.Fatal(err) + } + createNodeInbound(t, db, 1, "n1-in", 41001) + for _, up := range []int64{100, 200, 300, 400, 500} { + snap := snapshotWithClients(t, "n1-in", `{"clients":[{"email":"victim@x","subId":"picked-by-node","enable":true},{"email":"own@x","enable":true}]}`, xray.ClientTraffic{Email: "victim@x", Up: up, Enable: false, ExpiryTime: 1}, xray.ClientTraffic{Email: "own@x", Enable: true}) + snap.StructuralRevision = "unchanged-hostile-catalog" + snap.Inbounds[0].Id = 1 + if _, err := svc.SetRemoteTraffic(1, snap, false, false); err != nil { + t.Fatal(err) + } + } + if got := readTraffic(t, db, "victim@x"); got.Up != 400 || !got.Enable || got.ExpiryTime != 0 { + t.Fatalf("victim traffic = %+v, want 400 bytes with master lifecycle", got) + } + if stored := storedInboundSettings(t, db, "n1-in"); strings.Contains(stored, "victim@x") { + t.Fatalf("stored refused claim: %s", stored) + } + if row := readClientRecord(t, db, "victim@x"); row.SubID != "victim-sub" { + t.Fatalf("victim subscription = %q", row.SubID) + } + if !nodeHostsClient(t, db, "n1-in", "own@x") { + t.Fatal("lost node's own client") + } +} diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 7ebfaf9db..f40382268 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -95,6 +95,10 @@ func run(root, outDir string) error { ), AliasAllow: setOf("GeoKind"), }, + { + Path: resolveRel(root, "internal/web/runtime"), + StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1"), + }, { Path: resolveRel(root, "internal/web/service"), StructAllow: setOf(