[PR #5507] [CLOSED] feat(traffic): inbound Traffic Multiplier (per-attachment billing) #5908

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/5507
Author: @nima1024m
Created: 6/23/2026
Status: ❌ Closed

Base: main ← Head: feat/inbound-traffic-multiplier


📝 Commits (10+)

  • 4562072 feat(traffic): add Traffic Multiplier schema and Billed columns
  • d875c0e feat(traffic): meter per attachment and accrue Billed
  • 2731b7a feat(traffic): enforce quota on Billed; clear it on reset/renew
  • 342beb7 feat(traffic): decode per-attachment identity in IP-limit and online paths
  • 0de1eb3 feat(traffic): propagate Billed and the multiplier across the node fleet
  • a863913 feat(traffic): surface the multiplier in the panel UI and subscriptions
  • 5a96df4 fix(traffic): address ultra-review findings
  • 41248e5 fix(traffic): close ultra-review gaps (upgrade double-bill, Real-vs-Billed)
  • 8b780fb Merge origin/main into feat/inbound-traffic-multiplier
  • 21c985a Merge origin/main (v3.4.0) into feat/inbound-traffic-multiplier

📊 Changes

72 files changed (+1448 additions, -130 deletions)

View changed files

📝 frontend/public/openapi.json (+24 -0)
📝 frontend/src/generated/examples.ts (+5 -0)
📝 frontend/src/generated/schemas.ts (+19 -0)
📝 frontend/src/generated/types.ts (+3 -0)
📝 frontend/src/generated/zod.ts (+3 -0)
📝 frontend/src/lib/remark/remarkVariables.ts (+1 -0)
📝 frontend/src/lib/xray/inbound-form-adapter.ts (+4 -0)
📝 frontend/src/models/dbinbound.ts (+2 -0)
📝 frontend/src/pages/clients/ClientInfoModal.tsx (+15 -2)
📝 frontend/src/pages/inbounds/form/InboundFormModal.tsx (+11 -0)
📝 frontend/src/pages/inbounds/list/InboundList.tsx (+56 -4)
📝 frontend/src/pages/inbounds/list/types.ts (+1 -0)
📝 frontend/src/schemas/api/inbound.ts (+2 -0)
📝 frontend/src/schemas/client.ts (+4 -0)
📝 frontend/src/schemas/forms/inbound-form.ts (+1 -0)
📝 frontend/src/test/__snapshots__/inbound-full.test.ts.snap (+8 -0)
📝 internal/database/db.go (+27 -0)
➕ internal/database/db_backfill_test.go (+73 -0)
📝 internal/database/model/client_global_traffic.go (+5 -1)
➕ internal/database/model/client_inbound_traffic.go (+28 -0)

...and 52 more files

📄 Description

Summary

Adds a per-inbound Traffic Multiplier that scales how fast a client's real traffic draws down their quota — so operators can price premium tunnels (multiplier > 1) and economy tunnels (< 1) differently, with the rate made visible to the end user. Default 1 is fully behaviour-preserving.

Billing is exact and fair across inbounds: each (client, inbound) pair is metered separately, each slice is multiplied by its inbound's multiplier, and the slices are summed. Worked example — a client on a 2× and a 0.5× inbound who moves 50 GB and 30 GB is billed 50×2 + 30×0.5 = 115 GB against quota while Real stays 80 GB.

How it works

  • Real Traffic = bytes actually moved (unchanged metering). Billed Traffic = Real after each inbound's multiplier, summed — the number quota is enforced against.
  • Xray meters usage per client-email (summed across inbounds), so exact per-inbound billing needs per-attachment metering. Each (client, inbound) is given its own Xray accounting identity "<inboundId>::<email>"; the suffix is an internal detail and is stripped back to the logical email everywhere else (IP-limit grouping, online detection, subscriptions, UI).
  • Non-retroactive: Billed is accrued at the multiplier in force at each poll, so changing an inbound's multiplier never re-bills past usage.
  • Multi-node: the multiplier rides to nodes as an inbound field; each hosting panel bills its own slice; the master sums Real + Billed across the fleet (the node→master fold and the master→node enforcement push both carry Billed). Old nodes degrade safely to 1×.

Feature commits (one per phase)

  1. Phase 0 — schema: Inbound.multiplier (0.1–100, default 1), new client_inbound_traffics per-attachment table, billed_up/billed_down on client/node/global traffic, idempotent backfill (Billed = Real for existing rows).
  2. Phase 1 — per-attachment metering: encode identity at config build + live AddUser/RemoveUser; decode on the stats path; accrue Real per attachment + Billed into the per-client aggregate.
  3. Phase 2 — enforce quota on Billed (client depletion predicates, incl. the cross-panel push); zero Billed + clear the per-tunnel breakdown on every reset/renew/delete. Detach retains Billed (no refund).
  4. Phase 3 — decode the per-attachment identity in the IP-limit and online-detection paths so grouping stays per-client.
  5. Phase 4 — propagate Billed + the multiplier across the node fleet.
  6. Phase 5 — UI + {MULTIPLIER} subscription token: inbound form field, client modal Real-vs-Billed, an inbounds-list multiplier filter (range buckets + exact values), full localization across all 13 locales, regenerated codegen.

Code review — two max-effort rounds

The change was put through two rounds of multi-agent, recall-oriented review (many independent finder angles → adversarial verification → gap sweep), each landing as one additive fix commit. No findings were left unaddressed.

Round 1 — fix(traffic): address ultra-review findings

  • Spurious full Xray restarts (HIGH regression). RemoveUser now sends the encoded "<inboundId>::<email>", but the "User not found" already-removed idempotency checks still compared the logical email, so the benign case forced a full core restart (dropping every live connection) on each poll. Now matches the bare "not found" substring at all 5 sites.
  • Multi-node version skew. An old-build node reports no Billed (decodes to 0); the node→master fold now falls back to Real (a neutral 1×) so a node-only client's Billed enforcement still fires.
  • Real-vs-Billed display consistency. Subscription tokens, clients-page exhausted buckets, per-node depleted/active counts, and the /get/:email usedTraffic field all switched to Billed, so what's shown agrees with when service is actually cut.
  • Node multiplier mirrored on update (not just first create) — keeps {MULTIPLIER} and the list filter fresh.
  • External-inform webhook + dashboard WS aggregate the per-attachment slice back to one row per email (preserves the existing per-client shape for consumers).
  • DelInbound drops the inbound's client_inbound_traffics rows — no orphan leak / id-reuse double-count.

Round 2 — fix(traffic): close ultra-review gaps (upgrade double-bill, Real-vs-Billed)

  • Multi-node upgrade double-bill (HIGH). backfillBilledTraffic seeded Billed on client_traffics but not the per-node delta baseline node_client_traffics. AutoMigrate adds billed_* defaulting to 0 while up/down keep their pre-upgrade totals, so the first node-sync folded deltaBilled = canon.Billed − 0 (the node's entire history) on top of the already-backfilled client row — one-time doubling Billed for every node client and instantly depleting any whose quota lay below it. Now seeds the node baseline too. (client_global_traffics needs none: overwritten per push and folded with MAX, so a stale 0 can't lower anything.)
  • Clients page read Real where enforcement reads Billed. The status buckets (depleted/active/expiring) and the "remaining" sort used Up+Down, contradicting the summary badge and the client's actual cut-off state on any non-1× inbound. Switched to Billed. (The usage-range filter and "traffic" sort stay Real — they mean bytes moved; inbound-level depletion stays Real — inbounds have no multiplier.)
  • Subscription surfaces reported Real against a Billed quota. The Subscription-Userinfo header (raw + clash + json), the public info page, and the aggregate that feeds them now carry/report Billed, so total − used equals what enforcement cuts on and they agree with the already-Billed remark tokens.
  • Telegram "deplete soon" detection used Total − (Up+Down); the two client checks switched to Billed.
  • IP-limit live disconnect only kicked the one inbound resolved by email; for a client on several inbounds the over-limit connection survived on the others (fail2ban still banned the IP fleet-wide). Now force-drops the client on every inbound it is attached to.
  • Inbounds-list multiplier filter could blank the list with no way to clear once the last non-1× inbound became 1×; the predicate now only applies while its control is shown.

Testing

  • Go: per-attachment accrual (the 115 GB example), non-retroactive billing on a mid-cycle multiplier change, Billed-based depletion, reset clearing Billed + attachment rows, node→master Billed fold, the upgrade node-baseline backfill (seed / idempotent / reset), Billed-based clients-page buckets + remaining sort, per-email sub aggregation carrying Billed, getInboundsByEmail returning every attachment, identity encode/decode round-trip (incl. an embedded :: and legacy passthrough), {MULTIPLIER} token rendering. go build ./... and the full go test -race -shuffle=on ./internal/... suite pass.
  • Frontend: npm ci, gen (no codegen diff), typecheck, lint, test (572 pass), build — all green.
  • Locales: all 13 translation files validated as JSON with full key parity (multiplier + billed labels present everywhere).

Upgrade notes

  • One-time Xray stats rebaseline on first boot (the metered email string changes); no Real is lost and aggregates persist. Billed backfills to Real on both client_traffics and the per-node baseline since every existing inbound was effectively 1×.
  • Nodes should be updated to a build with this change to bill their inbounds at the configured multiplier; until then a node's inbounds bill at 1× (and old nodes degrade safely).

Still open (follow-up, not a bug)

  • A per-tunnel breakdown drill-down UI: client_inbound_traffics already persists per-attachment Real + Billed, but the client modal currently surfaces only per-client totals. A read endpoint + modal table would expose the split.

🔄 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/5507 **Author:** [@nima1024m](https://github.com/nima1024m) **Created:** 6/23/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `feat/inbound-traffic-multiplier` --- ### 📝 Commits (10+) - [`4562072`](https://github.com/MHSanaei/3x-ui/commit/456207214c2f450248d5400fc9473b28804f83ba) feat(traffic): add Traffic Multiplier schema and Billed columns - [`d875c0e`](https://github.com/MHSanaei/3x-ui/commit/d875c0e1ed98d7568304d29f458f866eb2e49b18) feat(traffic): meter per attachment and accrue Billed - [`2731b7a`](https://github.com/MHSanaei/3x-ui/commit/2731b7a527de3d5173e35264a75c963d1f243019) feat(traffic): enforce quota on Billed; clear it on reset/renew - [`342beb7`](https://github.com/MHSanaei/3x-ui/commit/342beb70cb9ecaf5524b7aba1a04bfc8f2462ca7) feat(traffic): decode per-attachment identity in IP-limit and online paths - [`0de1eb3`](https://github.com/MHSanaei/3x-ui/commit/0de1eb321da3842fd34874195a718abe5730d70f) feat(traffic): propagate Billed and the multiplier across the node fleet - [`a863913`](https://github.com/MHSanaei/3x-ui/commit/a8639131c34a83227f4b19b786726121441a4929) feat(traffic): surface the multiplier in the panel UI and subscriptions - [`5a96df4`](https://github.com/MHSanaei/3x-ui/commit/5a96df442b7d2cfcaeaaf6a202b90d526408074e) fix(traffic): address ultra-review findings - [`41248e5`](https://github.com/MHSanaei/3x-ui/commit/41248e57d5077bc6b8069c7d904b7bf69602f400) fix(traffic): close ultra-review gaps (upgrade double-bill, Real-vs-Billed) - [`8b780fb`](https://github.com/MHSanaei/3x-ui/commit/8b780fbd102d13edaffe11194caec2fcc747d13c) Merge origin/main into feat/inbound-traffic-multiplier - [`21c985a`](https://github.com/MHSanaei/3x-ui/commit/21c985adcb09ce0e03ba50c5d04fb094a6e4dd70) Merge origin/main (v3.4.0) into feat/inbound-traffic-multiplier ### 📊 Changes **72 files changed** (+1448 additions, -130 deletions) <details> <summary>View changed files</summary> 📝 `frontend/public/openapi.json` (+24 -0) 📝 `frontend/src/generated/examples.ts` (+5 -0) 📝 `frontend/src/generated/schemas.ts` (+19 -0) 📝 `frontend/src/generated/types.ts` (+3 -0) 📝 `frontend/src/generated/zod.ts` (+3 -0) 📝 `frontend/src/lib/remark/remarkVariables.ts` (+1 -0) 📝 `frontend/src/lib/xray/inbound-form-adapter.ts` (+4 -0) 📝 `frontend/src/models/dbinbound.ts` (+2 -0) 📝 `frontend/src/pages/clients/ClientInfoModal.tsx` (+15 -2) 📝 `frontend/src/pages/inbounds/form/InboundFormModal.tsx` (+11 -0) 📝 `frontend/src/pages/inbounds/list/InboundList.tsx` (+56 -4) 📝 `frontend/src/pages/inbounds/list/types.ts` (+1 -0) 📝 `frontend/src/schemas/api/inbound.ts` (+2 -0) 📝 `frontend/src/schemas/client.ts` (+4 -0) 📝 `frontend/src/schemas/forms/inbound-form.ts` (+1 -0) 📝 `frontend/src/test/__snapshots__/inbound-full.test.ts.snap` (+8 -0) 📝 `internal/database/db.go` (+27 -0) ➕ `internal/database/db_backfill_test.go` (+73 -0) 📝 `internal/database/model/client_global_traffic.go` (+5 -1) ➕ `internal/database/model/client_inbound_traffic.go` (+28 -0) _...and 52 more files_ </details> ### 📄 Description ## Summary Adds a per-inbound **Traffic Multiplier** that scales how fast a client's real traffic draws down their quota — so operators can price premium tunnels (multiplier > 1) and economy tunnels (< 1) differently, with the rate made visible to the end user. Default `1` is fully behaviour-preserving. Billing is **exact and fair across inbounds**: each `(client, inbound)` pair is metered separately, each slice is multiplied by its inbound's multiplier, and the slices are summed. Worked example — a client on a 2× and a 0.5× inbound who moves 50 GB and 30 GB is billed `50×2 + 30×0.5 = 115 GB` against quota while **Real** stays 80 GB. ## How it works - **Real Traffic** = bytes actually moved (unchanged metering). **Billed Traffic** = Real after each inbound's multiplier, summed — the number quota is enforced against. - Xray meters usage per client-email (summed across inbounds), so exact per-inbound billing needs per-attachment metering. Each `(client, inbound)` is given its own Xray accounting identity `"<inboundId>::<email>"`; the suffix is an internal detail and is stripped back to the logical email everywhere else (IP-limit grouping, online detection, subscriptions, UI). - **Non-retroactive**: Billed is accrued at the multiplier in force at each poll, so changing an inbound's multiplier never re-bills past usage. - **Multi-node**: the multiplier rides to nodes as an inbound field; each hosting panel bills its own slice; the master sums Real + Billed across the fleet (the node→master fold and the master→node enforcement push both carry Billed). Old nodes degrade safely to 1×. ## Feature commits (one per phase) 1. **Phase 0** — schema: `Inbound.multiplier` (0.1–100, default 1), new `client_inbound_traffics` per-attachment table, `billed_up/billed_down` on client/node/global traffic, idempotent backfill (Billed = Real for existing rows). 2. **Phase 1** — per-attachment metering: encode identity at config build + live AddUser/RemoveUser; decode on the stats path; accrue Real per attachment + Billed into the per-client aggregate. 3. **Phase 2** — enforce quota on Billed (client depletion predicates, incl. the cross-panel push); zero Billed + clear the per-tunnel breakdown on every reset/renew/delete. Detach retains Billed (no refund). 4. **Phase 3** — decode the per-attachment identity in the IP-limit and online-detection paths so grouping stays per-client. 5. **Phase 4** — propagate Billed + the multiplier across the node fleet. 6. **Phase 5** — UI + `{MULTIPLIER}` subscription token: inbound form field, client modal Real-vs-Billed, an inbounds-list multiplier filter (range buckets + exact values), full localization across all 13 locales, regenerated codegen. ## Code review — two max-effort rounds The change was put through two rounds of multi-agent, recall-oriented review (many independent finder angles → adversarial verification → gap sweep), each landing as one additive fix commit. No findings were left unaddressed. ### Round 1 — `fix(traffic): address ultra-review findings` - **Spurious full Xray restarts (HIGH regression).** `RemoveUser` now sends the encoded `"<inboundId>::<email>"`, but the "User not found" already-removed idempotency checks still compared the *logical* email, so the benign case forced a full core restart (dropping every live connection) on each poll. Now matches the bare `"not found"` substring at all 5 sites. - **Multi-node version skew.** An old-build node reports no Billed (decodes to 0); the node→master fold now falls back to Real (a neutral 1×) so a node-only client's Billed enforcement still fires. - **Real-vs-Billed display consistency.** Subscription tokens, clients-page exhausted buckets, per-node depleted/active counts, and the `/get/:email` `usedTraffic` field all switched to Billed, so what's shown agrees with when service is actually cut. - **Node multiplier mirrored on update** (not just first create) — keeps `{MULTIPLIER}` and the list filter fresh. - **External-inform webhook + dashboard WS** aggregate the per-attachment slice back to one row per email (preserves the existing per-client shape for consumers). - **`DelInbound`** drops the inbound's `client_inbound_traffics` rows — no orphan leak / id-reuse double-count. ### Round 2 — `fix(traffic): close ultra-review gaps (upgrade double-bill, Real-vs-Billed)` - **Multi-node upgrade double-bill (HIGH).** `backfillBilledTraffic` seeded Billed on `client_traffics` but not the per-node delta baseline `node_client_traffics`. AutoMigrate adds `billed_*` defaulting to 0 while `up/down` keep their pre-upgrade totals, so the first node-sync folded `deltaBilled = canon.Billed − 0` (the node's entire history) on top of the already-backfilled client row — one-time doubling Billed for every node client and instantly depleting any whose quota lay below it. Now seeds the node baseline too. (`client_global_traffics` needs none: overwritten per push and folded with MAX, so a stale 0 can't lower anything.) - **Clients page read Real where enforcement reads Billed.** The status buckets (depleted/active/expiring) and the "remaining" sort used `Up+Down`, contradicting the summary badge and the client's actual cut-off state on any non-1× inbound. Switched to Billed. (The usage-range filter and "traffic" sort stay Real — they mean bytes moved; inbound-level depletion stays Real — inbounds have no multiplier.) - **Subscription surfaces reported Real against a Billed quota.** The Subscription-Userinfo header (raw + clash + json), the public info page, and the aggregate that feeds them now carry/report Billed, so `total − used` equals what enforcement cuts on and they agree with the already-Billed remark tokens. - **Telegram "deplete soon" detection** used `Total − (Up+Down)`; the two client checks switched to Billed. - **IP-limit live disconnect** only kicked the one inbound resolved by email; for a client on several inbounds the over-limit connection survived on the others (fail2ban still banned the IP fleet-wide). Now force-drops the client on **every** inbound it is attached to. - **Inbounds-list multiplier filter** could blank the list with no way to clear once the last non-1× inbound became 1×; the predicate now only applies while its control is shown. ## Testing - **Go:** per-attachment accrual (the 115 GB example), non-retroactive billing on a mid-cycle multiplier change, Billed-based depletion, reset clearing Billed + attachment rows, node→master Billed fold, the upgrade node-baseline backfill (seed / idempotent / reset), Billed-based clients-page buckets + remaining sort, per-email sub aggregation carrying Billed, `getInboundsByEmail` returning every attachment, identity encode/decode round-trip (incl. an embedded `::` and legacy passthrough), `{MULTIPLIER}` token rendering. `go build ./...` and the full `go test -race -shuffle=on ./internal/...` suite pass. - **Frontend:** `npm ci`, `gen` (no codegen diff), `typecheck`, `lint`, `test` (572 pass), `build` — all green. - **Locales:** all 13 translation files validated as JSON with full key parity (multiplier + billed labels present everywhere). ## Upgrade notes - One-time Xray stats rebaseline on first boot (the metered email string changes); no Real is lost and aggregates persist. Billed backfills to Real on both `client_traffics` and the per-node baseline since every existing inbound was effectively 1×. - Nodes should be updated to a build with this change to bill their inbounds at the configured multiplier; until then a node's inbounds bill at 1× (and old nodes degrade safely). ## Still open (follow-up, not a bug) - A per-tunnel breakdown **drill-down UI**: `client_inbound_traffics` already persists per-attachment Real + Billed, but the client modal currently surfaces only per-client totals. A read endpoint + modal table would expose the split. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:04:56 +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#5908
No description provided.