[PR #6916] [MERGED] perf(runtime): pool the local xray gRPC connection #6519

Closed
opened 2026-11-02 04:09:20 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6916
Author: @muditagrawal2007
Created: 10/24/2026
Status: ✅ Merged
Merged: 10/24/2026
Merged by: @MHSanaei

Base: main ← Head: perf/local-xray-grpc-pool


📝 Commits (6)

  • 1ee1c73 perf(runtime): pool the local xray gRPC connection
  • 5a48c92 Merge remote-tracking branch 'origin/main' into pr/6916
  • 76d82fe style(runtime): fit the pooled-client comments in two lines
  • cc3d140 Merge remote-tracking branch 'origin/main' into perf/local-xray-grpc-pool
  • 2d412f6 fix(runtime): drop the pooled client when the core is unreachable
  • 57cd898 refactor(runtime): fold the core-restart test into the pool tests

📊 Changes

3 files changed (+186 additions, -4 deletions)

View changed files

📝 internal/web/runtime/local.go (+17 -4)
➕ internal/web/runtime/local_api.go (+52 -0)
➕ internal/web/runtime/local_api_test.go (+117 -0)

📄 Description

Summary

The local runtime opened a gRPC connection to the Xray core for every operation and closed it again afterwards. A bulk client delete calls the runtime once per client, so it paid a TCP + HTTP/2 handshake per client.

The connection is now pooled per API port.

before after
gRPC connections for a 5 000-client delete 5 000 1
connection lifetime one operation until the API port moves

Why

internal/web/runtime/local.go — every local inbound and user operation went through this:

var api xray.XrayAPI
if err := api.Init(port); err != nil { return err }
defer api.Close()          // ← the connection dies with the call
return fn(&api)

The removal loops call the runtime once per email — internal/web/service/client_bulk.go:1216, internal/web/service/client_inbound_apply.go:236 and :1225 — so a bulk delete did one grpc.NewClient + handshake per client, all serialised behind the runtime's mutex.

The fix keeps one client per API port, mirroring the node HTTP pool that already exists in this package (internal/web/runtime/tls_client.go:157-231):

api, err := localAPIForPort(port)   // built on first use, reused afterwards

A core restart can move the API port (internal/xray/process.go:580 recomputes it from the config), so the pool follows the port and closes the client it replaces rather than leaking it.

The hazard this deliberately avoids

xray.XrayAPI.StatsLastValues is written without a lock (internal/xray/api.go:846), so a second concurrent reader corrupts it — and a concurrent map write is a fatal runtime throw that cron.Recover cannot catch (the panel's own comment at internal/web/web.go:534-538 describes exactly this). The pooled client is therefore used only for inbound and user operations; the traffic poll keeps its own client, as before.

Evidence — red before, green after

before/after: a fresh connection per operation vs one pooled connection

--- FAIL: TestLocalWithAPIKeepsTheClientOpen
    the client was closed when the call returned; a pooled client must stay open
--- FAIL: TestLocalWithAPIReusesOneClient
    call 1 got a different client; the local gRPC connection must be pooled

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other

Areas affected

  • Backend (API endpoints, login, settings)
  • Frontend (UI / panel pages)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

Four new tests in internal/web/runtime/local_api_test.go:

  • TestLocalWithAPIKeepsTheClientOpen — after a call, the client must still be connected. XrayAPI.Close() nils the exported stub pointers, so a closed client is observable without reaching into the core.
  • TestLocalWithAPIReusesOneClient — three calls must hand out the same client.
  • TestLocalWithAPIEvictsTheClientWhenThePortChanges — a moved API port must not reuse the old client, and the old one must be closed.
  • TestLocalWithAPIWithoutARunningCoreFails — the "local xray is not running" path is unchanged.

Commands run locally:

go test ./internal/web/runtime/ ./internal/web/service/... ./internal/web/ -count=1
go test -race -count=1 ./internal/web/runtime/ ./internal/web/service/
go test -shuffle=on -count=1 $(go list ./... | grep -v frontend/node_modules)   # full Go suite
gofmt / gofumpt / go vet — clean
golangci-lint v2.15.0 run ./internal/web/... — 0 issues

Notes for the reviewer

  • Ordering is unchanged. The local runtime's mutex still serialises the calls, so UpdateInbound (remove + add) stays atomic against every other local operation — that guarantee is independent of the connection.
  • A gRPC ClientConn is safe for concurrent use, and the pooled client is only ever touched under the runtime's mutex, so the pool adds no new concurrency.
  • A dead core behaves the same as before: the pooled connection reconnects on its own, and a failed call still surfaces as an error to the caller.
  • No behaviour change — same operations, same order, same errors; only the connection lifetime changed.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6916 **Author:** [@muditagrawal2007](https://github.com/muditagrawal2007) **Created:** 10/24/2026 **Status:** ✅ Merged **Merged:** 10/24/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `perf/local-xray-grpc-pool` --- ### 📝 Commits (6) - [`1ee1c73`](https://github.com/MHSanaei/3x-ui/commit/1ee1c73c815bb243cb0f72336838492059cff213) perf(runtime): pool the local xray gRPC connection - [`5a48c92`](https://github.com/MHSanaei/3x-ui/commit/5a48c92b6a70d258949d10c09e0cd63e4a10fe30) Merge remote-tracking branch 'origin/main' into pr/6916 - [`76d82fe`](https://github.com/MHSanaei/3x-ui/commit/76d82fe074197df7485fb4cb23b5833f83dae738) style(runtime): fit the pooled-client comments in two lines - [`cc3d140`](https://github.com/MHSanaei/3x-ui/commit/cc3d140b7d6af2384c6dad04ad243b2b9cd17868) Merge remote-tracking branch 'origin/main' into perf/local-xray-grpc-pool - [`2d412f6`](https://github.com/MHSanaei/3x-ui/commit/2d412f615b047abffcb006d6a8103a0b15612bc8) fix(runtime): drop the pooled client when the core is unreachable - [`57cd898`](https://github.com/MHSanaei/3x-ui/commit/57cd89842158b7c8a2e8da58219402fd7cc00643) refactor(runtime): fold the core-restart test into the pool tests ### 📊 Changes **3 files changed** (+186 additions, -4 deletions) <details> <summary>View changed files</summary> 📝 `internal/web/runtime/local.go` (+17 -4) ➕ `internal/web/runtime/local_api.go` (+52 -0) ➕ `internal/web/runtime/local_api_test.go` (+117 -0) </details> ### 📄 Description ## Summary The local runtime opened a gRPC connection to the Xray core for **every** operation and closed it again afterwards. A bulk client delete calls the runtime once per client, so it paid a TCP + HTTP/2 handshake per client. The connection is now pooled per API port. | | before | after | |---|---|---| | gRPC connections for a 5 000-client delete | 5 000 | 1 | | connection lifetime | one operation | until the API port moves | --- ## Why `internal/web/runtime/local.go` — every local inbound and user operation went through this: ```go var api xray.XrayAPI if err := api.Init(port); err != nil { return err } defer api.Close() // ← the connection dies with the call return fn(&api) ``` The removal loops call the runtime once per email — `internal/web/service/client_bulk.go:1216`, `internal/web/service/client_inbound_apply.go:236` and `:1225` — so a bulk delete did one `grpc.NewClient` + handshake per client, all serialised behind the runtime's mutex. The fix keeps one client per API port, mirroring the node HTTP pool that already exists in this package (`internal/web/runtime/tls_client.go:157-231`): ```go api, err := localAPIForPort(port) // built on first use, reused afterwards ``` A core restart can move the API port (`internal/xray/process.go:580` recomputes it from the config), so the pool follows the port and **closes** the client it replaces rather than leaking it. ### The hazard this deliberately avoids `xray.XrayAPI.StatsLastValues` is written without a lock (`internal/xray/api.go:846`), so a second concurrent reader corrupts it — and a concurrent map write is a **fatal runtime throw** that `cron.Recover` cannot catch (the panel's own comment at `internal/web/web.go:534-538` describes exactly this). The pooled client is therefore used **only** for inbound and user operations; the traffic poll keeps its own client, as before. ### Evidence — red before, green after ![before/after: a fresh connection per operation vs one pooled connection](https://raw.githubusercontent.com/muditagrawal2007/3x-ui/pr-evidence/local-grpc-pool/.github/pr-evidence/local-grpc-pool.png) ``` --- FAIL: TestLocalWithAPIKeepsTheClientOpen the client was closed when the call returned; a pooled client must stay open --- FAIL: TestLocalWithAPIReusesOneClient call 1 got a different client; the local gRPC connection must be pooled ``` --- ## Type of change - [ ] Bug fix - [ ] New feature - [x] Refactoring (no behavior change) - [ ] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [x] Backend (API endpoints, login, settings) - [ ] Frontend (UI / panel pages) - [x] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [ ] Statistics / traffic counters - [ ] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [ ] Multi-node (sub-nodes) - [ ] Telegram bot ## How was this tested? Four new tests in `internal/web/runtime/local_api_test.go`: - **`TestLocalWithAPIKeepsTheClientOpen`** — after a call, the client must still be connected. `XrayAPI.Close()` nils the exported stub pointers, so a closed client is observable without reaching into the core. - **`TestLocalWithAPIReusesOneClient`** — three calls must hand out the same client. - **`TestLocalWithAPIEvictsTheClientWhenThePortChanges`** — a moved API port must not reuse the old client, and the old one must be closed. - **`TestLocalWithAPIWithoutARunningCoreFails`** — the "local xray is not running" path is unchanged. Commands run locally: ``` go test ./internal/web/runtime/ ./internal/web/service/... ./internal/web/ -count=1 go test -race -count=1 ./internal/web/runtime/ ./internal/web/service/ go test -shuffle=on -count=1 $(go list ./... | grep -v frontend/node_modules) # full Go suite gofmt / gofumpt / go vet — clean golangci-lint v2.15.0 run ./internal/web/... — 0 issues ``` ## Notes for the reviewer - **Ordering is unchanged.** The local runtime's mutex still serialises the calls, so `UpdateInbound` (remove + add) stays atomic against every other local operation — that guarantee is independent of the connection. - **A gRPC `ClientConn` is safe for concurrent use**, and the pooled client is only ever touched under the runtime's mutex, so the pool adds no new concurrency. - **A dead core behaves the same as before**: the pooled connection reconnects on its own, and a failed call still surfaces as an error to the caller. - **No behaviour change** — same operations, same order, same errors; only the connection lifetime changed. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:09:20 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6519
No description provided.