feat(sub): leastLoad member weights for subscription balancers (#6304)

* feat(model): add MemberWeights to SubBalancer

Per-inbound leastLoad weights, stored with the same gorm json serializer
as InboundIds so AutoMigrate adds the text column on every dialect
(postgresModelSettled sees the missing column and re-runs). Absent
entries mean weight 1.0; only meaningful for strategy leastLoad.

* feat(sub): accept memberWeights on the sub-balancer API

Parsed as one JSON form field (gin cannot bind bracket-keyed maps from
urlencoded bodies). validate() rejects weights under any strategy but
leastLoad — xray would silently ignore costs there, so storing them
would pretend a knob exists. Non-positive weights error instead of
defaulting: a zero usually means a typo'd "never pick this node".
Entries for inbounds no longer selected are dropped on save.

* feat(sub): emit leastLoad strategy costs from member weights

costs[] is built after the tagging loop reuses the exact retagged tags
(bal-N-protocol[-k]) and each member's owning inbound id. Members
without a configured weight default to 1.0, but costs are omitted
entirely unless at least one explicit weight survives — an all-1.0
array would bloat every subscription response for no effect.

* feat(sub-balancers): leastLoad member weight inputs

Weight fields render only under leastLoad and hide on strategy change
without dropping their values, so an accidental toggle away and back
loses nothing until save; non-leastLoad submits strip them entirely
because xray would ignore costs. Weights travel as one JSON form field
(gin cannot bind bracket-keyed maps) and every locale gets the three
new keys in the same commit per the dead-keys rule.

* docs(api): document memberWeights on sub-balancers

leastLoad-only JSON form field; update notes that omitting it clears
stored weights. Regenerated openapi artifacts via make gen + the docs
copy/gen:api step nothing checks automatically.

* fix(api-docs): use the allowed object ParamType for memberWeights

* fix(sub-balancers): cap the member-weight list height

Many selected inbounds pushed the modal body past the viewport. The
weight rows now scroll inside a 220px viewport, mirroring the inbound
picker's listHeight so both lists read the same.

* fix(sub): anchor leastLoad cost matches to exact member tags

Verified against xray-core: without regexp, WeightManager matches costs
by substring (strings.Index), so the bare tag "bal-1-vless" also hits
the deduplicated "bal-1-vless-2" and both members get the first
entry's weight. Anchored ^tag$ regexps make every cost entry match only
its own member. Also confirmed value<=0 makes xray derive a weight from
the first digit of the matched tag — validating weights > 0 server-side
was the right call.

* fix(sub-balancers): keep member weights across the enabled toggle

The table's toggleEnabled re-posted a full-row payload without
memberWeights, and the update path treats an absent key as "erase" —
flipping the switch silently dropped every configured weight. Round-trip
the stored weights through the toggle payload, and prove persistence
with a re-Get in the weight-validation test (the returned struct alone
would stay green even if Save skipped the column).

* fix(sub-balancers): address review on member weights

- omitempty on MemberWeights: the panel sends null for every pre-existing
  and non-leastLoad balancer, which failed the hand-written zod response
  schema on every fetch (zod .optional() accepts undefined only; switched
  to .nullish() per repo convention) and drifted the generated contract.
  Regenerated openapi artifacts + docs copy + MDX.
- Bound weights to the positive float32 range: xray decodes costs as
  float32, so an over-range value makes clients reject the whole
  subscription document and an underflow decays to the tag-digit
  fallback weight. Tests for both directions.
- Trim six comment blocks to the 2-line cap from CLAUDE.md.

---------

Co-authored-by: DIMFLIX <dimflix@users.noreply.github.com>
This commit is contained in:
DIMFLIX
2026-09-02 21:21:27 +03:00
committed by GitHub
parent f9cfd87cb2
commit 7100fbcd08
32 changed files with 525 additions and 15 deletions
+43 -1
View File
@@ -351,12 +351,49 @@ func balancerMemberSuffix(protocol string) string {
return protocol
}
// balMember is one retagged member outbound and the inbound it came from.
type balMember struct {
tag string
inboundId int
}
// leastLoadCosts builds xray's static strategy costs: higher value = picked
// less often; nil unless a member carries an explicit weight (all-1.0 bloat).
func leastLoadCosts(balancer *model.SubBalancer, members []balMember) []any {
if balancer.Strategy != "leastLoad" || len(members) == 0 || len(balancer.MemberWeights) == 0 {
return nil
}
costs := make([]any, 0, len(members))
configured := false
for _, m := range members {
value := 1.0
if weight, ok := balancer.MemberWeights[m.inboundId]; ok && weight > 0 {
value = weight
configured = true
}
// Anchored regexp: plain cost matching is substring-based in xray, so
// an unanchored "bal-1-vless" would also swallow "bal-1-vless-2".
costs = append(costs, map[string]any{
"regexp": true,
"match": "^" + m.tag + "$",
"value": value,
})
}
if !configured {
return nil
}
return costs
}
// buildBalancerConfig assembles the balancer profile: members retagged under a
// per-balancer prefix, a routing.balancers entry, and (for leastPing/leastLoad) an observatory.
func (s *SubJsonService) buildBalancerConfig(balancer *model.SubBalancer, entries []subConfigEntry, entryProxies [][]map[string]any) json_util.RawMessage {
prefix := fmt.Sprintf("bal-%d-", balancer.Id)
usedTags := make(map[string]bool)
var proxies []json_util.RawMessage
// Members in emission order with their owning inbound, so costs[] can
// reference the exact retagged tags assigned here.
var members []balMember
var firstTag string
// entryProxies is the pre-extracted proxy outbounds per entry; kind!=0 rows
// have none. Clone before retagging so the cached map stays reusable.
@@ -375,6 +412,7 @@ func (s *SubJsonService) buildBalancerConfig(balancer *model.SubBalancer, entrie
member := maps.Clone(outbound)
member["tag"] = tag
if raw, err := json.MarshalIndent(member, "", " "); err == nil {
members = append(members, balMember{tag: tag, inboundId: entry.id})
if firstTag == "" {
firstTag = tag
}
@@ -411,10 +449,14 @@ func (s *SubJsonService) buildBalancerConfig(balancer *model.SubBalancer, entrie
}
routing["rules"] = rules
isObservatory := balancer.Strategy == "leastPing" || balancer.Strategy == "leastLoad"
strategyEntry := map[string]any{"type": balancer.Strategy}
if costs := leastLoadCosts(balancer, members); costs != nil {
strategyEntry["settings"] = map[string]any{"costs": costs}
}
balancerEntry := map[string]any{
"tag": subBalancerTag,
"selector": []string{prefix},
"strategy": map[string]any{"type": balancer.Strategy},
"strategy": strategyEntry,
}
if isObservatory && firstTag != "" {
// With all probes failing, route to the first member instead of
+88
View File
@@ -420,3 +420,91 @@ func observatoryPingConfig(t *testing.T, docs []map[string]any, remarks string)
ping, _ := obs["pingConfig"].(map[string]any)
return ping
}
func balancerStrategy(t *testing.T, docs []map[string]any, remarks string) map[string]any {
t.Helper()
doc := findDocByRemarks(docs, remarks)
if doc == nil {
t.Fatalf("balancer doc %q missing", remarks)
}
routing, _ := doc["routing"].(map[string]any)
balancers, _ := routing["balancers"].([]any)
strategy, _ := balancers[0].(map[string]any)["strategy"].(map[string]any)
return strategy
}
// leastLoad with configured weights must emit strategy.settings.costs keyed by
// the retagged member tags; members without a weight count as 1.0.
func TestSubJson_BalancerLeastLoadCosts(t *testing.T) {
seedSubDB(t)
fast := seedSubInbound(t, "s1", "fast", 4791, 1, wsTLSStream)
slow := seedSubInbound(t, "s1", "slow", 4792, 2, wsTLSStream)
seedSubBalancer(t, &model.SubBalancer{
Remark: "weighted", Strategy: "leastLoad", InboundIds: []int{fast.Id, slow.Id},
MemberWeights: map[int]float64{fast.Id: 0.2}, SortOrder: 1, Enabled: true,
})
js := NewSubJsonService("", "", "", NewSubService(""))
out, _, err := js.GetJson("s1", "req.example.com", true)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
strategy := balancerStrategy(t, parseSubJsonDocs(t, out), "weighted")
settings, _ := strategy["settings"].(map[string]any)
costs, _ := settings["costs"].([]any)
if len(costs) != 2 {
t.Fatalf("costs = %v, want 2 entries:\n%s", costs, out)
}
first, _ := costs[0].(map[string]any)
second, _ := costs[1].(map[string]any)
// Anchored regexp is required: xray's plain cost match is substring-based,
// so a bare "bal-1-vless" would also hit the deduplicated "bal-1-vless-2".
if first["regexp"] != true || first["match"] != "^bal-1-vless$" || first["value"] != 0.2 {
t.Fatalf("costs[0] = %v, want regexp ^bal-1-vless$ value=0.2", first)
}
if second["regexp"] != true || second["match"] != "^bal-1-vless-2$" || second["value"] != 1.0 {
t.Fatalf("costs[1] = %v, want regexp ^bal-1-vless-2$ value=1 (default)", second)
}
}
// leastLoad without any configured weight emits no settings at all.
func TestSubJson_BalancerLeastLoadWithoutWeightsOmitsCosts(t *testing.T) {
seedSubDB(t)
a := seedSubInbound(t, "s1", "a", 4801, 1, wsTLSStream)
b := seedSubInbound(t, "s1", "b", 4802, 2, wsTLSStream)
seedSubBalancer(t, &model.SubBalancer{
Remark: "plain", Strategy: "leastLoad", InboundIds: []int{a.Id, b.Id}, SortOrder: 1, Enabled: true,
})
js := NewSubJsonService("", "", "", NewSubService(""))
out, _, err := js.GetJson("s1", "req.example.com", true)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
strategy := balancerStrategy(t, parseSubJsonDocs(t, out), "plain")
if _, has := strategy["settings"]; has {
t.Fatalf("leastLoad without weights must not emit strategy.settings: %v", strategy["settings"])
}
}
// Emission-side guard independent of validate(): a non-leastLoad row written
// directly to the DB must still emit no costs — xray would ignore them.
func TestSubJson_BalancerCostsSkippedForNonLeastLoadStrategy(t *testing.T) {
seedSubDB(t)
a := seedSubInbound(t, "s1", "a", 4811, 1, wsTLSStream)
b := seedSubInbound(t, "s1", "b", 4812, 2, wsTLSStream)
seedSubBalancer(t, &model.SubBalancer{
Remark: "misconfig", Strategy: "random", InboundIds: []int{a.Id, b.Id},
MemberWeights: map[int]float64{a.Id: 0.5}, SortOrder: 1, Enabled: true,
})
js := NewSubJsonService("", "", "", NewSubService(""))
out, _, err := js.GetJson("s1", "req.example.com", true)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
strategy := balancerStrategy(t, parseSubJsonDocs(t, out), "misconfig")
if _, has := strategy["settings"]; has {
t.Fatalf("random balancer must never emit costs despite stored weights: %v", strategy)
}
}