From 6e2589e6c9a2e3acd0690c5a5541ffac0861cf11 Mon Sep 17 00:00:00 2001 From: delifer Date: Tue, 1 Dec 2026 01:38:05 +0700 Subject: [PATCH 1/7] Add LibreSpeed functionality to x-ui.sh (#7224) * Add LibreSpeed functionality to x-ui.sh I have applied the fixes we discussed earlier to the current version of the PR; please let me know if you have any further questions or comments. A hashsum check has been added, and the application itself runs with very restricted privileges, as it should. * Update selection range in x-ui.sh to 0-29 --- x-ui.sh | 117 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 115 insertions(+), 2 deletions(-) diff --git a/x-ui.sh b/x-ui.sh index a2ba4170b..cafceef8e 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -2262,6 +2262,115 @@ run_speedtest() { speedtest } +run_librespeed() { + local nc=$'\033[0m' + local ls_user="librespeed" # username + local ls_bin="/usr/local/bin/librespeed-cli" # path to binary file + local action launch=0 + + if [ "$(id -u)" -ne 0 ]; then # block launch as root + echo -e "${red}Run as root (needed for install and user management).${nc}" + return 1 + fi + + echo -e "${yellow}What do you want to do?\n1) Use\n2) Install/Update\n3) Delete${nc}" # Menu section + read -rp ": " action + + case "$action" in #Launch + 1) + if [ -x "$ls_bin" ]; then + launch=1 + else + echo -e "${red}LibreSpeed is not installed!${nc}" + return 1 + fi + ;; + + 2) + echo -e "${yellow}Installing/Updating LibreSpeed...${nc}" + ( + set -euo pipefail + + for dep in curl jq tar sha256sum install awk; do + command -v "$dep" &>/dev/null || { echo -e "${red}Missing dependency: $dep${nc}"; exit 1; } + done + + # Architecture detection + local arch + case "$(uname -m)" in + x86_64|amd64) arch=amd64 ;; + aarch64|arm64) arch=arm64 ;; + armv7l|armv8l) arch=armv7 ;; + armv6l) arch=armv6 ;; + i386|i686) arch=386 ;; + *) echo -e "${red}Unsupported architecture: $(uname -m)${nc}"; exit 1 ;; + esac + + local tmp release_json version asset url sums_url expected actual + local curl_opts=(--proto '=https' --tlsv1.2 -fsSL) + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + + release_json=$(curl "${curl_opts[@]}" "https://api.github.com/repos/librespeed/speedtest-cli/releases/latest") # official github api + version=$(jq -r '.tag_name | ltrimstr("v")' <<<"$release_json") + asset="librespeed-cli_${version}_linux_${arch}.tar.gz" + + url=$(jq -r --arg n "$asset" '.assets[] | select(.name==$n) | .browser_download_url' <<<"$release_json") + [ -n "$url" ] || { echo -e "${red}No release asset named $asset${nc}"; exit 1; } + + echo -e "${yellow}Downloading $asset...${nc}" + curl "${curl_opts[@]}" -o "$tmp/$asset" "$url" + + # checking hashsum, but it'll stil empty for else function + sums_url=$(jq -r '[.assets[] | select(.name | test("checksum|sha256";"i"))][0].browser_download_url // empty' <<<"$release_json") + if [ -n "$sums_url" ]; then + curl "${curl_opts[@]}" -o "$tmp/checksums" "$sums_url" + expected=$(awk -v f="$asset" '$2==f || $2=="*" f {print $1}' "$tmp/checksums") + else + expected=$(jq -r --arg n "$asset" '.assets[] | select(.name==$n) | .digest // empty' <<<"$release_json") + expected=${expected#sha256:} + fi + [ -n "$expected" ] || { echo -e "${red}No checksum available, aborting.${nc}"; exit 1; } + + actual=$(sha256sum "$tmp/$asset" | awk '{print $1}') + if [ "$actual" != "$expected" ]; then + echo -e "${red}Checksum mismatch!\n expected: $expected\n actual: $actual${nc}" #something is wrong with hashsum + exit 1 + fi + echo -e "${green}Checksum OK.${nc}" # all good with hashsum + + # Extract only the binary; install root-owned so the service user can't modify it + tar -xzf "$tmp/$asset" -C "$tmp" librespeed-cli + install -o root -g root -m 0755 "$tmp/librespeed-cli" "$ls_bin" # very low privilage permissions + rm -f /usr/bin/librespeed-cli + ) || { echo -e "${red}Install failed.${nc}"; return 1; } + launch=1 + ;; + + 3) + rm -f "$ls_bin" /usr/bin/librespeed-cli # Deleting librespeed-cli + id -u "$ls_user" &>/dev/null && userdel "$ls_user" + echo -e "${green}LibreSpeed was deleted!${nc}" + ;; + + *) + echo -e "${red}Invalid option.${nc}" + return 1 + ;; + esac + + if [ "$launch" -eq 1 ]; then + # Create the locked-down system account + if ! id -u "$ls_user" &>/dev/null; then + useradd --system --no-create-home --home-dir /nonexistent \ + --shell "$(command -v nologin || echo /usr/sbin/nologin)" "$ls_user" \ + || { echo -e "${red}Could not create user $ls_user${nc}"; return 1; } + fi + echo -e "${green}Starting LibreSpeed...${nc}" + runuser -u "$ls_user" -- env -i HOME=/nonexistent PATH=/usr/bin:/bin "$ls_bin" + fi +} + ip_validation() { ipv6_regex="^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$" ipv4_regex="^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)$" @@ -3776,10 +3885,11 @@ show_menu() { │ ${green}26.${plain} Enable BBR │ │ ${green}27.${plain} Update Geo Files │ │ ${green}28.${plain} Speedtest by Ookla │ +│ ${green}29.${plain} Librespeed │ ╚────────────────────────────────────────────────╝ " show_status - echo && read -rp "Please enter your selection [0-28]: " num + echo && read -rp "Please enter your selection [0-29]: " num case "${num}" in 0) @@ -3869,8 +3979,11 @@ show_menu() { 28) run_speedtest ;; + 29) + run_librespeed + ;; *) - LOGE "Please enter the correct number [0-28]" + LOGE "Please enter the correct number [0-29]" ;; esac } From 4a680cb85968772b1255dd26047208488c59b0bd Mon Sep 17 00:00:00 2001 From: Hamed Date: Mon, 30 Nov 2026 22:54:25 +0330 Subject: [PATCH 2/7] fix(sub): export Loon REALITY with the Chrome 147 profile (#7248) * fix(sub): export Loon REALITY with the Chrome 147 profile * fix(sub): detect Loon on the default subscription URL * docs(sub): translate the Loon REALITY import section into fa, ru and zh The Loon section added to the English REALITY page had no counterpart in the other three locales, so readers of those pages never learned that the default subscription URL now serves Loon's native format, or that format=loon and format=raw select it by hand. --------- Co-authored-by: Sanaei --- docs/content/docs/en/config/reality.mdx | 12 ++++ docs/content/docs/fa/config/reality.mdx | 14 ++++ docs/content/docs/ru/config/reality.mdx | 13 ++++ docs/content/docs/zh/config/reality.mdx | 6 ++ internal/sub/controller.go | 30 ++++++--- internal/sub/loon.go | 90 +++++++++++++++++++++++++ internal/sub/loon_test.go | 59 ++++++++++++++++ 7 files changed, 215 insertions(+), 9 deletions(-) create mode 100644 internal/sub/loon.go create mode 100644 internal/sub/loon_test.go diff --git a/docs/content/docs/en/config/reality.mdx b/docs/content/docs/en/config/reality.mdx index 2bd717076..06e1e3c05 100644 --- a/docs/content/docs/en/config/reality.mdx +++ b/docs/content/docs/en/config/reality.mdx @@ -139,6 +139,18 @@ vless://@:443?security=reality&pbk=&sid=&sni +### Import a REALITY subscription into Loon + +Import the raw subscription URL as a Loon remote proxy subscription. The panel +recognizes Loon's default User-Agent and serves its native format. If a custom +User-Agent is in use, add `?format=loon` to the URL (or `&format=loon` if it +already has query parameters). Use `format=raw` to request standard URIs in Loon. + +Eligible raw TCP VLESS REALITY nodes with the post-quantum hint use +`tls-profile=chrome147` and retain their server name, public key, short ID and +Vision flow. Other entries keep their share URIs. See the +[Loon node format](https://nsloon.app/en/docs/Node/) for client support. + ## Generate a config Use the generator below to create a fresh X25519 keypair, UUID, and short ID, diff --git a/docs/content/docs/fa/config/reality.mdx b/docs/content/docs/fa/config/reality.mdx index 87d006845..b6fcc21b9 100644 --- a/docs/content/docs/fa/config/reality.mdx +++ b/docs/content/docs/fa/config/reality.mdx @@ -152,6 +152,20 @@ vless://@:443?security=reality&pbk=&sid=&sni +### وارد کردن اشتراک REALITY در Loon + +URL خام اشتراک را به‌عنوان اشتراک پروکسی راه‌دور (Remote Proxy) در Loon وارد +کنید. پنل User-Agent پیش‌فرض Loon را تشخیص می‌دهد و قالب بومی آن را ارائه +می‌کند. اگر User-Agent سفارشی در کار است، `?format=loon` را به URL اضافه کنید +(یا `&format=loon` اگر URL از قبل پارامتر کوئری دارد). برای دریافت URIهای +استاندارد در Loon از `format=raw` استفاده کنید. + +گره‌های واجد شرایط VLESS REALITY روی TCP خام که راهنمای پساکوانتومی را دارند از +`tls-profile=chrome147` استفاده می‌کنند و نام سرور، کلید عمومی، short ID و جریان +Vision خود را حفظ می‌کنند. سایر ورودی‌ها همان URI اشتراک‌گذاری خود را نگه +می‌دارند. برای پشتیبانی کلاینت، +[قالب گره‌ی Loon](https://nsloon.app/en/docs/Node/) را ببینید. + ## تولید یک پیکربندی از تولیدکننده‌ی زیر برای ساخت یک جفت‌کلید تازه‌ی X25519، UUID و short ID استفاده diff --git a/docs/content/docs/ru/config/reality.mdx b/docs/content/docs/ru/config/reality.mdx index ea364fe47..89a3a0fca 100644 --- a/docs/content/docs/ru/config/reality.mdx +++ b/docs/content/docs/ru/config/reality.mdx @@ -144,6 +144,19 @@ vless://@:443?security=reality&pbk=&sid=&sni +### Импорт подписки REALITY в Loon + +Импортируйте исходный URL подписки в Loon как удалённую подписку на прокси. +Панель распознаёт User-Agent Loon по умолчанию и отдаёт его собственный формат. +Если используется свой User-Agent, добавьте к URL `?format=loon` (или +`&format=loon`, если в нём уже есть параметры запроса). Чтобы получить в Loon +стандартные URI, используйте `format=raw`. + +Подходящие узлы VLESS REALITY на обычном TCP с постквантовой подсказкой получают +`tls-profile=chrome147` и сохраняют имя сервера, открытый ключ, short ID и поток +Vision. Остальные записи остаются ссылками для подключения. О поддержке в +клиенте см. [формат узлов Loon](https://nsloon.app/en/docs/Node/). + ## Сгенерируйте конфигурацию Используйте генератор ниже, чтобы создать новую пару ключей X25519, UUID и short diff --git a/docs/content/docs/zh/config/reality.mdx b/docs/content/docs/zh/config/reality.mdx index 33e779aa9..031569be7 100644 --- a/docs/content/docs/zh/config/reality.mdx +++ b/docs/content/docs/zh/config/reality.mdx @@ -110,6 +110,12 @@ vless://@:443?security=reality&pbk=&sid=&sni +### 将 REALITY 订阅导入 Loon + +将原始订阅 URL 作为远程代理订阅导入 Loon。面板会识别 Loon 的默认 User-Agent 并返回其原生格式。如果使用了自定义 User-Agent,请在 URL 后添加 `?format=loon`(若已有查询参数则添加 `&format=loon`)。如需在 Loon 中获取标准 URI,请使用 `format=raw`。 + +带有后量子提示、符合条件的原始 TCP VLESS REALITY 节点会使用 `tls-profile=chrome147`,并保留其 server name、公钥、short ID 和 Vision 流控。其他条目仍保持为分享链接。客户端支持情况请参阅 [Loon 节点格式](https://nsloon.app/en/docs/Node/)。 + ## 生成配置 使用下面的生成器创建一对全新的 X25519 密钥、UUID 和 short ID,然后复制服务器入站 JSON 和客户端分享链接。 diff --git a/internal/sub/controller.go b/internal/sub/controller.go index ef155e99f..0a9af1fba 100644 --- a/internal/sub/controller.go +++ b/internal/sub/controller.go @@ -506,18 +506,22 @@ func dedupeEmails(emails []string) []string { // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data. func (a *SUBController) subs(c *gin.Context) { userAgent := c.GetHeader("User-Agent") + requestedFormat := c.Query("format") + loon := strings.EqualFold(requestedFormat, "loon") || + requestedFormat == "" && strings.HasPrefix(strings.ToLower(userAgent), "loon/") + c.Writer.Header().Add("Vary", "User-Agent") if a.maybeServeSubInfo(c) { logSubscriptionRoute(userAgent, "info") return } - if a.maybeServeSubPage(c, subPageFormatRaw) { + if !loon && a.maybeServeSubPage(c, subPageFormatRaw) { logSubscriptionRoute(userAgent, "html") return } format := hwidLinks - if shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) { + if !loon && shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) { format = hwidClash - } else if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) { + } else if !loon && shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) { format = hwidJSONArray } if !a.enforceHwid(c, format) { @@ -528,12 +532,16 @@ func (a *SUBController) subs(c *gin.Context) { logSubscriptionRoute(userAgent, "clash") return } - if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) && a.serveJsonBody(c, true, "application/json; charset=utf-8", false) { + if !loon && shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) && a.serveJsonBody(c, true, "application/json; charset=utf-8", false) { a.recordSubscriptionFetch(c) logSubscriptionRoute(userAgent, "json") return } - logSubscriptionRoute(userAgent, "raw") + if loon { + logSubscriptionRoute(userAgent, "loon") + } else { + logSubscriptionRoute(userAgent, "raw") + } subId := c.Param("subid") scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) subReq := a.subService.ForRequest(host) @@ -546,9 +554,13 @@ func (a *SUBController) subs(c *gin.Context) { writeSubError(c, err) } else { var result strings.Builder - for _, sub := range subs { - result.WriteString(sub) - result.WriteString("\n") + if loon { + result.WriteString(loonSubscription(subs)) + } else { + for _, sub := range subs { + result.WriteString(sub) + result.WriteByte('\n') + } } // Add headers @@ -557,7 +569,7 @@ func (a *SUBController) subs(c *gin.Context) { a.ApplyCommonHeaders(c, header, a.updateInterval, metadata.Title, metadata.SupportURL, metadata.ProfileURL, metadata.Announce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings) // Incy's profile rides the raw body; other clients must not see that line (#6062). - if IsIncyClient(userAgent) && a.subIncyEnableRouting && a.subIncyRoutingRules != "" { + if !loon && IsIncyClient(userAgent) && a.subIncyEnableRouting && a.subIncyRoutingRules != "" { incyRules, _, err := resolveIncyRoutingSource(a.subIncyRoutingRules) if err == nil && strings.TrimSpace(incyRules) != "" { result.WriteString(incyRules) diff --git a/internal/sub/loon.go b/internal/sub/loon.go new file mode 100644 index 000000000..29b229bc7 --- /dev/null +++ b/internal/sub/loon.go @@ -0,0 +1,90 @@ +package sub + +import ( + "fmt" + "net/url" + "strconv" + "strings" + "unicode" + + "github.com/google/uuid" +) + +// loonSubscription keeps existing URI entries and renders eligible REALITY TCP nodes in Loon's native format. +func loonSubscription(links []string) string { + var out strings.Builder + out.WriteString("[Proxy]\n") + usedNames := make(map[string]bool) + for _, linksForClient := range links { + for line := range strings.SplitSeq(linksForClient, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + name, node, ok := loonRealityNode(line) + if ok { + base := name + for suffix := 2; usedNames[name]; suffix++ { + name = base + " (" + strconv.Itoa(suffix) + ")" + } + usedNames[name] = true + line = name + " = " + node + } + out.WriteString(line) + out.WriteByte('\n') + } + } + return out.String() +} + +func loonRealityNode(raw string) (name, node string, ok bool) { + u, err := url.Parse(raw) + if err != nil || u.Scheme != "vless" || u.User == nil { + return "", "", false + } + q := u.Query() + switch q.Get("type") { + case "", "raw", "tcp": + default: + return "", "", false + } + if q.Get("security") != "reality" || q.Get("support-x25519mlkem768") != "true" || + q.Get("pqv") != "" || (q.Get("encryption") != "" && q.Get("encryption") != "none") || + (q.Get("headerType") != "" && q.Get("headerType") != "none") { + return "", "", false + } + host, key, serverName, shortID, flow := u.Hostname(), q.Get("pbk"), q.Get("sni"), q.Get("sid"), q.Get("flow") + port, portErr := strconv.ParseUint(u.Port(), 10, 16) + id, idErr := uuid.Parse(u.User.Username()) + if portErr != nil || port == 0 || idErr != nil || host == "" || key == "" || + (flow != "" && flow != "xtls-rprx-vision" && flow != "xtls-rprx-vision-udp443") { + return "", "", false + } + for _, value := range []string{host, key, serverName, shortID} { + if strings.ContainsAny(value, ",=\"\\[]#") || strings.ContainsFunc(value, func(r rune) bool { + return unicode.IsControl(r) || unicode.IsSpace(r) + }) { + return "", "", false + } + } + name = strings.TrimSpace(strings.Map(func(r rune) rune { + if unicode.IsControl(r) || strings.ContainsRune("=,[]#\"", r) { + return ' ' + } + return r + }, u.Fragment)) + if name == "" { + name = host + } + node = fmt.Sprintf("VLESS,%s,%d,%q,transport=tcp,over-tls=true,public-key=%q,tls-profile=chrome147", host, port, id.String(), key) + if shortID != "" { + node += ",short-id=" + shortID + } + if serverName != "" { + node += ",sni=" + serverName + } + if flow != "" { + node += ",flow=" + flow + } + return name, node, true +} diff --git a/internal/sub/loon_test.go b/internal/sub/loon_test.go new file mode 100644 index 000000000..6e5167491 --- /dev/null +++ b/internal/sub/loon_test.go @@ -0,0 +1,59 @@ +package sub + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestLoonSubscriptionUsesChrome147ForPostQuantumReality(t *testing.T) { + seedSubDB(t) + seedSubInbound(t, "loon-profile", "reality", 8443, 1, `{ + "network":"tcp","security":"reality", + "realitySettings":{"serverNames":["backend.example.test"],"shortIds":["ab12cd"], + "settings":{"publicKey":"TEST-public-key","fingerprint":"chrome"}} + }`) + seedSubInbound(t, "loon-profile", "tls", 9443, 2, `{"network":"tcp","security":"tls"}`) + gin.SetMode(gin.TestMode) + router := newSubscriptionTestRouter(subscriptionTestRouterConfig{clashAutoDetect: true}) + fetch := func(query, client string) string { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "http://sub.example.test/sub/loon-profile"+query, nil) + req.Header.Set("User-Agent", client) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("subscription response status = %d", rec.Code) + } + if rec.Header().Get("Subscription-Userinfo") == "" { + t.Fatal("usage header was lost") + } + body, err := base64.StdEncoding.DecodeString(rec.Body.String()) + if err != nil { + t.Fatalf("decode subscription: %v", err) + } + return string(body) + } + raw := fetch("", "Generic/1.0") + if strings.Contains(raw, "tls-profile=") || !strings.Contains(raw, "fp=chrome") { + t.Fatal("default raw VLESS subscription changed") + } + const loonAgent = "Loon/991 CFNetwork/3896.100.1.1.1 Darwin/27.0.0" + loon := fetch("?format=loon", "Mihomo/1.19") + if auto := fetch("", loonAgent); auto != loon { + t.Fatal("Loon's default subscription URL differs from the explicit Loon format") + } + if explicitRaw := fetch("?format=raw", loonAgent); explicitRaw != raw { + t.Fatal("explicit raw format for Loon does not retain the normal share URIs") + } + if !strings.HasPrefix(loon, "[Proxy]\n") || !strings.Contains(loon, "= VLESS,203.0.113.5,8443,") || + !strings.Contains(loon, `public-key="TEST-public-key"`) || !strings.Contains(loon, "short-id=ab12cd") || + !strings.Contains(loon, "sni=backend.example.test") || !strings.Contains(loon, "tls-profile=chrome147") || + !strings.Contains(loon, "vless://") { + t.Fatalf("Loon subscription lacks the native REALITY node or the unchanged TLS entry: %s", loon) + } +} From bd8648de73d58dc18aad08cf3da97ef4a5ac2acf Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Mon, 30 Nov 2026 01:28:42 +0330 Subject: [PATCH 3/7] perf(wirecodec): bound node envelope compression memory (#7275) The shared zstd encoder for master-to-node request bodies was built with library defaults: one workspace per CPU, each holding a 16 MiB history for the default 8 MiB window. The pool hands its workspaces out in rotation and never frees them, so a 4-vCPU master kept about 70 MiB alive after its first few pushes and a 16-core one about 280 MiB. Build it with a 1 MiB window, at most four workers and zstd's low-memory mode, which retains about 10 MiB whatever the CPU count. Callers queue for a worker on a slot channel, so a cancelled push stops waiting instead of blocking inside EncodeAll. Frames stay standard zstd: capability negotiation, the SHA-256 of the uncompressed body and the node's decode bounds are unchanged. Closes #7274 --- internal/util/wirecodec/wirecodec.go | 29 +++++++- internal/util/wirecodec/wirecodec_test.go | 89 +++++++++++++++++++++++ internal/web/runtime/remote.go | 5 +- 3 files changed, 120 insertions(+), 3 deletions(-) diff --git a/internal/util/wirecodec/wirecodec.go b/internal/util/wirecodec/wirecodec.go index 9f1ef8458..aefe0ef17 100644 --- a/internal/util/wirecodec/wirecodec.go +++ b/internal/util/wirecodec/wirecodec.go @@ -4,6 +4,7 @@ package wirecodec import ( + "context" "crypto/sha256" "encoding/hex" "errors" @@ -39,12 +40,20 @@ const ( // maxDecodeBytes bounds in-memory decompression to defuse a zstd bomb from // an (authenticated) node-API caller. maxDecodeBytes = 16 << 20 + + // Node requests reuse a small history and keep a fixed upper bound on + // retained encoder workspaces, even on a master with many CPUs. + encoderWindow = 1 << 20 + maxEncoderWorkers = 4 ) // EncodeAll/DecodeAll on these shared instances are safe for concurrent use. var ( + encoderWorkers = min(maxEncoderWorkers, runtime.GOMAXPROCS(0)) + encoderSlots = make(chan struct{}, encoderWorkers) + zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithWindowSize(encoderWindow), + zstd.WithEncoderConcurrency(encoderWorkers), zstd.WithLowerEncoderMem(true)) decoderWorkers = runtime.GOMAXPROCS(0) - zstdEncoder, _ = zstd.NewWriter(nil) zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes), zstd.WithDecodeAllCapLimit(true), zstd.WithDecoderConcurrency(decoderWorkers)) // decodeSlots keeps callers waiting for a decoder worker from each holding an output buffer. @@ -54,7 +63,23 @@ var ( // Compress zstd-compresses b. func Compress(b []byte) []byte { - return zstdEncoder.EncodeAll(b, nil) + out, _ := CompressContext(context.Background(), b) + return out +} + +// CompressContext lets a caller cancel while waiting for an encoder. Once +// EncodeAll starts it runs synchronously. +func CompressContext(ctx context.Context, b []byte) ([]byte, error) { + select { + case encoderSlots <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-encoderSlots }() + if err := ctx.Err(); err != nil { + return nil, err + } + return zstdEncoder.EncodeAll(b, nil), nil } // Decompress zstd-decompresses src, rejecting output larger than maxOut (and any diff --git a/internal/util/wirecodec/wirecodec_test.go b/internal/util/wirecodec/wirecodec_test.go index 08ad22b30..bb01f9b10 100644 --- a/internal/util/wirecodec/wirecodec_test.go +++ b/internal/util/wirecodec/wirecodec_test.go @@ -2,9 +2,16 @@ package wirecodec import ( "bytes" + "context" + "errors" + "fmt" "runtime" "strings" + "sync" "testing" + "time" + + "github.com/klauspost/compress/zstd" ) func TestCompressRoundTrip(t *testing.T) { @@ -64,3 +71,85 @@ func TestDecompressOfManyFramesAllocatesTheOutputOnce(t *testing.T) { t.Fatalf("decoding %d bytes of frames allocated %d MiB", len(src), allocated>>20) } } + +func TestCompressBoundsFrameWindow(t *testing.T) { + orig := bytes.Repeat([]byte("synthetic node configuration"), 150_000) + packed := Compress(orig) + var header zstd.Header + if err := header.Decode(packed); err != nil { + t.Fatal(err) + } + window := header.WindowSize + if header.SingleSegment { + window = header.FrameContentSize + } + if window > 1<<20 { + t.Fatalf("zstd frame needs %d bytes of window, want at most 1 MiB", window) + } +} + +func TestCompressConcurrentFramesAreCompatible(t *testing.T) { + decoder, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + defer decoder.Close() + var callers sync.WaitGroup + for i := range 16 { + callers.Go(func() { + raw := bytes.Repeat([]byte(fmt.Sprintf("client-%d", i)), 40_000) + packed, err := CompressContext(t.Context(), raw) + if err != nil { + t.Errorf("encode %d: %v", i, err) + return + } + got, err := decoder.DecodeAll(packed, nil) + if err != nil || !bytes.Equal(got, raw) { + t.Errorf("decode frame %d with the default decoder: %v", i, err) + } + }) + } + callers.Wait() + + encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + defer encoder.Close() + raw := bytes.Repeat([]byte("legacy envelope"), 300_000) + decoded, err := Decompress(encoder.EncodeAll(raw, nil), len(raw)) + if err != nil || !bytes.Equal(decoded, raw) { + t.Fatalf("decode frame with the legacy default window: %v", err) + } +} + +func TestCompressCancelsWhileWaitingForAnEncoder(t *testing.T) { + for range cap(encoderSlots) { + encoderSlots <- struct{}{} + } + defer func() { + for range cap(encoderSlots) { + <-encoderSlots + } + }() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + called := make(chan struct{}) + result := make(chan error, 1) + go func() { + close(called) + _, err := CompressContext(ctx, []byte("waiting for a slot")) + result <- err + }() + <-called + cancel() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Fatalf("compression returned %v, want context.Canceled", err) + } + case <-time.After(time.Second): + t.Fatal("compression waited for a slot after cancellation") + } +} diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index ada3d9d75..df8e2d721 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -354,7 +354,10 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo if bodyBytes != nil { hashHex = wirecodec.Sha256Hex(bodyBytes) if len(bodyBytes) >= zstdMinBodyBytes && r.nodeSupportsZstd() { - bodyBytes = wirecodec.Compress(bodyBytes) + bodyBytes, err = wirecodec.CompressContext(ctx, bodyBytes) + if err != nil { + return nil, err + } zstdEncoded = true } reqBody = bytes.NewReader(bodyBytes) From 267379456ae3bcedbd148d4b158cb72b792ddfc2 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Mon, 30 Nov 2026 23:17:21 +0330 Subject: [PATCH 4/7] chore(wirecodec): pin the node encoder's retained-memory budget Two of the three options that bound the encoder had no test. With the worker cap removed, or zstd's low-memory mode dropped, every test stayed green while an encoder built for 64 CPUs retained 154 MiB or 13.7 MiB instead of 9.1 MiB. Only the 1 MiB window was pinned, through the frame header. Build the encoder in newEncoder(cpus) so a test can size it for a many-core host whatever machine runs it, warm every pooled workspace and fail above 12 MiB. --- internal/util/wirecodec/wirecodec.go | 19 ++++++++++++------ internal/util/wirecodec/wirecodec_test.go | 24 ++++++++++++++++++++++- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/internal/util/wirecodec/wirecodec.go b/internal/util/wirecodec/wirecodec.go index aefe0ef17..5d7df1d70 100644 --- a/internal/util/wirecodec/wirecodec.go +++ b/internal/util/wirecodec/wirecodec.go @@ -49,18 +49,25 @@ const ( // EncodeAll/DecodeAll on these shared instances are safe for concurrent use. var ( - encoderWorkers = min(maxEncoderWorkers, runtime.GOMAXPROCS(0)) - encoderSlots = make(chan struct{}, encoderWorkers) - zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithWindowSize(encoderWindow), - zstd.WithEncoderConcurrency(encoderWorkers), zstd.WithLowerEncoderMem(true)) - decoderWorkers = runtime.GOMAXPROCS(0) - zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes), + zstdEncoder, encoderWorkers = newEncoder(runtime.GOMAXPROCS(0)) + encoderSlots = make(chan struct{}, encoderWorkers) + decoderWorkers = runtime.GOMAXPROCS(0) + zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes), zstd.WithDecodeAllCapLimit(true), zstd.WithDecoderConcurrency(decoderWorkers)) // decodeSlots keeps callers waiting for a decoder worker from each holding an output buffer. decodeSlots = make(chan struct{}, decoderWorkers) errDecodedTooLarge = errors.New("wirecodec: decompressed body exceeds limit") ) +// newEncoder builds the envelope encoder for a host with cpus CPUs and reports +// how many workspaces it pools; they are never freed, hence the cap (#7274). +func newEncoder(cpus int) (*zstd.Encoder, int) { + workers := min(maxEncoderWorkers, cpus) + enc, _ := zstd.NewWriter(nil, zstd.WithWindowSize(encoderWindow), + zstd.WithEncoderConcurrency(workers), zstd.WithLowerEncoderMem(true)) + return enc, workers +} + // Compress zstd-compresses b. func Compress(b []byte) []byte { out, _ := CompressContext(context.Background(), b) diff --git a/internal/util/wirecodec/wirecodec_test.go b/internal/util/wirecodec/wirecodec_test.go index bb01f9b10..a34f0fd3f 100644 --- a/internal/util/wirecodec/wirecodec_test.go +++ b/internal/util/wirecodec/wirecodec_test.go @@ -72,6 +72,28 @@ func TestDecompressOfManyFramesAllocatesTheOutputOnce(t *testing.T) { } } +// The encoder keeps every workspace it has used for the life of the process, so +// their total must not grow with the master's CPU count (#7274). +func TestEncoderWorkspacesStayWithinBudgetOnAManyCoreHost(t *testing.T) { + const cpus, budget = 64, 12 << 20 + payload := bytes.Repeat([]byte("synthetic client traffic row "), 20_000) + enc, _ := newEncoder(cpus) + defer enc.Close() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + // EncodeAll hands the workspaces out in rotation, so sequential calls warm each one. + for range 2 * cpus { + enc.EncodeAll(payload, nil) + } + runtime.GC() + runtime.ReadMemStats(&after) + if retained := int64(after.HeapAlloc) - int64(before.HeapAlloc); retained > budget { + t.Fatalf("encoder for %d CPUs retains %.1f MiB after use, want at most %d MiB", + cpus, float64(retained)/(1<<20), budget>>20) + } +} + func TestCompressBoundsFrameWindow(t *testing.T) { orig := bytes.Repeat([]byte("synthetic node configuration"), 150_000) packed := Compress(orig) @@ -97,7 +119,7 @@ func TestCompressConcurrentFramesAreCompatible(t *testing.T) { var callers sync.WaitGroup for i := range 16 { callers.Go(func() { - raw := bytes.Repeat([]byte(fmt.Sprintf("client-%d", i)), 40_000) + raw := bytes.Repeat(fmt.Appendf(nil, "client-%d", i), 40_000) packed, err := CompressContext(t.Context(), raw) if err != nil { t.Errorf("encode %d: %v", i, err) From b2d7a9bb08d04d158a6d6bbe5e2dafd88f23fe85 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 11:40:21 +0330 Subject: [PATCH 5/7] fix(panel): break Xray restart deadlock and bound panel reload (#7346) Fix the production-confirmed ABBA lock inversion introduced in v3.12.0: Xray restart held the lifecycle mutex while synchronously waiting for the serialized traffic writer, which needed the same mutex to amend the committed live configuration snapshot. This blocked API writes and node synchronization, and made panel reload wait indefinitely for cron shutdown. Run traffic maintenance before acquiring the Xray lifecycle mutex, keep config generation free of writer submissions, and retain the live-snapshot generation guard. Bound panel-only reload with one 75-second deadline across shutdown and startup; fence replacement workers until the old generation drains, and exit nonzero for supervised recovery on failure. Preserve Xray on healthy reloads, gracefully handle termination signals, log phase timings and bounded function-only stack diagnostics, and distinguish accepted restart requests from successful completion. Validation: all 13 GitHub checks passed on the reviewed head, including Go tests, race, PostgreSQL durable-first/migration, node and Xray E2E, frontend, lint, codegen, vulnerability check and docs. PR validation reports isolated SQLite/PostgreSQL 18 reload tests with 15,844 clients and 30,270 memberships, stable real Xray PIDs, and legacy/current node interoperability. Addresses the primary deadlock and bounded panel reload; writer cancellation and per-source listener admission diagnostics remain follow-ups. Supervised failure recovery may interrupt Xray sessions. Fixes #7345 --- docs/content/docs/en/help/troubleshooting.mdx | 12 ++ internal/nodee2e/harness_test.go | 28 ++++- internal/sub/sub.go | 15 ++- internal/web/controller/setting.go | 2 +- internal/web/global/global.go | 9 ++ internal/web/service/xray.go | 9 +- .../web/service/xray_restart_writer_test.go | 83 +++++++++++++ internal/web/translation/ar-EG.json | 2 +- internal/web/translation/en-US.json | 2 +- internal/web/translation/es-ES.json | 2 +- internal/web/translation/fa-IR.json | 2 +- internal/web/translation/id-ID.json | 2 +- internal/web/translation/ja-JP.json | 2 +- internal/web/translation/pt-BR.json | 2 +- internal/web/translation/ru-RU.json | 2 +- internal/web/translation/sk-SK.json | 2 +- internal/web/translation/tr-TR.json | 2 +- internal/web/translation/uk-UA.json | 2 +- internal/web/translation/vi-VN.json | 2 +- internal/web/translation/zh-CN.json | 2 +- internal/web/translation/zh-TW.json | 2 +- internal/web/web.go | 39 ++++-- internal/web/web_shutdown_test.go | 43 ++++++- main.go | 83 +++++++------ panel_restart.go | 114 ++++++++++++++++++ panel_restart_test.go | 86 +++++++++++++ 26 files changed, 475 insertions(+), 76 deletions(-) create mode 100644 internal/web/service/xray_restart_writer_test.go create mode 100644 panel_restart.go create mode 100644 panel_restart_test.go diff --git a/docs/content/docs/en/help/troubleshooting.mdx b/docs/content/docs/en/help/troubleshooting.mdx index d9b72d373..014247621 100644 --- a/docs/content/docs/en/help/troubleshooting.mdx +++ b/docs/content/docs/en/help/troubleshooting.mdx @@ -13,6 +13,18 @@ A checklist for the most common issues. When in doubt, raise the log level - Make sure the **panel port isn't already in use** by another service. - Verify the database path is writable (default `/etc/x-ui/x-ui.db`). +## Panel restart takes too long + +The restart action acknowledges that a request was accepted. The service logs +successful completion once the panel and subscription listeners have both started. +A normal panel restart keeps the running Xray process. Each restart has a +75-second budget shared by both listener drains and the other shutdown and startup phases. + +If a phase fails or overruns that budget, the panel exits with an error so its +supervisor can restart it. This recovery can interrupt Xray sessions. On a +systemd installation, inspect `journalctl -u x-ui` for the phase and elapsed +time. Use a supervisor configured to restart the service after failures. + ## 502 / panel unreachable behind a proxy - Confirm the panel is actually listening on the upstream port (e.g. `2053`). diff --git a/internal/nodee2e/harness_test.go b/internal/nodee2e/harness_test.go index 8b9101efa..09c65a619 100644 --- a/internal/nodee2e/harness_test.go +++ b/internal/nodee2e/harness_test.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -49,14 +50,31 @@ type panel struct { logOut *os.File } +// The fixture processes bind after their databases have been prepared. Keep +// each assignment unique for the run and below the default ephemeral range on +// CI, where outbound HTTP connections could otherwise take the same port. +var fixturePortOffset atomic.Uint32 + func freePort(t *testing.T) int { t.Helper() - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("free port: %v", err) + var lastErr error + for range 64 { + port := 19999 + int(fixturePortOffset.Add(1)) + if port > 29999 { + t.Fatal("exhausted node fixture ports") + } + listener, err := net.Listen("tcp", ":"+strconv.Itoa(port)) + if err != nil { + lastErr = err + continue + } + if err := listener.Close(); err != nil { + t.Fatalf("release fixture port %d: %v", port, err) + } + return port } - defer l.Close() - return l.Addr().(*net.TCPAddr).Port + t.Fatalf("no available node fixture port: %v", lastErr) + return 0 } func (p *panel) env() []string { diff --git a/internal/sub/sub.go b/internal/sub/sub.go index 64821c886..a2d1f4066 100644 --- a/internal/sub/sub.go +++ b/internal/sub/sub.go @@ -5,6 +5,7 @@ package sub import ( "context" "crypto/tls" + "errors" "io" "io/fs" "net" @@ -485,6 +486,13 @@ func (s *Server) Start() (err error) { // Stop gracefully shuts down the subscription server and closes the listener. func (s *Server) Stop() error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.StopWithContext(ctx) +} + +// StopWithContext drains subscription HTTP connections within the caller's deadline. +func (s *Server) StopWithContext(ctx context.Context) error { s.cancel() if s.sub != nil { s.sub.Close() @@ -493,12 +501,13 @@ func (s *Server) Stop() error { var err1 error var err2 error if s.httpServer != nil { - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) - defer shutdownCancel() - err1 = s.httpServer.Shutdown(shutdownCtx) + err1 = s.httpServer.Shutdown(ctx) } if s.listener != nil { err2 = s.listener.Close() + if errors.Is(err2, net.ErrClosed) { + err2 = nil + } } return common.Combine(err1, err2) } diff --git a/internal/web/controller/setting.go b/internal/web/controller/setting.go index ca5c25fad..977c86401 100644 --- a/internal/web/controller/setting.go +++ b/internal/web/controller/setting.go @@ -241,7 +241,7 @@ func (a *SettingController) restartPanel(c *gin.Context) { } answer.NextPort, _ = a.settingService.GetListenPort() err := a.panelService.RestartPanel(time.Second * 3) - jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), answer, err) + jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelAccepted"), answer, err) } // getDefaultXrayConfig retrieves the default Xray configuration. diff --git a/internal/web/global/global.go b/internal/web/global/global.go index 89bd52c1a..d8b229f75 100644 --- a/internal/web/global/global.go +++ b/internal/web/global/global.go @@ -10,6 +10,7 @@ import ( ) var ( + serverMu sync.RWMutex webServer WebServer subServer SubServer @@ -31,21 +32,29 @@ type SubServer interface { // SetWebServer sets the global web server instance. func SetWebServer(s WebServer) { + serverMu.Lock() + defer serverMu.Unlock() webServer = s } // GetWebServer returns the global web server instance. func GetWebServer() WebServer { + serverMu.RLock() + defer serverMu.RUnlock() return webServer } // SetSubServer sets the global subscription server instance. func SetSubServer(s SubServer) { + serverMu.Lock() + defer serverMu.Unlock() subServer = s } // GetSubServer returns the global subscription server instance. func GetSubServer() SubServer { + serverMu.RLock() + defer serverMu.RUnlock() return subServer } diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index ed1a6f5d4..3f9c5306e 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -202,8 +202,6 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) { xrayConfig.OutboundConfigs = forceUserspaceWireGuardTun(xrayConfig.OutboundConfigs) } - _, _, _ = s.inboundService.AddTraffic(nil, nil) - inbounds, err := s.inboundService.GetAllInbounds() if err != nil { return nil, err @@ -1555,6 +1553,13 @@ func (s *XrayService) RestartXrayFrom(isForce bool, origin XrayOrigin) error { // dropSessions replaces a running core whatever its config says: only a new process // ends the sessions of clients the API has already removed. func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin, dropSessions bool) error { + if !isForce && isManuallyStopped.Load() { + return nil + } + // Committed traffic maintenance can take the Xray lock to update the live snapshot. + if _, _, err := s.inboundService.AddTraffic(nil, nil); err != nil { + logger.Warning("traffic maintenance before Xray restart failed:", err) + } lock.Lock() defer lock.Unlock() logger.Debug("restart Xray, force:", isForce) diff --git a/internal/web/service/xray_restart_writer_test.go b/internal/web/service/xray_restart_writer_test.go new file mode 100644 index 000000000..d84df7d58 --- /dev/null +++ b/internal/web/service/xray_restart_writer_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + + "gorm.io/gorm" +) + +func TestPendingXrayRestartDoesNotHoldLifecycleLockWhileWaitingForWriter(t *testing.T) { + db := initTrafficTestDB(t) + stopped := isManuallyStopped.Swap(false) + pending := pendingXrayRestart.Swap(nil) + reconcile := isNeedXrayReconcile.Swap(false) + depletion := pendingXraySessionDrop.Swap(false) + t.Cleanup(func() { + isManuallyStopped.Store(stopped) + pendingXrayRestart.Store(pending) + isNeedXrayReconcile.Store(reconcile) + pendingXraySessionDrop.Store(depletion) + }) + var configRead atomic.Bool + const hook = "test:reject-restart-config-before-starting-core" + if err := db.Callback().Query().Before("gorm:query").Register(hook, func(tx *gorm.DB) { + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && tx.Statement.ConnPool == db.Statement.ConnPool { + configRead.Store(true) + _ = tx.AddError(errors.New("injected config read failure")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + + StartTrafficWriter() + t.Cleanup(StopTrafficWriter) + parked, release, writerDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + var lifecycleAvailable bool + go func() { + defer close(writerDone) + _ = submitTrafficWriteBackground(func() error { + close(parked) + <-release + lifecycleAvailable = lock.TryLock() + if lifecycleAvailable { + lock.Unlock() + } + return nil + }) + }() + t.Cleanup(func() { unblock(); <-writerDone }) + select { + case <-parked: + case <-time.After(3 * time.Second): + t.Fatal("traffic writer did not start") + } + + svc := &XrayService{} + svc.SetToNeedRestartFrom(XrayOriginConfigChange) + restartDone := make(chan struct{}) + go func() { defer close(restartDone); svc.ApplyPendingRestart() }() + t.Cleanup(func() { unblock(); <-restartDone }) + for deadline := time.Now().Add(3 * time.Second); trafficWriterQueueLen() == 0; time.Sleep(time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("pending restart never queued lifecycle maintenance") + } + } + unblock() + <-writerDone + <-restartDone + if !lifecycleAvailable { + t.Fatal("restart held the Xray lifecycle lock while waiting for the traffic writer") + } + if !configRead.Load() || pendingXrayRestart.Load() == nil { + t.Fatal("restart skipped config construction or failed to re-arm the request") + } +} diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 7238b0965..f8766bf36 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1339,7 +1339,7 @@ "infoDesc": "كل تغيير هتعمله هنا لازم يتخزن. ياريت تعيد تشغيل البانل عشان التعديلات تتفعل.", "restartPanel": "إعادة تشغيل اللوحة", "restartPanelDesc": "متأكد إنك عايز تعيد تشغيل البانل؟ لو ماقدرتش تدخل بعد إعادة التشغيل، شوف سجل البانل على السيرفر.", - "restartPanelSuccess": "تم إعادة تشغيل اللوحة بنجاح", + "restartPanelAccepted": "تم قبول طلب إعادة تشغيل اللوحة.", "actions": "إجراءات", "resetDefaultConfig": "استرجاع الافتراضي", "panelSettings": "عام", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 5df5f1e61..24af28443 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1460,7 +1460,7 @@ "infoDesc": "Every change made here needs to be saved. Please restart the panel to apply changes.", "restartPanel": "Restart Panel", "restartPanelDesc": "Are you sure you want to restart the panel? If you cannot access the panel after restarting, please view the panel log info on the server.", - "restartPanelSuccess": "The panel was successfully restarted.", + "restartPanelAccepted": "Panel restart request accepted.", "actions": "Actions", "resetDefaultConfig": "Reset to Default", "panelSettings": "General", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index df05bd18f..42429f419 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1339,7 +1339,7 @@ "infoDesc": "Cada cambio realizado aquí debe ser guardado. Por favor, reinicie el panel para aplicar los cambios.", "restartPanel": "Reiniciar panel", "restartPanelDesc": "¿Está seguro de que desea reiniciar el panel? Haga clic en Aceptar para reiniciar después de 3 segundos. Si no puede acceder al panel después de reiniciar, por favor, consulte la información de registro del panel en el servidor.", - "restartPanelSuccess": "El panel se reinició correctamente", + "restartPanelAccepted": "Se aceptó la solicitud de reinicio del panel.", "actions": "Acciones", "resetDefaultConfig": "Restablecer a Configuración Predeterminada", "panelSettings": "Configuraciones del Panel", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index b89862162..5f8bf7016 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1339,7 +1339,7 @@ "infoDesc": "برای اعمال تغییرات در این بخش باید پس از ذخیره کردن، پنل را ریستارت کنید", "restartPanel": "راه‌اندازی مجدد پنل", "restartPanelDesc": "آیا مطمئن به ریستارت پنل هستید؟ اگر پس‌از ریستارت نمی‌توانید به پنل دسترسی پیدا کنید، لطفاً گزارش‌های موجود در اسکریپت پنل را بررسی کنید", - "restartPanelSuccess": "پنل با موفقیت راه‌اندازی مجدد شد", + "restartPanelAccepted": "درخواست راه‌اندازی مجدد پنل پذیرفته شد.", "actions": "عملیات ها", "resetDefaultConfig": "برگشت به پیش‌فرض", "panelSettings": "پیکربندی", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 77df99297..209bdc64e 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1339,7 +1339,7 @@ "infoDesc": "Setiap perubahan yang dibuat di sini perlu disimpan. Harap restart panel untuk menerapkan perubahan.", "restartPanel": "Mulai ulang panel", "restartPanelDesc": "Apakah Anda yakin ingin merestart panel? Jika Anda tidak dapat mengakses panel setelah merestart, lihat info log panel di server.", - "restartPanelSuccess": "Panel berhasil dimulai ulang", + "restartPanelAccepted": "Permintaan untuk memulai ulang panel telah diterima.", "actions": "Tindakan", "resetDefaultConfig": "Reset ke Default", "panelSettings": "Umum", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 34cdd4de0..58837eb0a 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1339,7 +1339,7 @@ "infoDesc": "ここでのすべての変更は、保存してパネルを再起動する必要があります", "restartPanel": "パネルを再起動", "restartPanelDesc": "パネルを再起動してもよろしいですか?再起動後にパネルにアクセスできない場合は、サーバーでパネルログを確認してください", - "restartPanelSuccess": "パネルの再起動に成功しました", + "restartPanelAccepted": "パネルの再起動リクエストを受け付けました。", "actions": "操作", "resetDefaultConfig": "デフォルト設定にリセット", "panelSettings": "一般", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 781f6cdb6..f5454593c 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1339,7 +1339,7 @@ "infoDesc": "Toda alteração feita aqui precisa ser salva. Reinicie o painel para aplicar as alterações.", "restartPanel": "Reiniciar painel", "restartPanelDesc": "Tem certeza de que deseja reiniciar o painel? Se não conseguir acessar o painel após reiniciar, consulte os logs do painel no servidor.", - "restartPanelSuccess": "O painel foi reiniciado com sucesso", + "restartPanelAccepted": "A solicitação de reinicialização do painel foi aceita.", "actions": "Ações", "resetDefaultConfig": "Redefinir para Padrão", "panelSettings": "Geral", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 5b5065d8f..3e336f3fe 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1339,7 +1339,7 @@ "infoDesc": "Сохраните изменения и перезапустите панель для их применения.", "restartPanel": "Перезапустить панель", "restartPanelDesc": "Вы уверены, что хотите перезапустить панель? Подтвердите, и перезапуск произойдёт через 3 секунды. Если панель будет недоступна, проверьте лог сервера", - "restartPanelSuccess": "Панель успешно перезапущена", + "restartPanelAccepted": "Запрос на перезапуск панели принят.", "actions": "Действия", "resetDefaultConfig": "Восстановить настройки по умолчанию", "panelSettings": "Панель", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 175906240..d564f6aad 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1460,7 +1460,7 @@ "infoDesc": "Každú zmenu najprv uložte. Na jej použitie reštartujte panel.", "restartPanel": "Reštartovať panel", "restartPanelDesc": "Naozaj chcete reštartovať panel? Ak sa po reštarte nedá otvoriť, skontrolujte záznamy panelu na serveri.", - "restartPanelSuccess": "Panel bol úspešne reštartovaný.", + "restartPanelAccepted": "Požiadavka na reštart panela bola prijatá.", "actions": "Akcie", "resetDefaultConfig": "Obnoviť predvolené nastavenia", "panelSettings": "Všeobecné", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index fbab4b889..6baa7a495 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1339,7 +1339,7 @@ "infoDesc": "Burada yapılan her değişikliğin kaydedilmesi gerekir. Değişikliklerin uygulanması için paneli yeniden başlatın.", "restartPanel": "Paneli Yeniden Başlat", "restartPanelDesc": "Paneli yeniden başlatmak istediğinizden emin misiniz? Yeniden başlattıktan sonra panele erişemezseniz, sunucudaki panel loglarını kontrol edin.", - "restartPanelSuccess": "Panel başarıyla yeniden başlatıldı.", + "restartPanelAccepted": "Paneli yeniden başlatma isteği kabul edildi.", "actions": "İşlemler", "resetDefaultConfig": "Varsayılana Sıfırla", "panelSettings": "Genel", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index fb302d746..defd6b693 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1339,7 +1339,7 @@ "infoDesc": "Кожна внесена тут зміна повинна бути збережена. Перезапустіть панель, щоб застосувати зміни.", "restartPanel": "Перезапустити панель", "restartPanelDesc": "Ви впевнені, що бажаєте перезапустити панель? Якщо ви не можете отримати доступ до панелі після перезапуску, будь ласка, перегляньте інформацію журналу панелі на сервері.", - "restartPanelSuccess": "Панель успішно перезапущено", + "restartPanelAccepted": "Запит на перезапуск панелі прийнято.", "actions": "Дії", "resetDefaultConfig": "Відновити значення за замовчуванням", "panelSettings": "Загальні", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 52570f998..9ac29d089 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1339,7 +1339,7 @@ "infoDesc": "Mọi thay đổi được thực hiện ở đây cần phải được lưu. Vui lòng khởi động lại bảng điều khiển để áp dụng các thay đổi.", "restartPanel": "Khởi động lại bảng điều khiển", "restartPanelDesc": "Bạn có chắc chắn muốn khởi động lại bảng điều khiển? Nhấn OK để khởi động lại sau 3 giây. Nếu bạn không thể truy cập bảng điều khiển sau khi khởi động lại, vui lòng xem thông tin nhật ký của bảng điều khiển trên máy chủ.", - "restartPanelSuccess": "Đã khởi động lại bảng điều khiển thành công", + "restartPanelAccepted": "Yêu cầu khởi động lại bảng điều khiển đã được chấp nhận.", "actions": "Hành động", "resetDefaultConfig": "Đặt lại cấu hình mặc định", "panelSettings": "Bảng điều khiển", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index d10a4f91b..fbfd10cd6 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1339,7 +1339,7 @@ "infoDesc": "此处的所有更改都需要保存并重启面板才能生效", "restartPanel": "重启面板", "restartPanelDesc": "确定要重启面板吗?若重启后无法访问面板,请前往服务器查看面板日志信息", - "restartPanelSuccess": "面板已成功重启", + "restartPanelAccepted": "已接受面板重启请求。", "actions": "操作", "resetDefaultConfig": "重置为默认配置", "panelSettings": "常规", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index a736e06b7..a1d96b556 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1339,7 +1339,7 @@ "infoDesc": "此處的所有更改都需要儲存並重啟面板才能生效", "restartPanel": "重新啟動面板", "restartPanelDesc": "確定要重啟面板嗎?若重啟後無法訪問面板,請前往伺服器檢視面板日誌資訊", - "restartPanelSuccess": "面板已成功重新啟動", + "restartPanelAccepted": "已接受面板重新啟動請求。", "actions": "操作", "resetDefaultConfig": "重置為預設配置", "panelSettings": "常規", diff --git a/internal/web/web.go b/internal/web/web.go index 65a49d319..f00823791 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -789,24 +789,32 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) { // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot. func (s *Server) Stop() error { - return s.stop(true, true) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.stop(ctx, true, true) } -func (s *Server) StopPanelOnly() error { - return s.stop(false, true) +func (s *Server) StopPanelOnly(ctx context.Context) error { + return s.stop(ctx, false, true) } -func (s *Server) stop(stopXray bool, stopTgBot bool) error { +func (s *Server) stop(ctx context.Context, stopXray bool, stopTgBot bool) error { s.cancel() var err1 error var err2 error if s.httpServer != nil { - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) - err1 = s.httpServer.Shutdown(shutdownCtx) - shutdownCancel() + err1 = runPanelStopPhase("http drain", func() error { + return s.httpServer.Shutdown(ctx) + }) + if err1 != nil && !stopXray { + return fmt.Errorf("drain old panel HTTP requests: %w", err1) + } } if s.cron != nil { - <-s.cron.Stop().Done() + _ = runPanelStopPhase("cron drain", func() error { + <-s.cron.Stop().Done() + return nil + }) } if stopXray { tuic.GetManager().StopAll() @@ -830,9 +838,12 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { s.tgbotService.Stop() } if s.bus != nil { - s.bus.Stop() + _ = runPanelStopPhase("event subscribers", func() error { + s.bus.Stop() + return nil + }) } - if err := service.PersistSystemMetrics(); err != nil { + if err := runPanelStopPhase("system metrics", service.PersistSystemMetrics); err != nil { logger.Warning("persist system metrics on shutdown failed:", err) } if stopXray { @@ -854,6 +865,14 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { return common.Combine(err1, err2) } +func runPanelStopPhase(name string, run func() error) error { + started := time.Now() + logger.Infof("panel stop phase=%s state=started", name) + err := run() + logger.Infof("panel stop phase=%s state=finished duration=%s error=%v", name, time.Since(started), err) + return err +} + // GetCtx returns the server's context for cancellation and deadline management. func (s *Server) GetCtx() context.Context { return s.ctx diff --git a/internal/web/web_shutdown_test.go b/internal/web/web_shutdown_test.go index 599c1cd77..0d5c9c24b 100644 --- a/internal/web/web_shutdown_test.go +++ b/internal/web/web_shutdown_test.go @@ -2,6 +2,7 @@ package web import ( "context" + "errors" "net" "net/http" "testing" @@ -32,7 +33,47 @@ func TestServerStopPanelOnlyWithPreclosedListenerSucceeds(t *testing.T) { defer cancel() _ = s.httpServer.Shutdown(shutdownCtx) - if err := s.StopPanelOnly(); err != nil { + if err := s.StopPanelOnly(context.Background()); err != nil { t.Fatalf("expected nil error when listener is already closed, got: %v", err) } } + +func TestServerStopPanelOnlyHonorsCallerDeadline(t *testing.T) { + t.Setenv("XUI_DB_FOLDER", t.TempDir()) + s := NewServer(nil) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s.listener = ln + entered, release := make(chan struct{}), make(chan struct{}) + s.httpServer = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + <-release + w.WriteHeader(http.StatusNoContent) + })} + t.Cleanup(func() { + close(release) + _ = s.httpServer.Close() + }) + go func() { _ = s.httpServer.Serve(ln) }() + requestDone := make(chan error, 1) + go func() { + client := &http.Client{Timeout: 3 * time.Second} + res, err := client.Get("http://" + ln.Addr().String()) + if err == nil { + _ = res.Body.Close() + } + requestDone <- err + }() + select { + case <-entered: + case err := <-requestDone: + t.Fatalf("handler did not start: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if err := s.StopPanelOnly(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("active HTTP drain ignored its caller deadline: %v", err) + } +} diff --git a/main.go b/main.go index 70bbfd739..0f53f15cf 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ package main import ( "context" _ "embed" + "errors" "flag" "fmt" "log" @@ -161,7 +162,7 @@ func runWebServer() { monitor, err := tunnelmonitor.New(monitorCfg, func(_ context.Context) error { logger.Warning("Tunnel health monitor threshold reached, restarting xray-core") - return server.RestartXray(service.XrayOriginTunnelHealth) + return (&service.XrayService{}).RestartXrayFrom(true, service.XrayOriginTunnelHealth) }) if err != nil { logger.Warning("Tunnel health monitor disabled: ", err) @@ -169,38 +170,42 @@ func runWebServer() { go monitor.Run(monitorCtx) } } - for { - sig := <-sigCh - - switch sig { + for shutdown := false; !shutdown; { + switch <-sigCh { case syscall.SIGHUP: logger.Info("Received SIGHUP signal. Restarting servers...") - err := server.StopPanelOnly() + var nextWeb *web.Server + var nextSub *sub.Server + pending, err := runPanelRestart(sigCh, panelRestartTimeout, + panelRestartPhase{"panel shutdown", server.StopPanelOnly}, + panelRestartPhase{"subscription shutdown", subServer.StopWithContext}, + panelRestartPhase{"panel startup", func(context.Context) error { + nextWeb = web.NewServer(sub.NewLinkProvider()) + global.SetWebServer(nextWeb) + return nextWeb.StartPanelOnly() + }}, + panelRestartPhase{"subscription startup", func(context.Context) error { + nextSub = sub.NewServer() + global.SetSubServer(nextSub) + return nextSub.Start() + }}, + ) if err != nil { - logger.Debug("Error stopping web server:", err) - } - err = subServer.Stop() - if err != nil { - logger.Debug("Error stopping sub server:", err) - } - - server = web.NewServer(sub.NewLinkProvider()) - global.SetWebServer(server) - err = server.StartPanelOnly() - if err != nil { - log.Fatalf("Error restarting web server: %v", err) + if errors.Is(err, context.DeadlineExceeded) { + logPanelRestartStacks() + } + log.Fatalf("Panel restart failed, exiting for supervisor recovery: %v", err) } + server, subServer = nextWeb, nextSub log.Println("Web server restarted successfully.") - - sub.SetDistFS(web.EmbeddedDist()) - subServer = sub.NewServer() - global.SetSubServer(subServer) - err = subServer.Start() - if err != nil { - log.Fatalf("Error restarting sub server: %v", err) - } log.Println("Sub server restarted successfully.") + shutdown = pending.shutdown + if pending.restartXray && !shutdown { + if err := server.RestartXray(service.XrayOriginSignal); err != nil { + logger.Error("Failed to restart xray-core:", err) + } + } case sys.SIGUSR1: logger.Info("Received USR1 signal, restarting xray-core...") err := server.RestartXray(service.XrayOriginSignal) @@ -209,22 +214,20 @@ func runWebServer() { } default: - if stopTunnelHealthMonitor != nil { - stopTunnelHealthMonitor() - } - - // --- FIX FOR TELEGRAM BOT CONFLICT (409) on full shutdown --- - tgbot.StopBot() - // ------------------------------------------------------------ - - if err := server.Stop(); err != nil { - logger.Error("Server shutdown failed:", err) - } - _ = subServer.Stop() - log.Println("Shutting down servers.") - return + shutdown = true } } + + if stopTunnelHealthMonitor != nil { + stopTunnelHealthMonitor() + } + // Stop polling before process exit to avoid Telegram 409 conflicts. + tgbot.StopBot() + if err := server.Stop(); err != nil { + logger.Error("Server shutdown failed:", err) + } + _ = subServer.Stop() + log.Println("Shutting down servers.") } // resetSetting resets all panel settings to their default values. diff --git a/panel_restart.go b/panel_restart.go new file mode 100644 index 000000000..8db21a60a --- /dev/null +++ b/panel_restart.go @@ -0,0 +1,114 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "runtime" + "strings" + "sync/atomic" + "syscall" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/util/sys" +) + +// Each listener can take up to 30 seconds to drain ordinary HTTP traffic. +const panelRestartTimeout = 75 * time.Second + +type panelRestartPhase struct { + name string + run func(context.Context) error +} + +type panelRestartSignals struct { + shutdown bool + restartXray bool +} + +func runPanelRestart(signals <-chan os.Signal, budget time.Duration, phases ...panelRestartPhase) (panelRestartSignals, error) { + ctx, cancel := context.WithTimeout(context.Background(), budget) + defer cancel() + var phase atomic.Pointer[panelRestartPhase] + result := make(chan error, 1) + go func() { + for i := range phases { + if err := ctx.Err(); err != nil { + result <- err + return + } + step := &phases[i] + phase.Store(step) + started := time.Now() + log.Printf("panel restart phase=%s state=started", step.name) + err := step.run(ctx) + log.Printf("panel restart phase=%s state=finished duration=%s error=%v", step.name, time.Since(started), err) + if err != nil { + result <- fmt.Errorf("%s: %w", step.name, err) + return + } + } + result <- ctx.Err() + }() + + var pending panelRestartSignals + phaseName := func() string { + if current := phase.Load(); current != nil { + return current.name + } + return "dispatch" + } + for { + select { + case err := <-result: + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) + } + return pending, err + case <-ctx.Done(): + return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) + case sig, ok := <-signals: + if !ok { + signals = nil + continue + } + switch sig { + case syscall.SIGHUP: + continue + case sys.SIGUSR1: + pending.restartXray = true + default: + // Let the current restart finish within its existing deadline, + // then let the signal loop stop the new generation gracefully. + pending.shutdown = true + } + } + } +} + +// Log function names only. Argument values and goroutine labels can contain panel data. +func logPanelRestartStacks() { + records := make([]runtime.StackRecord, 2048) + n, ok := runtime.GoroutineProfile(records) + if !ok { + log.Printf("panel restart goroutine profile omitted: %d goroutines exceed diagnostic capacity", n) + return + } + log.Printf("panel restart goroutine profile: %d goroutines, showing up to 24 stacks", n) + for _, record := range records[:min(n, 24)] { + frames := runtime.CallersFrames(record.Stack()) + names := make([]string, 0, 12) + for range cap(names) { + frame, more := frames.Next() + if frame.Function != "" { + names = append(names, frame.Function) + } + if !more { + break + } + } + log.Print(strings.Join(names, " <- ")) + } +} diff --git a/panel_restart_test.go b/panel_restart_test.go new file mode 100644 index 000000000..75a32707c --- /dev/null +++ b/panel_restart_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "errors" + "os" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +func TestPanelRestartDeadlineFencesBlockedDrain(t *testing.T) { + entered, release, drained := make(chan struct{}), make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + t.Cleanup(unblock) + newGeneration := make(chan struct{}) + _, err := runPanelRestart(nil, 250*time.Millisecond, + panelRestartPhase{"panel drain", func(context.Context) error { + close(entered) + <-release + close(drained) + return nil + }}, + panelRestartPhase{"panel startup", func(context.Context) error { close(newGeneration); return nil }}, + ) + if !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "panel drain") { + t.Fatalf("blocked drain: %v", err) + } + <-entered + unblock() + <-drained + select { + case <-newGeneration: + t.Fatal("new workers started after a failed drain") + case <-time.After(75 * time.Millisecond): + } +} + +func TestPanelRestartDrainsBeforeGracefulShutdown(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + t.Cleanup(unblock) + signals := make(chan os.Signal) + type outcome struct { + pending panelRestartSignals + err error + } + result := make(chan outcome, 1) + started := false + go func() { + pending, err := runPanelRestart(signals, 3*time.Second, + panelRestartPhase{"panel shutdown", func(context.Context) error { + close(entered) + <-release + return nil + }}, + panelRestartPhase{"panel startup", func(context.Context) error { + started = true + return nil + }}, + ) + result <- outcome{pending, err} + }() + <-entered + signals <- syscall.SIGHUP + signals <- syscall.SIGTERM + unblock() + got := <-result + if got.err != nil || !got.pending.shutdown || !started { + t.Fatalf("current restart must finish before graceful cleanup: started=%v, result=%+v", started, got) + } +} + +func TestPanelRestartDoesNotStartListenersAfterShutdownFailure(t *testing.T) { + failure := errors.New("old listener did not drain") + started := false + _, err := runPanelRestart(nil, time.Second, + panelRestartPhase{"panel shutdown", func(context.Context) error { return failure }}, + panelRestartPhase{"panel startup", func(context.Context) error { started = true; return nil }}, + ) + if started || !errors.Is(err, failure) { + t.Fatalf("started=%t, error=%v", started, err) + } +} From 9f483d94653142d72290cbb10ff29cb55db88791 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 12:30:15 +0330 Subject: [PATCH 6/7] fix(inbounds): check WebSocket snapshot size before loading (#7309) Avoid materializing full inbound settings and client statistics only to discard the snapshot above the existing 5,000-row WebSocket cutoff. Probe user-scoped direct and sibling-backed traffic rows with bounded SQL before loading the snapshot; skip work without subscribers, fall back to invalidation on probe failure, and retain the post-read guard for concurrent growth. Coalesce WebSocket invalidations by resource in a 200 ms window so paired Inbounds and Clients events refresh both query roots without duplicate same-resource refetches. Regression coverage exercises the real inbound mutation route and WebSocket hub at and above the cutoff, shared traffic, user scoping, no subscribers, and frontend paired invalidations. All 12 CI jobs passed on the reviewed PR head. The author also reports SQLite/PostgreSQL 16 validation and make verify. Static review of the current merge candidate found no overlapping file changes with main; CI on that exact combined revision was not independently run before merge. The reported synthetic SQLite notification benchmark (30 inbounds, 7,101 clients, 115,041 associations) improved from 323.87 ms to 0.24 ms and from 324,751,126 to 5,393 allocated bytes per operation. These figures do not establish production HTTP or browser latency improvements. Fixes #7297 --- frontend/src/api/websocketBridge.ts | 24 +-- .../test/websocket-bridge-inbounds.test.tsx | 63 ++++++ internal/web/controller/inbound.go | 12 +- .../web/controller/inbound_broadcast_test.go | 192 ++++++++++++++++++ internal/web/service/inbound.go | 26 +++ 5 files changed, 300 insertions(+), 17 deletions(-) create mode 100644 frontend/src/test/websocket-bridge-inbounds.test.tsx create mode 100644 internal/web/controller/inbound_broadcast_test.go diff --git a/frontend/src/api/websocketBridge.ts b/frontend/src/api/websocketBridge.ts index 9394398c8..b475a20a0 100644 --- a/frontend/src/api/websocketBridge.ts +++ b/frontend/src/api/websocketBridge.ts @@ -7,26 +7,27 @@ import { isRecentLocalInvalidate } from '@/api/invalidationTracker'; type Handler = (payload: unknown) => void; -let invalidateTimer: number | null = null; - export function useWebSocketBridge() { const queryClient = useQueryClient(); useEffect(() => { const client = getSharedWebSocketClient(); + const pendingInvalidations = new Set<'inbounds' | 'clients'>(); + let invalidateTimer: number | undefined; const onInvalidate: Handler = (payload) => { const p = payload as { type?: string } | undefined; if (!p || (p.type !== 'inbounds' && p.type !== 'clients')) return; - if (invalidateTimer != null) clearTimeout(invalidateTimer); + pendingInvalidations.add(p.type); + if (invalidateTimer !== undefined) return; invalidateTimer = window.setTimeout(() => { - invalidateTimer = null; - if (isRecentLocalInvalidate()) return; - if (p.type === 'inbounds') { - queryClient.invalidateQueries({ queryKey: ['inbounds'] }); - } else { - queryClient.invalidateQueries({ queryKey: ['clients'] }); + invalidateTimer = undefined; + if (!isRecentLocalInvalidate()) { + for (const type of pendingInvalidations) { + queryClient.invalidateQueries({ queryKey: keys[type].root() }); + } } + pendingInvalidations.clear(); }, 200); }; @@ -56,10 +57,7 @@ export function useWebSocketBridge() { client.off('outbounds', onOutbounds); client.off('nodes', onNodes); client.off('inbounds', onInbounds); - if (invalidateTimer != null) { - clearTimeout(invalidateTimer); - invalidateTimer = null; - } + clearTimeout(invalidateTimer); }; }, [queryClient]); } diff --git a/frontend/src/test/websocket-bridge-inbounds.test.tsx b/frontend/src/test/websocket-bridge-inbounds.test.tsx new file mode 100644 index 000000000..2849f27af --- /dev/null +++ b/frontend/src/test/websocket-bridge-inbounds.test.tsx @@ -0,0 +1,63 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClientProvider, useQuery } from '@tanstack/react-query'; +import type { ReactNode } from 'react'; +import { expect, it, vi } from 'vitest'; + +import { keys } from '@/api/queryKeys'; +import { getSharedWebSocketClient } from '@/api/websocket'; +import { useWebSocketBridge } from '@/api/websocketBridge'; + +import { makeTestQueryClient } from './test-utils'; + +it('refreshes inbounds and clients when a mutation invalidates both resources', async () => { + const sockets: EventTarget[] = []; + class FixtureSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + readyState = FixtureSocket.CONNECTING; + constructor() { + super(); + sockets.push(this); + } + close() {} + } + vi.stubGlobal('WebSocket', FixtureSocket); + const queryClient = makeTestQueryClient(); + let rows = [{ id: 1, remark: 'Before update' }]; + const fetchInbounds = vi.fn(async () => rows); + const fetchClients = vi.fn(async () => []); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const { result, unmount } = renderHook( + () => { + useWebSocketBridge(); + useQuery({ queryKey: keys.clients.all(), queryFn: fetchClients }); + return useQuery({ queryKey: keys.inbounds.slim(), queryFn: fetchInbounds }); + }, + { wrapper }, + ); + + try { + await waitFor(() => expect(result.current.data).toEqual(rows)); + const [connected] = sockets; + if (!connected) throw new Error('WebSocket was not connected'); + rows = [{ id: 1, remark: 'After update' }]; + act(() => { + for (const type of ['inbounds', 'inbounds', 'clients']) { + connected.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ type: 'invalidate', payload: { type } }), + }), + ); + } + }); + await waitFor(() => expect(result.current.data).toEqual(rows)); + expect(fetchInbounds).toHaveBeenCalledTimes(2); + expect(fetchClients).toHaveBeenCalledTimes(2); + } finally { + unmount(); + getSharedWebSocketClient().disconnect(); + vi.unstubAllGlobals(); + } +}); diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index ad4020ddf..f89aea5bb 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -39,18 +39,22 @@ func NewInboundController(g *gin.RouterGroup) *InboundController { // Mirrors the same heuristic used by the periodic traffic job. const broadcastInboundsUpdateClientLimit = 5000 -// broadcastInboundsUpdate fetches and broadcasts the inbound list for userId. -// At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling, -// so we send an invalidate signal instead — frontend re-fetches via REST. -// Skipped entirely when no WebSocket clients are connected. +// broadcastInboundsUpdate sends either a small snapshot or an invalidate. +// Skip all snapshot work when no WebSocket clients are connected. func (a *InboundController) broadcastInboundsUpdate(userId int) { if !websocket.HasClients() { return } + overLimit, err := a.inboundService.InboundClientStatsOverLimit(userId, broadcastInboundsUpdateClientLimit) + if err != nil || overLimit { + websocket.BroadcastInvalidate(websocket.MessageTypeInbounds) + return + } inbounds, err := a.inboundService.GetInbounds(userId) if err != nil { return } + // Stats can grow between the probe and the snapshot read. totalClients := 0 for _, ib := range inbounds { totalClients += len(ib.ClientStats) diff --git a/internal/web/controller/inbound_broadcast_test.go b/internal/web/controller/inbound_broadcast_test.go new file mode 100644 index 000000000..9587de484 --- /dev/null +++ b/internal/web/controller/inbound_broadcast_test.go @@ -0,0 +1,192 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "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/web/entity" + "github.com/mhsanaei/3x-ui/v3/internal/web/global" + "github.com/mhsanaei/3x-ui/v3/internal/web/session" + "github.com/mhsanaei/3x-ui/v3/internal/web/websocket" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type inboundBroadcastServer struct{ hub *websocket.Hub } + +func (s inboundBroadcastServer) GetWSHub() any { return s.hub } +func (inboundBroadcastServer) GetCtx() context.Context { return context.Background() } +func (inboundBroadcastServer) GetCron() *cron.Cron { return nil } + +func TestInboundMutationSkipsSnapshotReadsAboveWebSocketCutoff(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "panel.db")) + db := database.GetDB() + seed := func(userID, port, count int) model.Inbound { + t.Helper() + row := model.Inbound{UserId: userID, Port: port, Tag: fmt.Sprintf("in-%d", port), Protocol: model.VLESS, Settings: `{"clients":[],"decryption":"none"}`} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + stats := make([]xray.ClientTraffic, count) + for i := range stats { + stats[i] = xray.ClientTraffic{InboundId: row.Id, Email: fmt.Sprintf("client-%d-%d", port, i)} + } + if count > 0 { + if err := db.CreateInBatches(&stats, 100).Error; err != nil { + t.Fatal(err) + } + } + return row + } + const limit = broadcastInboundsUpdateClientLimit + owned := seed(1, 29100, limit-1) + sibling := seed(1, 29101, 0) + seed(2, 29102, limit+1) + attach := func(inbound model.Inbound, statsIndex int) { + t.Helper() + row := model.ClientRecord{Email: fmt.Sprintf("client-%d-%d", owned.Port, statsIndex)} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id} + if err := db.Create(&link).Error; err != nil { + t.Fatal(err) + } + } + attach(sibling, 0) + attach(owned, 1) + + snapshotReads, probes := 0, 0 + if err := db.Callback().Query().After("gorm:query").Register("test:inbound_snapshot", func(tx *gorm.DB) { + sql := tx.Statement.SQL.String() + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && + strings.Contains(sql, "WHERE user_id =") && strings.HasSuffix(sql, "ORDER BY id ASC") { + snapshotReads++ + } + }); err != nil { + t.Fatal(err) + } + if err := db.Callback().Row().After("gorm:row").Register("test:inbound_stats_probe", func(tx *gorm.DB) { + if strings.Contains(tx.Statement.SQL.String(), "AS candidate_stats") { + probes++ + } + }); err != nil { + t.Fatal(err) + } + + router := gin.New() + group := router.Group("/panel/api/inbounds", func(c *gin.Context) { + session.SetAPIAuthUser(c, &model.User{Id: 1}) + }) + NewInboundController(group) + previous := global.GetWebServer() + t.Cleanup(func() { global.SetWebServer(previous) }) + + for i, tc := range []struct { + name string + ws bool + wantType websocket.MessageType + reads int + prepare func() + }{ + {name: "no subscribers"}, + {name: "at cutoff with shared traffic and unrelated user", ws: true, wantType: websocket.MessageTypeInbounds, reads: 1}, + {name: "above cutoff from sibling counter", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { attach(sibling, 2) }}, + {name: "above cutoff from direct traffic", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { seed(1, 29110, 2) }}, + } { + t.Run(tc.name, func(t *testing.T) { + var subscriber *websocket.Client + if tc.ws { + hub := websocket.NewHub() + done := make(chan struct{}) + go func() { + defer close(done) + hub.Run() + }() + t.Cleanup(func() { hub.Stop(); <-done }) + global.SetWebServer(inboundBroadcastServer{hub}) + subscriber = websocket.NewClient("test") + hub.Register(subscriber) + for deadline := time.Now().Add(2 * time.Second); hub.GetClientCount() == 0; { + if time.Now().After(deadline) { + t.Fatal("subscriber did not register") + } + time.Sleep(time.Millisecond) + } + } else { + global.SetWebServer(nil) + } + if tc.prepare != nil { + tc.prepare() + } + snapshotReads, probes = 0, 0 + port := 29103 + i + body := fmt.Sprintf(`{"protocol":"vless","enable":false,"remark":"created","port":%d,"settings":"{\"clients\":[],\"decryption\":\"none\"}","streamSettings":"{\"network\":\"tcp\",\"security\":\"none\"}"}`, port) + req := httptest.NewRequest(http.MethodPost, "/panel/api/inbounds/add", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var response entity.Msg + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || !response.Success { + t.Fatalf("add failed: %s (%v)", rec.Body, err) + } + if snapshotReads != tc.reads { + t.Errorf("full inbound snapshot reads = %d, want %d", snapshotReads, tc.reads) + } + wantProbes := 0 + if tc.ws { + wantProbes = 1 + } + if probes != wantProbes { + t.Errorf("snapshot size probes = %d, want %d", probes, wantProbes) + } + if subscriber == nil { + return + } + select { + case data := <-subscriber.Send: + var event struct { + Type websocket.MessageType + Payload json.RawMessage + } + if err := json.Unmarshal(data, &event); err != nil || event.Type != tc.wantType { + t.Fatalf("unexpected WebSocket type %q: %v, want %q", event.Type, err, tc.wantType) + } + if tc.wantType == websocket.MessageTypeInbounds { + var rows []model.Inbound + if err := json.Unmarshal(event.Payload, &rows); err != nil { + t.Fatal(err) + } + total, created := 0, false + for _, row := range rows { + if row.Port == 29102 { + t.Fatal("snapshot contains another user's inbound") + } + total += len(row.ClientStats) + created = created || row.Port == port + } + if !created || total != limit { + t.Fatalf("snapshot missing updated state: created=%t client stats=%d", created, total) + } + } else if string(event.Payload) != `{"type":"inbounds"}` { + t.Fatalf("unexpected invalidation payload %s", event.Payload) + } + case <-time.After(2 * time.Second): + t.Fatal("mutation did not publish an inbound event") + } + }) + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 4761e279d..1d9c194db 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -199,6 +199,32 @@ func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { return inbounds, nil } +// InboundClientStatsOverLimit probes direct stats and eligible sibling counters +// without fetching inbound settings or materializing stats. +func (s *InboundService) InboundClientStatsOverLimit(userID, limit int) (bool, error) { + var count int + // Exact email matches include every row eligible for backfill. Case folding + // can only reduce the number actually appended by backfillClientStats. + err := database.GetDB().Raw(` + SELECT COUNT(*) FROM ( + SELECT 1 + FROM inbounds AS ib + JOIN client_traffics AS stats ON stats.inbound_id = ib.id + WHERE ib.user_id = ? + UNION ALL + SELECT 1 + FROM inbounds AS ib + JOIN client_inbounds AS link ON link.inbound_id = ib.id + JOIN clients AS client ON client.id = link.client_id + JOIN client_traffics AS stats ON stats.email = client.email + WHERE ib.user_id = ? AND client.email <> '' + AND (stats.inbound_id <> ib.id OR stats.inbound_id IS NULL) + LIMIT ? + ) AS candidate_stats + `, userID, userID, limit+1).Row().Scan(&count) + return count > limit, err +} + func (s *InboundService) getInboundsFromDB(db *gorm.DB, userId int) ([]*model.Inbound, error) { var inbounds []*model.Inbound err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error From bdddb08249f343b2e063bdf4158d18da2cbe6caa Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 13:02:15 +0330 Subject: [PATCH 7/7] fix(nodes): shorten the traffic merge lock window (#7315) Stage existing client traffic updates in snapshot order and flush them after client reconciliation to shorten PostgreSQL row-lock lifetime. Keep configuration, traffic counters, renewals and baselines atomic in the same serialized transaction, preserve concurrent last_sub_fetch updates, and retain rollback and idempotent replay semantics. Batch baseline upserts by (node_id, email) within SQLite parameter limits. Decode snapshot claims before opening the transaction while retaining transactional ownership checks. Add debug metrics for queue wait, writer execution and transaction duration. Validation: all 12 GitHub CI jobs passed on reviewed head 6dc504b67575576c00ec89aca4b646aa409f88e7, including race, PostgreSQL, node and Xray E2E. PostgreSQL CI logs explicitly confirm both contention and baseline batching regressions. The author reports PostgreSQL 16/18 validation, rollback/replay coverage and a reduction from 4,187 baseline upserts to 28 in a local fixture. Scope: this resolves the reproduced subscription row-lock window, not the full serialized writer hold, shared-client cache restriction, historical 41-second SQL tail or cross-process migration/restore deadlock. These require follow-up. No independent production measurements or successful CI run on the exact latest combined revision were verified before merge. Refs #7305 --- .github/workflows/ci.yml | 10 + internal/web/service/inbound_node.go | 132 +++++++++----- internal/web/service/inbound_node_claims.go | 51 ++++-- .../web/service/node_merge_contention_test.go | 172 ++++++++++++++++++ 4 files changed, 299 insertions(+), 66 deletions(-) create mode 100644 internal/web/service/node_merge_contention_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..2e83d681e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,6 +214,16 @@ jobs: exit 1 fi + - name: PostgreSQL node merge contention + run: | + set -o pipefail + go test ./internal/web/service -run '^TestNodeMerge(LetsSubscriptionTouchDuringClientReconciliationPostgres|BatchesBaselinesForActiveClients)$' -count=1 -v | tee /tmp/postgres-node-merge-contention.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-merge-contention.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected both PostgreSQL node merge contention tests to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL schema and migration tests run: | set -o pipefail diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6f855bda0..5ca1f4bc8 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -248,19 +248,48 @@ type nodeTrafficCounter struct { Down int64 } -func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, counter nodeTrafficCounter, dippedWhileFrozen bool) error { +func upsertNodeBaselines(tx *gorm.DB, changes map[string]model.NodeClientTraffic) error { + if len(changes) == 0 { + return nil + } + rows := make([]model.NodeClientTraffic, 0, len(changes)) + for _, email := range slices.Sorted(maps.Keys(changes)) { + rows = append(rows, changes[email]) + } return tx.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, DoUpdates: clause.AssignmentColumns([]string{"up", "down", "dipped_while_frozen"}), - }).Create(&model.NodeClientTraffic{ - NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dippedWhileFrozen, - }).Error + }).CreateInBatches(rows, sqliteMaxVars/6).Error } -// mergeNodeClientTraffic folds one node-reported client into its central row. -// While frozen (a push pending or just landed) only the counters may move. -func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraffic, canon nodeTrafficCounter, frozen bool, deltaUp, deltaDown, now int64) error { - if frozen { +type nodeClientTrafficWrite struct { + stats xray.ClientTraffic + canon nodeTrafficCounter + deltaUp, deltaDown int64 + frozen, renewed bool +} + +// apply folds a planned change into the existing counter row without touching last_sub_fetch. +func (write nodeClientTrafficWrite) apply(tx *gorm.DB, now int64) error { + cs, canon := write.stats, write.canon + if write.renewed { + if err := tx.Exec( + fmt.Sprintf( + `UPDATE client_traffics + SET up = ?, down = ?, enable = ?, total = ?, + expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s + WHERE email = ?`, + database.GreatestExpr("last_online", "?"), + ), + canon.Up, canon.Down, cs.Enable, cs.Total, + cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, + cs.LastOnline, cs.Email, + ).Error; err != nil { + return err + } + return clearGlobalTraffic(tx, cs.Email) + } + if write.frozen { return tx.Exec( fmt.Sprintf( `UPDATE client_traffics @@ -270,7 +299,7 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClampedAddExpr("down"), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, cs.LastOnline, cs.Email, + write.deltaUp, write.deltaDown, cs.LastOnline, cs.Email, ).Error } return tx.Exec( @@ -286,8 +315,8 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClientTrafficExpiryMergeExpr(), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, - cs.Enable, now, deltaUp, deltaDown, canon.Up, canon.Down, + write.deltaUp, write.deltaDown, + cs.Enable, now, write.deltaUp, write.deltaDown, canon.Up, canon.Down, cs.Total, cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.LastOnline, cs.Email, @@ -433,11 +462,15 @@ func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime. // config push just landed, whose snapshot may still predate it (#6228). func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { var structuralChange bool + queuedAt := time.Now() // Node merges take the background lane: a per-client mutation the operator // is waiting on must not queue behind the next batch of 5s snapshots. err := submitTrafficWriteBackground(func() error { + started := time.Now() var inner error structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed) + logger.Debugf("node traffic writer: node_id=%d queue_wait_ms=%d writer_ms=%d success=%t", + nodeID, started.Sub(queuedAt).Milliseconds(), time.Since(started).Milliseconds(), inner == nil) return inner }) if err != nil { @@ -793,18 +826,27 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + var claimInputs nodeClaimInputs + if !skipStructure { + claimInputs = readNodeClaimInputs(snap) + } + txStarted := time.Now() tx := db.Begin() + if tx.Error != nil { + return false, tx.Error + } committed := false defer func() { if !committed { tx.Rollback() + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=false", nodeID, time.Since(txStarted).Milliseconds()) } }() claims := &nodeClientClaims{} rawSettings := make(map[*model.Inbound]string, len(snap.Inbounds)) if !skipStructure { - claims, err = loadNodeClientClaims(tx, nodeID, snap) + claims, err = loadNodeClientClaims(tx, nodeID, claimInputs) if err != nil { return false, err } @@ -1167,6 +1209,19 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + baselineChanges := make(map[string]model.NodeClientTraffic) + var trafficWrites []nodeClientTrafficWrite + stageBaseline := func(email string, counter nodeTrafficCounter, dipped bool) { + baselineChanges[email] = model.NodeClientTraffic{ + NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dipped, + } + nodeBaselines[email] = counter + if dipped { + dippedWhileFrozen[email] = true + } else { + delete(dippedWhileFrozen, email) + } + } for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1260,11 +1315,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi activatedEmails[row.Email] = struct{}{} } structuralChange = true - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, false); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - delete(dippedWhileFrozen, cs.Email) + stageBaseline(cs.Email, canon, false) continue } @@ -1295,23 +1346,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if renewed { // A renewal starts a fresh quota window: adopt the node's counters // and enable state, drop stale pushes (mirrors autoRenewClients). - if err := tx.Exec( - fmt.Sprintf( - `UPDATE client_traffics - SET up = ?, down = ?, enable = ?, total = ?, - expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s - WHERE email = ?`, - database.GreatestExpr("last_online", "?"), - ), - canon.Up, canon.Down, cs.Enable, cs.Total, - cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, - cs.LastOnline, cs.Email, - ).Error; err != nil { - return false, err - } - if err := clearGlobalTraffic(tx, cs.Email); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{stats: cs, canon: canon, renewed: true}) existing.Up = canon.Up existing.Down = canon.Down existing.Enable = cs.Enable @@ -1343,9 +1378,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A multi-attached client is reported once per inbound and an idle one // every tick: rewriting an unchanged row only holds its lock longer. if next != *row { - if err := s.mergeNodeClientTraffic(tx, cs, canon, clientFrozen, deltaUp, deltaDown, now); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{ + stats: cs, canon: canon, frozen: clientFrozen, deltaUp: deltaUp, deltaDown: deltaDown, + }) if row.ExpiryTime <= 0 && next.ExpiryTime > 0 { activatedEmails[cs.Email] = struct{}{} } @@ -1358,15 +1393,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if seen && base == canon && stillOwed == dippedWhileFrozen[cs.Email] { continue } - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, stillOwed); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - if stillOwed { - dippedWhileFrozen[cs.Email] = true - } else { - delete(dippedWhileFrozen, cs.Email) - } + stageBaseline(cs.Email, canon, stillOwed) } if skipStructure { @@ -1509,7 +1536,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi adoptedSettings := p.wireSettings liftChanged := false if adopt && !isNew { - // Use the traffic deltas just applied to this transaction (#6228). + // Use the staged traffic values before flushing their SQL updates (#6228). if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed { adoptedSettings, liftChanged = lifted, true } @@ -1595,6 +1622,16 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + if err := upsertNodeBaselines(tx, baselineChanges); err != nil { + return false, err + } + // Client reconciliation used the planned traffic values in memory. Lock + // the existing traffic rows only now, in snapshot order, before commit. + for _, write := range trafficWrites { + if err := write.apply(tx, now); err != nil { + return false, err + } + } for _, emails := range chunkStrings(slices.Sorted(maps.Keys(activatedEmails)), sqlInChunk) { if err := liftActivatedClientRecordExpiries(tx.Model(&model.ClientRecord{}).Where("email IN ?", emails)); err != nil { return false, err @@ -1605,6 +1642,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi return false, err } committed = true + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=true", nodeID, time.Since(txStarted).Milliseconds()) if adoptedSettingsChanged { InvalidateSubData() } diff --git a/internal/web/service/inbound_node_claims.go b/internal/web/service/inbound_node_claims.go index 1e655a591..248a587c9 100644 --- a/internal/web/service/inbound_node_claims.go +++ b/internal/web/service/inbound_node_claims.go @@ -39,17 +39,20 @@ var nodeKeptSharedKeys = []string{"flow", "privateKey", "publicKey", "allowedIPs type clientLinkScope struct{ here, elsewhere bool } -func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot) (*nodeClientClaims, error) { - claims := &nodeClientClaims{ - refused: map[string]string{}, - shared: map[string]*model.ClientRecord{}, - storedSubID: map[string]string{}, - usageOnly: map[string]struct{}{}, +type nodeClaimInputs struct { + subIDByEmail map[string]string + refused map[string]string + sharesSubID map[string]struct{} +} + +func readNodeClaimInputs(snap *runtime.TrafficSnapshot) nodeClaimInputs { + inputs := nodeClaimInputs{ + subIDByEmail: map[string]string{}, + refused: map[string]string{}, + sharesSubID: map[string]struct{}{}, } - subIDByEmail := map[string]string{} // A subId selects a whole subscription, so within one snapshot it may name one client only. firstEmailBySub := map[string]string{} - sharesSubID := map[string]struct{}{} for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -64,28 +67,38 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot continue } if c.Email != strings.TrimSpace(c.Email) { - claims.refused[c.Email] = "its email carries surrounding white space" + inputs.refused[c.Email] = "its email carries surrounding white space" continue } - if _, seen := subIDByEmail[c.Email]; !seen { + if _, seen := inputs.subIDByEmail[c.Email]; !seen { var subID string _ = json.Unmarshal(c.SubID, &subID) - subIDByEmail[c.Email] = subID + inputs.subIDByEmail[c.Email] = subID if first, taken := firstEmailBySub[subID]; subID != "" && taken && !strings.EqualFold(first, c.Email) { - sharesSubID[c.Email] = struct{}{} + inputs.sharesSubID[c.Email] = struct{}{} } else if subID != "" && !taken { firstEmailBySub[subID] = c.Email } } } } - if len(subIDByEmail) == 0 { + return inputs +} + +func loadNodeClientClaims(tx *gorm.DB, nodeID int, inputs nodeClaimInputs) (*nodeClientClaims, error) { + claims := &nodeClientClaims{ + refused: inputs.refused, + shared: map[string]*model.ClientRecord{}, + storedSubID: map[string]string{}, + usageOnly: map[string]struct{}{}, + } + if len(inputs.subIDByEmail) == 0 { logRefusedClaims(nodeID, claims.refused) return claims, nil } - reported := make([]string, 0, len(subIDByEmail)) - for email := range subIDByEmail { + reported := make([]string, 0, len(inputs.subIDByEmail)) + for email := range inputs.subIDByEmail { reported = append(reported, email) } // SQLite's LOWER folds ASCII only, so a non-ASCII capital is matched by its spellings too. @@ -104,8 +117,8 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot byLower[strings.ToLower(records[i].Email)] = records[i].Email } - subIDs := make([]string, 0, len(subIDByEmail)) - for _, subID := range subIDByEmail { + subIDs := make([]string, 0, len(inputs.subIDByEmail)) + for _, subID := range inputs.subIDByEmail { if subID != "" { subIDs = append(subIDs, subID) } @@ -132,7 +145,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot holdersBySub[h.SubID] = append(holdersBySub[h.SubID], h) } subIDTaken := func(email, subID string) bool { - if _, shared := sharesSubID[email]; shared { + if _, shared := inputs.sharesSubID[email]; shared { return true } for _, h := range holdersBySub[subID] { @@ -143,7 +156,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot return false } - for email, subID := range subIDByEmail { + for email, subID := range inputs.subIDByEmail { rec, exact := byEmail[email] if !exact { if _, variant := byLower[strings.ToLower(email)]; variant { diff --git a/internal/web/service/node_merge_contention_test.go b/internal/web/service/node_merge_contention_test.go new file mode 100644 index 000000000..b5721132b --- /dev/null +++ b/internal/web/service/node_merge_contention_test.go @@ -0,0 +1,172 @@ +package service + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "contention.db")) + node := &model.Node{Name: "merge-lock-window", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "subscription-touch@example.test" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"subId":"touch-sub","enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "contention", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + before := readTraffic(t, db, email) + + const touchedAt = 1730000000123 + probed := false + var probeErr error + if err := db.Callback().Update().Before("gorm:update").Register("test:touch_during_reconcile", func(tx *gorm.DB) { + if tx.Statement.Table != "clients" || probed { + return + } + probed = true + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + probeErr = db.WithContext(ctx).Transaction(func(other *gorm.DB) error { + if err := other.Exec("SET LOCAL lock_timeout = '150ms'").Error; err != nil { + return err + } + return other.Model(&xray.ClientTraffic{}). + Where("email IN (SELECT email FROM clients WHERE sub_id = ?)", "touch-sub"). + Update("last_sub_fetch", touchedAt).Error + }) + }); err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + if !probed || probeErr != nil { + t.Fatalf("subscription update during client reconciliation: probed=%t err=%v", probed, probeErr) + } + if after := readTraffic(t, db, email); after.Up != before.Up+30 || after.Total != 2000 || after.LastSubFetch != touchedAt { + t.Fatalf("merge or subscription touch lost data: before=%+v after=%+v", before, after) + } +} + +func TestNodeMergeBatchesBaselinesForActiveClients(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "batch.db")) + node := &model.Node{Name: "batch-baselines", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const clients = 24 + snapshot := func(up int64) *runtime.TrafficSnapshot { + rows := make([]xray.ClientTraffic, 0, clients) + entries := make([]model.Client, 0, clients) + for i := range clients { + email := fmt.Sprintf("batch-%d@x", i) + rows = append(rows, xray.ClientTraffic{Email: email, Enable: true, Up: up}) + entries = append(entries, model.Client{Email: email, Enable: true}) + } + return snapshotWithClients(t, "batch-baselines", clientsSettings(t, entries), rows...) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100), false, false); err != nil { + t.Fatal(err) + } + trace := &snapshotReadLog{Interface: logger.Discard} + previous := db.Logger + db.Logger = trace + t.Cleanup(func() { db.Logger = previous }) + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + writes := 0 + for _, sql := range trace.statements { + if strings.HasPrefix(strings.ToUpper(sql), "INSERT INTO") && strings.Contains(sql, "node_client_traffics") { + writes++ + } + } + if writes != 1 { + t.Errorf("baseline upserts=%d for %d changed clients, want one", writes, clients) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + var rows []model.NodeClientTraffic + if err := db.Where("node_id = ?", node.Id).Find(&rows).Error; err != nil { + t.Fatal(err) + } + if len(rows) != clients { + t.Fatalf("stored %d baselines, want %d", len(rows), clients) + } + for _, row := range rows { + if row.Up != 107 { + t.Errorf("%s baseline up=%d, want 107", row.Email, row.Up) + } + if traffic := readTraffic(t, db, row.Email); traffic.Up != 107 { + t.Errorf("%s stored up=%d, want one 7-byte delta on top of adoption", row.Email, traffic.Up) + } + } +} + +func TestNodeMergeRollsBackConfigTrafficAndBaselineOnLateWriteFailure(t *testing.T) { + if config.GetDBKind() == database.DialectPostgres { + t.Skip("uses a SQLite trigger to fail the final traffic update") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "rollback.db")) + node := &model.Node{Name: "late-traffic-rollback", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "late-traffic@x" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "late-write", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + if err := db.Exec(`CREATE TRIGGER fail_late_traffic BEFORE UPDATE OF up ON client_traffics + WHEN NEW.email = 'late-traffic@x' AND NEW.up > OLD.up + BEGIN SELECT RAISE(ABORT, 'injected late traffic failure'); END`).Error; err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err == nil || !strings.Contains(err.Error(), "injected late traffic failure") { + t.Fatalf("merge failure=%v, want triggered write failure", err) + } + assertState := func(up, quota int64) { + t.Helper() + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", node.Id, email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, email) + record := lookupClientRecord(t, email) + if baseline.Up != up || traffic.Up != up || traffic.Total != quota || record.TotalGB != quota { + t.Fatalf("inconsistent merge: baseline=%d up=%d traffic quota=%d record quota=%d", baseline.Up, traffic.Up, traffic.Total, record.TotalGB) + } + } + assertState(100, 1000) + if err := db.Exec("DROP TRIGGER fail_late_traffic").Error; err != nil { + t.Fatal(err) + } + for range 2 { + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + } + assertState(130, 2000) +}