From 0afa11ddffa7958585d320179415d1d5fe410a5c Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 03:26:44 +0330 Subject: [PATCH] fix(nodes): share lightweight remote inbound catalog refreshes (#7313) Replace full inbound/client-list downloads on cold remote ID lookups with an owner-scoped six-field catalog projected directly from the database. Coalesce concurrent catalog refreshes per remote while preserving independent caller cancellation and rejecting stale ID mappings after topology mutations. Seed reconciliation from the catalog, create missing inbounds directly, preserve prefixed/adopted aliases and invalidate pushed state when remote IDs change. Avoid invalidating catalog generations on unchanged-ID settings pushes. Retain client-membership-aware reconciliation state and legacy full-list fallback only on HTTP 404/405. Cover permissions, query projection, concurrent refresh/cancellation, deletion/recreation, reconciliation request counts and mixed-version node compatibility. Integrated CI and Docs CI passed, including race, node E2E and PostgreSQL catalog projection. Synthetic response-size comparison is not a production latency benchmark. Fixes #7303. --- .github/workflows/ci.yml | 3 + .../docs/en/reference/api/inbounds.mdx | 17 +- docs/public/openapi.json | 86 +++++ frontend/public/openapi.json | 86 +++++ frontend/src/generated/examples.ts | 8 + frontend/src/generated/schemas.ts | 37 ++ frontend/src/generated/types.ts | 9 + frontend/src/generated/zod.ts | 10 + frontend/src/pages/api-docs/endpoints.ts | 10 + internal/nodee2e/node_snapshot_test.go | 21 +- internal/web/controller/api.go | 1 + internal/web/controller/inbound.go | 10 + internal/web/job/ldap_sync_hung_node_test.go | 2 +- .../web/job/node_traffic_isolation_test.go | 7 +- .../job/periodic_traffic_reset_nodes_test.go | 2 +- internal/web/node_contract_test.go | 76 ++++ internal/web/runtime/reconcile_skip_test.go | 8 + internal/web/runtime/remote.go | 140 +++----- .../web/runtime/remote_inbound_catalog.go | 153 ++++++++ .../runtime/remote_inbound_catalog_test.go | 334 ++++++++++++++++++ .../web/runtime/remote_inbound_lookup_test.go | 6 +- internal/web/runtime/remote_reset_test.go | 7 +- .../service/client_create_reconcile_test.go | 2 +- internal/web/service/inbound.go | 11 + .../service/inbound_node_reconcile_test.go | 42 ++- internal/web/service/node_http_fake_test.go | 4 +- tools/openapigen/main.go | 2 +- 27 files changed, 990 insertions(+), 104 deletions(-) create mode 100644 internal/web/runtime/remote_inbound_catalog.go create mode 100644 internal/web/runtime/remote_inbound_catalog_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f8c2c9d3..73f7498be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,6 +155,9 @@ jobs: exit 1 fi + - name: PostgreSQL inbound catalog scope and projection + run: go test ./internal/web -run '^TestRemoteInboundCatalogScopeAndProjection$' -count=1 -v + - name: PostgreSQL online attribution regressions run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/inbounds.mdx b/docs/content/docs/en/reference/api/inbounds.mdx index 165dc5fd8..3f0d9d5ca 100644 --- a/docs/content/docs/en/reference/api/inbounds.mdx +++ b/docs/content/docs/en/reference/api/inbounds.mdx @@ -29,6 +29,11 @@ _openapi: for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...). url: '#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-' + - depth: 2 + title: List inbound metadata for the authenticated user. Returns id, tag, + remark, listen, protocol, and port for remote ID lookup and + reconciliation. + url: '#list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation' - depth: 2 title: Lightweight picker projection of the authenticated user’s inbounds. Returns id, remark, tag, protocol, port, a server-computed @@ -148,6 +153,10 @@ _openapi: Use this for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...). id: same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow- + - content: List inbound metadata for the authenticated user. Returns id, tag, + remark, listen, protocol, and port for remote ID lookup and + reconciliation. + id: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation - content: Lightweight picker projection of the authenticated user’s inbounds. Returns id, remark, tag, protocol, port, a server-computed tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on @@ -231,7 +240,11 @@ _openapi: decryption. An empty list can remove rules even from an incompatible inbound. Triggers an Xray restart. id: replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-nonempty-lists-require-tcp-with-tlsreality-and-no-active-vless-server-decryption-an-empty-list-can-remove-rules-even-from-an-incompatible-inbound-triggers-an-xray-restart - contents: [] + contents: + - content: Available to panel sessions, admin, node-admin, and node-sync tokens. + The catalog queries only metadata columns. An empty catalog is + returned as an empty array. + heading: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} @@ -241,7 +254,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index afb1a2f6b..870ef99e3 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -5867,6 +5867,43 @@ ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { @@ -7153,6 +7190,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "description": "Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index afb1a2f6b..870ef99e3 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -5867,6 +5867,43 @@ ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { @@ -7153,6 +7190,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "description": "Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 310051ae7..b8e09aa02 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1567,6 +1567,14 @@ export const EXAMPLES: Record = { ], "target": "old.example.com:443" }, + "RemoteInboundOption": { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + }, "ServerSettings": { "contentPaddingAddition": "", "disableCookies": false, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 542b3178d..378fc8b16 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -5841,6 +5841,43 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 62b462e76..4d2bca454 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1318,6 +1318,15 @@ export interface RealityWatchStatus { target: string; } +export interface RemoteInboundOption { + id: number; + listen: string; + port: number; + protocol: Protocol; + remark: string; + tag: string; +} + export interface ServerSettings { contentPaddingAddition?: string; disableCookies: boolean; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index f0a263118..de23c7e02 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1411,6 +1411,16 @@ export const RealityWatchStatusSchema = z.object({ }); export type RealityWatchStatus = z.infer; +export const RemoteInboundOptionSchema = z.object({ + id: z.number().int(), + listen: z.string(), + port: z.number().int(), + protocol: z.lazy(() => ProtocolSchema), + remark: z.string(), + tag: z.string(), +}); +export type RemoteInboundOption = z.infer; + export const ServerSettingsSchema = z.object({ contentPaddingAddition: z.string().optional(), disableCookies: z.boolean(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index a92ac3320..91080469e 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -303,6 +303,16 @@ export const sections: readonly Section[] = [ response: '{\n "success": true,\n "obj": [\n {\n "id": 1,\n "remark": "VLESS-443",\n "settings": {\n "clients": [\n { "email": "alice", "enable": true }\n ],\n "decryption": "none"\n },\n "clientStats": []\n }\n ]\n}', }, + { + method: 'GET', + path: '/panel/api/inbounds/catalog', + summary: + 'List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.', + description: + 'Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.', + responseSchema: 'RemoteInboundOption', + responseSchemaArray: true, + }, { method: 'GET', path: '/panel/api/inbounds/options', diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go index dcdbf55cf..50fdfa891 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -45,7 +45,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { token := node.mintToken("snapshot-link", "node-sync") master.start() node.start() - var lists, compact, full, unchanged, clientAdds atomic.Int32 + var catalogs, lists, compact, full, unchanged, clientAdds atomic.Int32 target, err := url.Parse(node.url()) if err != nil { t.Fatal(err) @@ -90,6 +90,8 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { } front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { switch req.URL.Path { + case "/panel/api/inbounds/catalog": + catalogs.Add(1) case "/panel/api/inbounds/list": lists.Add(1) case "/panel/api/inbounds/trafficSnapshot": @@ -114,10 +116,25 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { t.Fatal(err) } + params := map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true} + if version.master == current { + var options []inboundView + obj := master.call(http.MethodPost, "/panel/api/nodes/inbounds", params) + if err := json.Unmarshal(obj, &options); err != nil || len(options) != 1 || options[0].Id != source.Id { + t.Fatalf("read node options: %s, %v", obj, err) + } + var wantLists int32 + if version.node != current { + wantLists = 1 + } + if got := lists.Swap(0); catalogs.Load() != 1 || got != wantLists { + t.Fatalf("node options used catalog=%d and full list=%d, want 1 and %d", catalogs.Load(), got, wantLists) + } + } if version.master == current { node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil)) } - master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) + master.call(http.MethodPost, "/panel/api/nodes/add", params) eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { ib, ok := master.inboundOnPort(inboundPort) ready := lists.Load() >= 3 diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go index 879b6e930..bbe7fc371 100644 --- a/internal/web/controller/api.go +++ b/internal/web/controller/api.go @@ -114,6 +114,7 @@ var monitorScopeAllow = map[string]struct{}{ var nodeSyncScopeAllow = map[string]map[string]struct{}{ "/server/status": {http.MethodGet: {}}, "/inbounds/list": {http.MethodGet: {}}, + "/inbounds/catalog": {http.MethodGet: {}}, "/inbounds/trafficSnapshot": {http.MethodGet: {}}, "/inbounds/add": {http.MethodPost: {}}, "/inbounds/del/:id": {http.MethodPost: {}}, diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index f89aea5bb..d8354d795 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -84,6 +84,7 @@ func (a *InboundController) initRouter(g *gin.RouterGroup) { g.GET("/trafficSnapshot", a.getTrafficSnapshot) g.GET("/list/slim", a.getInboundsSlim) g.GET("/options", a.getInboundOptions) + g.GET("/catalog", a.getInboundCatalog) g.GET("/allLinks", a.getAllInboundLinks) g.GET("/get/:id", a.getInbound) g.GET("/:id/fallbacks", a.getFallbacks) @@ -152,6 +153,15 @@ func (a *InboundController) getInboundOptions(c *gin.Context) { jsonObj(c, options, nil) } +func (a *InboundController) getInboundCatalog(c *gin.Context) { + options, err := a.inboundService.GetInboundCatalog(session.GetLoginUser(c).Id) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err) + return + } + jsonObj(c, options, nil) +} + // getAmneziaWGKernelReadiness reports whether this host can run an AmneziaWG // inbound on the kernel module, so the form can disable the toggle and say why. func (a *InboundController) getAmneziaWGKernelReadiness(c *gin.Context) { diff --git a/internal/web/job/ldap_sync_hung_node_test.go b/internal/web/job/ldap_sync_hung_node_test.go index 0c9d2c55e..f89ef01f2 100644 --- a/internal/web/job/ldap_sync_hung_node_test.go +++ b/internal/web/job/ldap_sync_hung_node_test.go @@ -29,7 +29,7 @@ func ldapHungNodeInbound(t *testing.T, emails []string) (*resetGate, *model.Inbo srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) w.Header().Set("Content-Type", "application/json") - if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/list") { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/catalog") { _, _ = w.Write([]byte(`{"success":true,"obj":[{"id":1,"tag":"` + tag + `"}]}`)) return } diff --git a/internal/web/job/node_traffic_isolation_test.go b/internal/web/job/node_traffic_isolation_test.go index 68bed06a1..82d74a063 100644 --- a/internal/web/job/node_traffic_isolation_test.go +++ b/internal/web/job/node_traffic_isolation_test.go @@ -39,11 +39,14 @@ func TestNodeTrafficSyncAllowsHealthyNextTickDuringSlowReconcile(t *testing.T) { var slowID int for _, slow := range []bool{true, false} { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + switch { + case slow && strings.HasSuffix(r.URL.Path, "/inbounds/catalog"): slowReconciles.Add(1) slowRequests <- struct{}{} <-release - } else if !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + case slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"): + slowRequests <- struct{}{} + case !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"): fastRequests <- struct{}{} } w.Header().Set("Content-Type", "application/json") diff --git a/internal/web/job/periodic_traffic_reset_nodes_test.go b/internal/web/job/periodic_traffic_reset_nodes_test.go index 18619fd1b..525a220f6 100644 --- a/internal/web/job/periodic_traffic_reset_nodes_test.go +++ b/internal/web/job/periodic_traffic_reset_nodes_test.go @@ -46,7 +46,7 @@ func resetNode(t *testing.T, gate *resetGate, name, inboundTag string) int { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) - if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/list") { + if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/catalog") { w.Header().Set("Content-Type", "application/json") _, _ = fmt.Fprintf(w, `{"success":true,"obj":[{"id":1,"tag":%q}]}`, inboundTag) return diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index f2e13b453..83d7b81ca 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -13,14 +13,17 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" "github.com/robfig/cron/v3" + "gorm.io/gorm" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/util/crypto" "github.com/mhsanaei/3x-ui/v3/internal/web/global" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" @@ -137,6 +140,79 @@ func seedNodeTraffic(t *testing.T, emails ...string) { const contractTag = "in-51001-tcp" +func TestRemoteInboundCatalogScopeAndProjection(t *testing.T) { + cleanup, err := testpg.IsolatePackage("inbound_catalog") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + node := startContractNode(t) + db := database.GetDB() + var user model.User + if err := db.Order("id ASC").First(&user).Error; err != nil { + t.Fatal(err) + } + owned := masterInbound("owned", true, "private") + owned.UserId, owned.Listen = user.Id, "127.0.0.1" + other := masterInbound("different owner", true, "private-other") + other.UserId, other.Port, other.Tag = user.Id+1, 51002, "in-51002-tcp" + if err := db.Create([]*model.Inbound{owned, other}).Error; err != nil { + t.Fatal(err) + } + var reads, wide atomic.Int32 + if err := db.Callback().Query().After("gorm:query").Register("test:catalog_projection", func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + reads.Add(1) + sql := tx.Statement.SQL.String() + if strings.Contains(sql, "*") || strings.Contains(sql, "settings") { + wide.Add(1) + } + } + }); err != nil { + t.Fatal(err) + } + for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeAdmin, model.ApiScopeNodeSync, model.ApiScopeMonitor} { + t.Run(scope, func(t *testing.T) { + node.masterWithToken(t, scope) + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, node.srv.URL+"/panel/api/inbounds/catalog", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer contract-"+scope) + resp, err := node.srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if scope == model.ApiScopeMonitor { + if resp.StatusCode != http.StatusForbidden { + t.Fatalf("monitor catalog status=%d, want forbidden", resp.StatusCode) + } + return + } + var envelope struct { + Success bool + Obj []map[string]any + } + if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK || !envelope.Success || len(envelope.Obj) != 1 { + t.Fatalf("catalog status=%d envelope=%+v", resp.StatusCode, envelope) + } + got := envelope.Obj[0] + if len(got) != 6 || got["id"] != float64(owned.Id) || got["tag"] != owned.Tag || + got["remark"] != owned.Remark || got["listen"] != owned.Listen || + got["protocol"] != string(owned.Protocol) || got["port"] != float64(owned.Port) { + t.Fatalf("unexpected catalog fields: %v", got) + } + }) + } + if reads.Load() != 3 || wide.Load() != 0 { + t.Fatalf("catalog queries = %d, wide queries = %d", reads.Load(), wide.Load()) + } +} + func masterInbound(remark string, enable bool, clients ...string) *model.Inbound { entries := make([]string, 0, len(clients)) for i, email := range clients { diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 8e225320c..42fc4bd1e 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -17,6 +17,11 @@ import ( func TestReconcileInbound_SkipsUnchanged(t *testing.T) { var pushes atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/panel/api/inbounds/add" { + pushes.Add(1) + _, _ = w.Write([]byte(`{"success":true,"obj":{"id":7,"tag":"in-1"}}`)) + return + } if r.Method == http.MethodPost && (strings.Contains(r.URL.Path, "/panel/api/inbounds/update/") || strings.Contains(r.URL.Path, "/panel/api/inbounds/add")) { pushes.Add(1) @@ -109,6 +114,9 @@ func newCountingNodeServer(t *testing.T, clientsResp string) (*httptest.Server, srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch { + case r.URL.Path == "/panel/api/inbounds/catalog": + _, _ = w.Write([]byte(`{"success":true,"obj":[]}`)) + return case strings.Contains(r.URL.Path, "/panel/api/inbounds/add"): counts.adds.Add(1) case strings.Contains(r.URL.Path, "/panel/api/inbounds/update/"): diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index e3e0830fd..cfdf8c9a1 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -94,6 +94,8 @@ type Remote struct { mu sync.RWMutex remoteIDByTag map[string]int adoptedAliases map[string]string + catalogFlight *inboundCatalogFlight + catalogVersion uint64 // pushedFP holds the fingerprint of the last inbound wire payload successfully // pushed, keyed by panel-side tag, so reconcile can skip re-sending an // unchanged inbound. Guarded by mu; dropped with the Remote on node config change. @@ -123,12 +125,12 @@ type Remote struct { } type RemoteInboundOption struct { - Id int `json:"id"` - Tag string `json:"tag"` - Remark string `json:"remark"` - Listen string `json:"listen"` - Protocol model.Protocol `json:"protocol"` - Port int `json:"port"` + Id int `json:"id" example:"7"` + Tag string `json:"tag" example:"in-443"` + Remark string `json:"remark" example:"VLESS-443"` + Listen string `json:"listen" example:"127.0.0.1"` + Protocol model.Protocol `json:"protocol" example:"vless"` + Port int `json:"port" example:"443"` } func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { @@ -190,7 +192,7 @@ func (r *Remote) nodeSupports(ctx context.Context, capability string) (bool, err caps := r.nodeCaps r.mu.RUnlock() if caps == nil { - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, ""); err != nil { return false, err } r.mu.RLock() @@ -444,7 +446,7 @@ func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) { if id, ok := r.cacheGetTag(tag); ok { return id, nil } - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, tag); err != nil { return 0, err } if id, ok := r.cacheGetTag(tag); ok { @@ -478,24 +480,32 @@ func (r *Remote) cacheGetTag(tag string) (int, bool) { return r.cachedTagID(tag) } +// cachedTagID requires r.mu to be held. func (r *Remote) cachedTagID(tag string) (int, bool) { - if id, ok := r.remoteIDByTag[tag]; ok { + return lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)) +} + +func lookupRemoteTag(ids map[string]int, tag, prefix string) (int, bool) { + if id, ok := ids[tag]; ok { return id, true } - prefix := nodeInboundTagPrefix(r.node.Id) if stripped, found := strings.CutPrefix(tag, prefix); found { - tag = stripped - } else { - tag = prefix + tag + id, ok := ids[stripped] + return id, ok } - id, ok := r.remoteIDByTag[tag] + id, ok := ids[prefix+tag] return id, ok } func (r *Remote) cacheSet(tag string, id int) { r.mu.Lock() defer r.mu.Unlock() + previous, known := r.cachedTagID(tag) r.remoteIDByTag[tag] = id + // Settings-only pushes do not supersede the catalog's ID mapping. + if !known || previous != id { + r.catalogVersion++ + } } func (r *Remote) cacheDel(tag string) { @@ -503,19 +513,11 @@ func (r *Remote) cacheDel(tag string) { defer r.mu.Unlock() delete(r.remoteIDByTag, tag) delete(r.pushedFP, tag) -} - -// forgetTag drops every tag form cacheGetTag would match, once the node reports -// none of them, so the next resolve re-reads the node instead of a deleted id. -func (r *Remote) forgetTag(tag string) { - prefix := nodeInboundTagPrefix(r.node.Id) - bare := strings.TrimPrefix(tag, prefix) - r.cacheDel(bare) - r.cacheDel(prefix + bare) + r.catalogVersion++ } func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) { - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, ""); err != nil { return nil, err } r.mu.RLock() @@ -528,52 +530,8 @@ func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) { } func (r *Remote) ListInboundOptions(ctx context.Context) ([]RemoteInboundOption, error) { - env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) - if err != nil { - return nil, err - } - list, err := json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds) - if err != nil { - return nil, fmt.Errorf("decode inbound list: %w", err) - } - return list, nil -} - -func (r *Remote) refreshRemoteIDs(ctx context.Context) error { - env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) - if err != nil { - return err - } - list, err := json_util.DecodeCappedList[struct { - Id int `json:"id"` - Tag string `json:"tag"` - }](env.Obj, maxNodeInbounds) - if err != nil { - return fmt.Errorf("decode inbound list: %w", err) - } - next := make(map[string]int, len(list)) - for _, ib := range list { - if ib.Tag == "" { - continue - } - next[ib.Tag] = ib.Id - } - r.mu.Lock() - // A rebuild sees only node-reported tags, so the adopted aliases must be - // re-applied or a later op on an adopted inbound re-creates it as a duplicate. - for centralTag, nodeTag := range r.adoptedAliases { - // A tag the node reports itself is authoritative; the alias only fills - // the gap left for a central tag the node knows under another name. - if _, reported := next[centralTag]; reported { - continue - } - if id, ok := next[nodeTag]; ok { - next[centralTag] = id - } - } - r.remoteIDByTag = next - r.mu.Unlock() - return nil + list, err := r.loadInboundCatalog(ctx, "") + return slices.Clone(list), err } func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error { @@ -652,16 +610,17 @@ func (r *Remote) SetInboundSubSortIndex(ctx context.Context, ib *model.Inbound, // whether a push actually happened. This turns a full-fleet reconcile from "send // every inbound's full settings" into "send only what changed". func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, existsOnNode bool) (bool, error) { + if !existsOnNode { + r.ForgetInbound(ib.Tag) + err := r.AddInbound(ctx, ib) + return err == nil, err + } fp := wireFingerprint(wireInbound(ib, r.node.Id)) - if existsOnNode { - r.mu.RLock() - prev, ok := r.pushedFP[ib.Tag] - r.mu.RUnlock() - if ok && prev.fingerprint == fp { - return false, nil - } - } else { - r.forgetTag(ib.Tag) + r.mu.RLock() + prev, ok := r.pushedFP[ib.Tag] + r.mu.RUnlock() + if ok && prev.fingerprint == fp { + return false, nil } if err := r.UpdateInbound(ctx, ib, ib); err != nil { return false, err @@ -702,14 +661,22 @@ func (r *Remote) ForgetInbound(tag string) { bare := strings.TrimPrefix(tag, prefix) r.mu.Lock() defer r.mu.Unlock() - for _, t := range []string{bare, prefix + bare} { - if alias, ok := r.adoptedAliases[t]; ok { - delete(r.remoteIDByTag, alias) - delete(r.adoptedAliases, t) + forget := func(t string) { + t = strings.TrimPrefix(t, prefix) + for _, form := range []string{t, prefix + t} { + delete(r.remoteIDByTag, form) + delete(r.pushedFP, form) } - delete(r.remoteIDByTag, t) - delete(r.pushedFP, t) } + for central, nodeTag := range r.adoptedAliases { + if strings.TrimPrefix(central, prefix) == bare || strings.TrimPrefix(nodeTag, prefix) == bare { + forget(central) + forget(nodeTag) + delete(r.adoptedAliases, central) + } + } + forget(bare) + r.catalogVersion++ } // AdoptInboundAlias records a deployed alias without mutating either panel. @@ -720,6 +687,7 @@ func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption r.remoteIDByTag[remote.Tag] = remote.Id r.remoteIDByTag[ib.Tag] = remote.Id r.adoptedAliases[ib.Tag] = remote.Tag + r.catalogVersion++ r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -831,7 +799,7 @@ func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json. var refreshErr error for _, tag := range tags { if id, ok := r.cacheGetTag(tag); !ok || id <= 0 { - refreshErr = r.refreshRemoteIDs(ctx) + _, refreshErr = r.loadInboundCatalog(ctx, "") break } } diff --git a/internal/web/runtime/remote_inbound_catalog.go b/internal/web/runtime/remote_inbound_catalog.go new file mode 100644 index 000000000..5531cc031 --- /dev/null +++ b/internal/web/runtime/remote_inbound_catalog.go @@ -0,0 +1,153 @@ +package runtime + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + + "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" +) + +type inboundCatalogFlight struct { + done chan struct{} + cancel context.CancelFunc + waiters int + options []RemoteInboundOption + err error +} + +// loadInboundCatalog shares a refresh across callers. A lookup rechecks its cache +// under the same lock used to register the flight. +func (r *Remote) loadInboundCatalog(ctx context.Context, tag string) ([]RemoteInboundOption, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.Lock() + if tag != "" { + if _, ok := lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)); ok { + r.mu.Unlock() + return nil, nil + } + } + flight := r.catalogFlight + if flight == nil { + // The RPC belongs to the group. Each caller waits on its own context. + requestCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), remoteHTTPTimeout) + flight = &inboundCatalogFlight{done: make(chan struct{}), cancel: cancel} + r.catalogFlight = flight + go r.refreshInboundCatalog(requestCtx, flight, r.catalogVersion) + } + flight.waiters++ + r.mu.Unlock() + + select { + case <-flight.done: + if err := ctx.Err(); err != nil { + return nil, err + } + return flight.options, flight.err + case <-ctx.Done(): + r.mu.Lock() + flight.waiters-- + if r.catalogFlight == flight && flight.waiters == 0 { + r.catalogFlight = nil + flight.cancel() + } + r.mu.Unlock() + return nil, ctx.Err() + } +} + +func (r *Remote) refreshInboundCatalog(ctx context.Context, flight *inboundCatalogFlight, version uint64) { + defer flight.cancel() + defer close(flight.done) + for attempt := 0; ; attempt++ { + options, ids, err := r.fetchInboundCatalog(ctx) + r.mu.Lock() + if r.catalogFlight != flight { + r.mu.Unlock() + return + } + if err == nil && version != r.catalogVersion { + // An inbound mutation completed during the read. Retry once within + // the same budget, so a stale response cannot revive an old ID. + if attempt == 0 { + version = r.catalogVersion + r.mu.Unlock() + continue + } + err = errors.New("remote inbound catalog changed during refresh") + } + if err == nil { + r.installInboundCatalog(ids) + flight.options = options + } + flight.err = err + r.catalogFlight = nil + r.mu.Unlock() + return + } +} + +func (r *Remote) fetchInboundCatalog(ctx context.Context) (list []RemoteInboundOption, ids map[string]int, err error) { + // Fetching runs on the shared worker, outside each caller's panic boundary. + defer func() { + if cause := recover(); cause != nil { + list, ids, err = nil, nil, fmt.Errorf("fetch inbound catalog: panic: %v", cause) + } + }() + env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/catalog", nil) + var status *remoteHTTPError + legacy := errors.As(err, &status) && (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed) + if legacy { + env, err = r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) + } + if err != nil { + return nil, nil, err + } + if !legacy && !bytes.HasPrefix(bytes.TrimSpace(env.Obj), []byte("[")) { + return nil, nil, errors.New("decode inbound list: catalog must be an array") + } + list, err = json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds) + if err != nil { + return nil, nil, fmt.Errorf("decode inbound list: %w", err) + } + ids = make(map[string]int, len(list)) + for _, ib := range list { + if ib.Id <= 0 || ib.Tag == "" { + return nil, nil, errors.New("decode inbound list: entry missing a valid ID or tag") + } + if _, exists := ids[ib.Tag]; exists { + return nil, nil, errors.New("decode inbound list: duplicate tag") + } + ids[ib.Tag] = ib.Id + } + return list, ids, nil +} + +// installInboundCatalog runs with mu held. Explicit node tags outrank inferred aliases. +func (r *Remote) installInboundCatalog(ids map[string]int) { + prefix := nodeInboundTagPrefix(r.node.Id) + aliases := make(map[string]int, len(r.adoptedAliases)) + for central, nodeTag := range r.adoptedAliases { + if _, exists := lookupRemoteTag(ids, central, prefix); exists { + continue + } + if id, ok := lookupRemoteTag(ids, nodeTag, prefix); ok { + aliases[central] = id + } + } + for tag, id := range aliases { + ids[tag] = id + } + for tag := range r.pushedFP { + oldID, known := lookupRemoteTag(r.remoteIDByTag, tag, prefix) + nextID, present := lookupRemoteTag(ids, tag, prefix) + if !present || known && nextID != oldID { + delete(r.pushedFP, tag) + } + } + r.remoteIDByTag = ids +} diff --git a/internal/web/runtime/remote_inbound_catalog_test.go b/internal/web/runtime/remote_inbound_catalog_test.go new file mode 100644 index 000000000..b34e01edd --- /dev/null +++ b/internal/web/runtime/remote_inbound_catalog_test.go @@ -0,0 +1,334 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type observedCatalogContext struct { + context.Context + waiting chan struct{} + once sync.Once +} + +func (ctx *observedCatalogContext) Done() <-chan struct{} { + ctx.once.Do(func() { close(ctx.waiting) }) + return ctx.Context.Done() +} + +func TestRemoteInboundCatalogCoalescesMissesAcrossCallerCancellation(t *testing.T) { + var modern, legacy atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var first, cleanup sync.Once + unblock := func() { cleanup.Do(func() { close(release) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + modern.Add(1) + case "/panel/api/inbounds/list": + legacy.Add(1) + default: + http.NotFound(w, req) + return + } + first.Do(func() { close(started) }) + select { + case <-release: + fmt.Fprint(w, `{"success":true,"obj":[{"id":43,"tag":"in-443"}]}`) + case <-req.Context().Done(): + } + })) + t.Cleanup(srv.Close) + t.Cleanup(unblock) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx, finish := context.WithTimeout(context.Background(), 4*time.Second) + defer finish() + leaderCtx, cancel := context.WithCancel(ctx) + defer cancel() + leader := make(chan error, 1) + go func() { + _, err := r.resolveRemoteID(leaderCtx, "in-443") + leader <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog request never started") + } + const followers = 6 + results := make(chan error, followers) + tag := fmt.Sprintf("n%d-in-443", r.node.Id) + for range followers { + waiter := &observedCatalogContext{Context: ctx, waiting: make(chan struct{})} + go func() { + id, err := r.resolveRemoteID(waiter, tag) + if err == nil && id != 43 { + err = fmt.Errorf("resolved ID = %d, want 43", id) + } + results <- err + }() + select { + case <-waiter.waiting: + case <-ctx.Done(): + t.Fatal("follower did not join the lookup") + } + } + cancel() + select { + case err := <-leader: + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled caller got %v", err) + } + case <-ctx.Done(): + t.Fatal("canceled caller still waits on the catalog") + } + unblock() + for range followers { + select { + case err := <-results: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("follower never received the catalog") + } + } + if id, err := r.resolveRemoteID(ctx, tag); err != nil || id != 43 { + t.Fatalf("warm cache = (%d, %v), want 43", id, err) + } + if modern.Load() != 1 || legacy.Load() != 0 { + t.Fatalf("catalog requests = %d, full list requests = %d; want 1 and 0", modern.Load(), legacy.Load()) + } +} + +func TestRemoteInboundCatalogLegacyFallbackSeedsCache(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} { + t.Run(http.StatusText(status), func(t *testing.T) { + var modern, legacy atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + modern.Add(1) + w.WriteHeader(status) + case "/panel/api/inbounds/list": + legacy.Add(1) + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"test","port":443,"settings":"large"}]}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx := context.Background() + options, err := r.ListInboundOptions(ctx) + if err != nil || len(options) != 1 || options[0].Port != 443 { + t.Fatalf("legacy options=%+v err=%v", options, err) + } + if id, err := r.resolveRemoteID(ctx, "test"); err != nil || id != 7 { + t.Fatalf("legacy ID = %d, err=%v", id, err) + } + if modern.Load() != 1 || legacy.Load() != 1 { + t.Fatalf("catalog requests=%d full list requests=%d, want 1 each", modern.Load(), legacy.Load()) + } + }) + } +} + +func TestRemoteInboundCatalogSurvivesSettingsOnlyPushes(t *testing.T) { + var reads atomic.Int32 + started := make(chan chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + reads.Add(1) + resume := make(chan struct{}) + select { + case started <- resume: + case <-req.Context().Done(): + return + } + select { + case <-resume: + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"warm"},{"id":8,"tag":"cold"}]}`) + case <-req.Context().Done(): + } + case "/panel/api/inbounds/update/7": + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + r.cacheSet("warm", 7) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + id, err := r.resolveRemoteID(ctx, "cold") + if err == nil && id != 8 { + err = fmt.Errorf("cold lookup resolved ID %d, want 8", id) + } + done <- err + }() + + for { + select { + case resume := <-started: + before := &model.Inbound{Tag: "warm", Protocol: model.VLESS, Settings: `{"clients":[]}`} + after := *before + after.Settings = fmt.Sprintf(`{"clients":[{"email":"client-%d@example.test"}]}`, reads.Load()) + err := r.UpdateInbound(ctx, before, &after) + close(resume) + if err != nil { + t.Fatal(err) + } + case err := <-done: + if err != nil || reads.Load() != 1 { + t.Fatalf("lookup during settings-only updates: reads=%d, err=%v", reads.Load(), err) + } + return + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } +} + +func TestRemoteInboundCatalogDoesNotRestoreDeletedAlias(t *testing.T) { + var gets atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list": + if gets.Add(1) == 1 { + close(started) + <-release + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"adopted"}]}`) + } else { + fmt.Fprint(w, `{"success":true,"obj":[]}`) + } + case "/panel/api/inbounds/del/7": + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + t.Cleanup(unblock) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ib := &model.Inbound{Tag: "central", Protocol: model.VLESS} + r.AdoptInboundAlias(ib, RemoteInboundOption{Id: 7, Tag: "adopted"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + options, err := r.ListInboundOptions(ctx) + if err == nil && len(options) != 0 { + err = fmt.Errorf("stale catalog returned: %+v", options) + } + done <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog never started") + } + if err := r.DelInbound(ctx, &model.Inbound{Tag: "adopted"}); err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + if _, ok := r.cacheGetTag(ib.Tag); ok || gets.Load() != 2 { + t.Fatalf("deleted alias still cached or stale read was not retried: gets=%d", gets.Load()) + } +} + +func TestRemoteInboundCatalogRefreshDetectsRecreatedInbound(t *testing.T) { + var remoteID, pushedID atomic.Int32 + remoteID.Store(7) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + fmt.Fprintf(w, `{"success":true,"obj":[{"id":%d,"tag":"in-443"}]}`, remoteID.Load()) + case "/panel/api/inbounds/update/7": + pushedID.Store(7) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/update/8": + pushedID.Store(8) + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ib := &model.Inbound{Tag: "in-443", Protocol: model.VLESS, Port: 443} + ctx := context.Background() + if err := r.UpdateInbound(ctx, ib, ib); err != nil || pushedID.Load() != 7 { + t.Fatalf("first update used ID %d, err=%v", pushedID.Load(), err) + } + remoteID.Store(8) + if _, err := r.ListInboundOptions(ctx); err != nil { + t.Fatal(err) + } + if pushed, err := r.ReconcileInbound(ctx, ib, true); err != nil || !pushed || pushedID.Load() != 8 { + t.Fatalf("reconcile after recreation: pushed=%t, ID=%d, err=%v", pushed, pushedID.Load(), err) + } +} + +func TestRemoteInboundCatalogCancelsRPCWhenLastWaiterLeaves(t *testing.T) { + var calls atomic.Int32 + started, canceled := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if calls.Add(1) == 1 { + close(started) + <-req.Context().Done() + close(canceled) + return + } + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"valid"}]}`) + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx, finish := context.WithTimeout(context.Background(), 3*time.Second) + defer finish() + lookup, cancel := context.WithCancel(ctx) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := r.resolveRemoteID(lookup, "valid") + done <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog never started") + } + cancel() + if err := <-done; !errors.Is(err, context.Canceled) { + t.Fatalf("lookup error=%v, want canceled", err) + } + select { + case <-canceled: + case <-ctx.Done(): + t.Fatal("abandoned catalog request was not canceled") + } + if id, err := r.resolveRemoteID(ctx, "valid"); err != nil || id != 7 || calls.Load() != 2 { + t.Fatalf("fresh lookup ID=%d err=%v calls=%d", id, err, calls.Load()) + } +} diff --git a/internal/web/runtime/remote_inbound_lookup_test.go b/internal/web/runtime/remote_inbound_lookup_test.go index a0504029b..05441f24f 100644 --- a/internal/web/runtime/remote_inbound_lookup_test.go +++ b/internal/web/runtime/remote_inbound_lookup_test.go @@ -23,11 +23,13 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) { {"unavailable", http.StatusServiceUnavailable, "", "HTTP 503"}, {"application error", http.StatusOK, `{"success":false,"msg":"node database unavailable"}`, "node database unavailable"}, {"invalid catalog", http.StatusOK, `{"success":true,"obj":{"id":4}}`, "decode inbound list"}, + {"missing catalog", http.StatusOK, `{"success":true}`, "decode inbound list"}, + {"invalid row", http.StatusOK, `{"success":true,"obj":[{"id":0,"tag":"in-lookup"}]}`, "decode inbound list"}, } { t.Run(tc.name, func(t *testing.T) { var mutations atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/list") { + if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/catalog") { mutations.Add(1) _, _ = w.Write([]byte(`{"success":true}`)) return @@ -45,7 +47,7 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) { t.Errorf("UpdateInbound error = %v, want %q", err, tc.want) } if got := mutations.Load(); got != 0 { - t.Errorf("mutation requests after failed lookup = %d, want 0", got) + t.Errorf("mutation or fallback requests after failed lookup = %d, want 0", got) } }) } diff --git a/internal/web/runtime/remote_reset_test.go b/internal/web/runtime/remote_reset_test.go index 27159e3e6..722d29bff 100644 --- a/internal/web/runtime/remote_reset_test.go +++ b/internal/web/runtime/remote_reset_test.go @@ -3,6 +3,7 @@ package runtime import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "slices" @@ -62,7 +63,7 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) { var resetPosted bool srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") - if req.URL.Path == "/panel/api/inbounds/list" { + if req.URL.Path == "/panel/api/inbounds/catalog" { _, _ = w.Write([]byte(`{"success":true,"msg":"ok","obj":[]}`)) return } @@ -73,8 +74,8 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) { r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) ib := &model.Inbound{Id: 42, Tag: "n1-in-443"} - if err := r.ResetInboundTraffic(context.Background(), ib); err == nil { - t.Fatal("ResetInboundTraffic error = nil, want unknown-tag error") + if err := r.ResetInboundTraffic(context.Background(), ib); !errors.Is(err, errRemoteInboundNotFound) { + t.Fatalf("ResetInboundTraffic error = %v, want unknown-tag error", err) } if resetPosted { t.Fatal("reset request posted to node despite an unresolved tag") diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go index 87f435e46..e56e722fc 100644 --- a/internal/web/service/client_create_reconcile_test.go +++ b/internal/web/service/client_create_reconcile_test.go @@ -33,7 +33,7 @@ type groupedCreatePeer struct { func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch { - case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + case strings.HasSuffix(r.URL.Path, "/inbounds/catalog"), strings.HasSuffix(r.URL.Path, "/inbounds/list"): p.mu.Lock() catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags)) for tag, id := range p.tags { diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 59bc2cabe..03fe9cd14 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -400,6 +400,17 @@ type InboundOption struct { ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"` } +// GetInboundCatalog selects the fields needed for remote inbound lookup and reconciliation. +func (s *InboundService) GetInboundCatalog(userID int) ([]runtime.RemoteInboundOption, error) { + catalog := make([]runtime.RemoteInboundOption, 0) + err := database.GetDB().Model(&model.Inbound{}). + Select("id", "tag", "remark", "listen", "protocol", "port"). + Where("user_id = ?", userID). + Order("id ASC"). + Find(&catalog).Error + return catalog, err +} + func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) { db := database.GetDB() var rows []struct { diff --git a/internal/web/service/inbound_node_reconcile_test.go b/internal/web/service/inbound_node_reconcile_test.go index 2075f1fc1..0e62543da 100644 --- a/internal/web/service/inbound_node_reconcile_test.go +++ b/internal/web/service/inbound_node_reconcile_test.go @@ -12,6 +12,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "github.com/mhsanaei/3x-ui/v3/internal/database" @@ -263,7 +264,7 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "msg": "", "obj": obj}) } mux := http.NewServeMux() - mux.HandleFunc("/panel/api/inbounds/list", func(w http.ResponseWriter, _ *http.Request) { + mux.HandleFunc("/panel/api/inbounds/catalog", func(w http.ResponseWriter, _ *http.Request) { writeOK(w, []map[string]any{{"id": 41, "tag": "already-deployed", "listen": "", "port": 8443, "protocol": "vless"}}) }) mux.HandleFunc("/panel/api/inbounds/", func(w http.ResponseWriter, _ *http.Request) { @@ -301,6 +302,45 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes } } +func TestReconcileNodeUsesOneCatalogForUpdatesCreatesAndDeletes(t *testing.T) { + setupConflictDB(t) + var reads, fullLists, adds, updates, deletes atomic.Int32 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list": + if req.URL.Path == "/panel/api/inbounds/catalog" { + reads.Add(1) + } else { + fullLists.Add(1) + } + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"existing"},{"id":6,"tag":"removed"}]}`) + case "/panel/api/inbounds/add": + adds.Add(1) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/update/7": + updates.Add(1) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/del/6": + deletes.Add(1) + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(ts.Close) + node := reconcileTestNode(t, ts, "catalog-node", "all", nil) + for i, tag := range []string{"existing", "missing-a", "missing-b"} { + seedInboundConflictNode(t, tag, "", 12000+i, model.VLESS, `{"network":"tcp"}`, `{"clients":[]}`, &node.Id) + } + svc := InboundService{} + if err := svc.ReconcileNode(context.Background(), runtime.NewRemote(node, nil), node); err != nil { + t.Fatal(err) + } + if reads.Load() != 1 || fullLists.Load() != 0 || adds.Load() != 2 || updates.Load() != 1 || deletes.Load() != 1 { + t.Fatalf("catalog=%d full list=%d adds=%d updates=%d deletes=%d", reads.Load(), fullLists.Load(), adds.Load(), updates.Load(), deletes.Load()) + } +} + func TestReconcileNode_AmbiguousCompatibleInboundsAreNotSwept(t *testing.T) { setupConflictDB(t) diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index aaf21b930..aaf1655b4 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -27,7 +27,7 @@ type fakeNodeHTTP struct { pendingClientAcks int clientAdds []ClientCreatePayload clientAddEvents chan ClientCreatePayload - // hold makes every non-list request block until the master gives up. + // hold makes requests outside inbound discovery block until the master gives up. hold bool release chan struct{} } @@ -43,7 +43,7 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { f.mu.Lock() w.Header().Set(wirecodec.CapsHeader, f.caps) f.mu.Unlock() - if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + if strings.HasSuffix(r.URL.Path, "/inbounds/catalog") || strings.HasSuffix(r.URL.Path, "/inbounds/list") { f.mu.Lock() f.hits["list"]++ type ent struct { diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 2633d92c0..04362843f 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -97,7 +97,7 @@ func run(root, outDir string) error { }, { Path: resolveRel(root, "internal/web/runtime"), - StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1"), + StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1", "RemoteInboundOption"), }, { Path: resolveRel(root, "internal/web/service"),