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.
This commit is contained in:
Hamed
2026-12-03 03:26:44 +03:30
committed by GitHub
parent 8a686cd8bd
commit 0afa11ddff
27 changed files with 990 additions and 104 deletions
+3
View File
@@ -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
@@ -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}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/trafficSnapshot","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/amneziawgKernelReadiness","method":"get"},{"path":"/panel/api/inbounds/allLinks","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/subSortIndex","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/trafficSnapshot","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/catalog","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/amneziawgKernelReadiness","method":"get"},{"path":"/panel/api/inbounds/allLinks","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/subSortIndex","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
</>
);
}
+86
View File
@@ -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": [
+86
View File
@@ -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": [
+8
View File
@@ -1567,6 +1567,14 @@ export const EXAMPLES: Record<string, unknown> = {
],
"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,
+37
View File
@@ -5841,6 +5841,43 @@ export const SCHEMAS: Record<string, unknown> = {
],
"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": {
+9
View File
@@ -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;
+10
View File
@@ -1411,6 +1411,16 @@ export const RealityWatchStatusSchema = z.object({
});
export type RealityWatchStatus = z.infer<typeof RealityWatchStatusSchema>;
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<typeof RemoteInboundOptionSchema>;
export const ServerSettingsSchema = z.object({
contentPaddingAddition: z.string().optional(),
disableCookies: z.boolean(),
+10
View File
@@ -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',
+19 -2
View File
@@ -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
+1
View File
@@ -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: {}},
+10
View File
@@ -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) {
+1 -1
View File
@@ -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
}
@@ -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")
@@ -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
+76
View File
@@ -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 {
@@ -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/"):
+54 -86
View File
@@ -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
}
}
@@ -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
}
@@ -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())
}
}
@@ -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)
}
})
}
+4 -3
View File
@@ -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")
@@ -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 {
+11
View File
@@ -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 {
@@ -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)
+2 -2
View File
@@ -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 {
+1 -1
View File
@@ -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"),