From 3025efad065a9ae3d7491faebaf7f81b0aa70b9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=AE=80=E7=9B=B4=E8=A0=A2=E4=B8=B6?= Date: Thu, 24 Sep 2026 08:32:42 -0400 Subject: [PATCH] feat: add load-balance hash-key to pin a session on the inbound user (#3133) --- adapter/outboundgroup/loadbalance.go | 59 ++++++++- adapter/outboundgroup/loadbalance_test.go | 140 ++++++++++++++++++++++ docs/config.yaml | 9 ++ 3 files changed, 202 insertions(+), 6 deletions(-) create mode 100644 adapter/outboundgroup/loadbalance_test.go diff --git a/adapter/outboundgroup/loadbalance.go b/adapter/outboundgroup/loadbalance.go index 88d4674a0..e6439042f 100644 --- a/adapter/outboundgroup/loadbalance.go +++ b/adapter/outboundgroup/loadbalance.go @@ -21,6 +21,7 @@ import ( type LoadBalanceOption struct { Strategy string `group:"strategy,omitempty"` + HashKey string `group:"hash-key,omitempty"` } type LoadBalance struct { @@ -34,6 +35,10 @@ type LoadBalance struct { type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy var errStrategy = errors.New("unsupported strategy") +var errHashKey = errors.New("unsupported hash-key") + +// keyFn derives the value a hashing strategy pins a request on. +type keyFn = func(metadata *C.Metadata) string func getKey(metadata *C.Metadata) string { if metadata == nil { @@ -68,6 +73,39 @@ func getKeyWithSrcAndDst(metadata *C.Metadata) string { return fmt.Sprintf("%s%s", src, dst) } +// getKeyWithInUser pins on the authenticated inbound user instead of on an +// address. Both address-derived keys assume one client's traffic to one +// destination is one unit of work, which is false for a client whose single +// unit of work walks several destinations: the hash moves with the host, and +// the egress IP changes underneath a session the destination is tracking. +// The inbound user is the only identity the client itself controls, and +// `IN-USER` rules already match on it -- hence the option value `in-user`, +// which names the same thing those rules do. An unauthenticated request keeps +// the strategy's own key rather than collapsing every such request onto one +// node. +func getKeyWithInUser(fallback keyFn) keyFn { + return func(metadata *C.Metadata) string { + if metadata != nil && metadata.InUser != "" { + return metadata.InUser + } + + return fallback(metadata) + } +} + +// hashKey resolves the `hash-key` option into a decorator over whichever key +// the chosen strategy derives by default. +func hashKey(name string) (func(keyFn) keyFn, error) { + switch name { + case "": + return func(fn keyFn) keyFn { return fn }, nil + case "in-user": + return getKeyWithInUser, nil + } + + return nil, fmt.Errorf("%w: %s", errHashKey, name) +} + func jumpHash(key uint64, buckets int32) int32 { var b, j int64 @@ -155,10 +193,10 @@ func strategyRoundRobin(url string) strategyFn { } } -func strategyConsistentHashing(url string) strategyFn { +func strategyConsistentHashing(url string, keyOf keyFn) strategyFn { maxRetry := 5 return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy { - key := utils.MapHash(getKey(metadata)) + key := utils.MapHash(keyOf(metadata)) buckets := int32(len(proxies)) for i := 0; i < maxRetry; i, key = i+1, key+1 { idx := jumpHash(key, buckets) @@ -179,14 +217,14 @@ func strategyConsistentHashing(url string) strategyFn { } } -func strategyStickySessions(url string) strategyFn { +func strategyStickySessions(url string, keyOf keyFn) strategyFn { ttl := time.Minute * 10 maxRetry := 5 lruCache := lru.New[uint64, int]( lru.WithAge[uint64, int](int64(ttl.Seconds())), lru.WithSize[uint64, int](1000)) return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy { - key := utils.MapHash(getKeyWithSrcAndDst(metadata)) + key := utils.MapHash(keyOf(metadata)) length := len(proxies) idx, has := lruCache.Get(key) if !has || idx >= length { @@ -249,13 +287,22 @@ func (lb *LoadBalance) Now() string { func NewLoadBalance(option GroupCommonOption, loadBalanceOption LoadBalanceOption, emptyFallback C.Proxy, providers []P.ProxyProvider) (lb *LoadBalance, err error) { var strategyFn strategyFn + withKey, err := hashKey(loadBalanceOption.HashKey) + if err != nil { + return nil, err + } switch loadBalanceOption.Strategy { case "", "consistent-hashing": - strategyFn = strategyConsistentHashing(option.URL) + strategyFn = strategyConsistentHashing(option.URL, withKey(getKey)) case "round-robin": + // Rejected rather than ignored: round-robin hashes nothing, so a + // hash-key here means the config expects stickiness it will not get. + if loadBalanceOption.HashKey != "" { + return nil, fmt.Errorf("%w: round-robin does not hash", errHashKey) + } strategyFn = strategyRoundRobin(option.URL) case "sticky-sessions": - strategyFn = strategyStickySessions(option.URL) + strategyFn = strategyStickySessions(option.URL, withKey(getKeyWithSrcAndDst)) default: return nil, fmt.Errorf("%w: %s", errStrategy, loadBalanceOption.Strategy) } diff --git a/adapter/outboundgroup/loadbalance_test.go b/adapter/outboundgroup/loadbalance_test.go new file mode 100644 index 000000000..bcd8ebbee --- /dev/null +++ b/adapter/outboundgroup/loadbalance_test.go @@ -0,0 +1,140 @@ +package outboundgroup + +import ( + "net/netip" + "testing" + + "github.com/metacubex/mihomo/adapter" + "github.com/metacubex/mihomo/adapter/outbound" + C "github.com/metacubex/mihomo/constant" + + "github.com/stretchr/testify/require" +) + +const testUrl = "https://www.gstatic.com/generate_204" + +func balancedProxies(count int) []C.Proxy { + proxies := make([]C.Proxy, 0, count) + for i := 0; i < count; i++ { + proxies = append(proxies, adapter.NewProxy(outbound.NewDirect())) + } + return proxies +} + +// The proxies are indistinguishable by name, so identity is the pointer. +func indexOf(t *testing.T, proxies []C.Proxy, selected C.Proxy) int { + t.Helper() + for i, proxy := range proxies { + if proxy == selected { + return i + } + } + require.Fail(t, "selected proxy is not a member of the group") + return -1 +} + +func request(user, host string) *C.Metadata { + return &C.Metadata{ + NetWork: C.TCP, + Host: host, + DstPort: 443, + SrcIP: netip.MustParseAddr("127.0.0.1"), + InUser: user, + } +} + +// One unit of work walking several destinations is the case both address-derived +// keys get wrong: the group is meant to hold that work on one egress, and the +// default key moves it as soon as the host changes. +func TestLoadBalanceHashKeyInUserSurvivesADestinationChange(t *testing.T) { + proxies := balancedProxies(8) + hosts := []string{"a.example.com", "b.example.org", "c.example.net", "d.example.io"} + + byUser := strategyConsistentHashing(testUrl, getKeyWithInUser(getKey)) + pinned := indexOf(t, proxies, byUser(proxies, request("job-1", hosts[0]), false)) + for _, host := range hosts { + selected := byUser(proxies, request("job-1", host), false) + require.Equal(t, pinned, indexOf(t, proxies, selected), + "hash-key: user must ignore the destination") + } + + byDestination := strategyConsistentHashing(testUrl, getKey) + seen := map[int]bool{} + for _, host := range hosts { + seen[indexOf(t, proxies, byDestination(proxies, request("job-1", host), false))] = true + } + require.Greater(t, len(seen), 1, + "the default key is expected to move with the destination") +} + +// Pinning must not become a single node: distinct users still spread. +func TestLoadBalanceHashKeyInUserSpreadsUsers(t *testing.T) { + proxies := balancedProxies(8) + strategy := strategyConsistentHashing(testUrl, getKeyWithInUser(getKey)) + + seen := map[int]bool{} + for _, user := range []string{"job-1", "job-2", "job-3", "job-4", "job-5", "job-6"} { + selected := strategy(proxies, request(user, "a.example.com"), false) + seen[indexOf(t, proxies, selected)] = true + } + require.Greater(t, len(seen), 1) +} + +// Sticky sessions keys on source and destination; a client behind one source +// address cannot separate its own concurrent jobs without a supplied identity. +func TestLoadBalanceHashKeyInUserSeparatesJobsSharingASourceAddress(t *testing.T) { + proxies := balancedProxies(8) + strategy := strategyStickySessions(testUrl, getKeyWithInUser(getKeyWithSrcAndDst)) + + first := indexOf(t, proxies, strategy(proxies, request("job-1", "a.example.com"), false)) + require.Equal(t, first, + indexOf(t, proxies, strategy(proxies, request("job-1", "b.example.org"), false))) + + shared := strategyStickySessions(testUrl, getKeyWithSrcAndDst) + require.Equal(t, + indexOf(t, proxies, shared(proxies, request("job-1", "a.example.com"), false)), + indexOf(t, proxies, shared(proxies, request("job-2", "a.example.com"), false)), + "without a supplied key the two jobs are one session") +} + +// An unauthenticated request keeps the strategy's own key. Returning a constant +// instead would herd every anonymous request onto one member. +func TestLoadBalanceHashKeyInUserFallsBackWhenUnauthenticated(t *testing.T) { + keyed := getKeyWithInUser(getKey) + require.Equal(t, "example.com", keyed(request("", "a.example.com"))) + require.Equal(t, "job-1", keyed(request("job-1", "a.example.com"))) + require.Equal(t, getKey(nil), keyed(nil)) +} + +// The option name is the contract with the config file, and nothing else here +// exercises it: every other test reaches the decorator directly, so renaming +// the case would leave them all green while `hash-key: in-user` stopped working. +func TestLoadBalanceHashKeyResolvesTheOptionName(t *testing.T) { + withInUser, err := hashKey("in-user") + require.NoError(t, err) + require.Equal(t, "job-1", withInUser(getKey)(request("job-1", "a.example.com"))) + + identity, err := hashKey("") + require.NoError(t, err) + require.Equal(t, getKey(request("job-1", "a.example.com")), + identity(getKey)(request("job-1", "a.example.com"))) +} + +func TestLoadBalanceHashKeyRejectsUnusableConfigs(t *testing.T) { + _, err := hashKey("session") + require.ErrorIs(t, err, errHashKey) + + // `user` was the name this option carried before review. Rejecting it keeps + // the rename honest: without this the case above could still read `user` + // and every test here would stay green. + _, err = hashKey("user") + require.ErrorIs(t, err, errHashKey) + + _, err = NewLoadBalance(GroupCommonOption{Name: "lb"}, + LoadBalanceOption{Strategy: "round-robin", HashKey: "in-user"}, nil, nil) + require.ErrorIs(t, err, errHashKey) + + _, err = NewLoadBalance(GroupCommonOption{Name: "lb"}, + LoadBalanceOption{Strategy: "consistent-hashing", HashKey: "nonsense"}, nil, nil) + require.ErrorIs(t, err, errHashKey) +} diff --git a/docs/config.yaml b/docs/config.yaml index b57f64616..51179386f 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1790,6 +1790,15 @@ proxy-groups: url: "https://cp.cloudflare.com/generate_204" interval: 300 # strategy: consistent-hashing # 可选 round-robin 和 sticky-sessions + # hash-key: in-user # 可选,仅 consistent-hashing 和 sticky-sessions 支持; + # # round-robin 不做哈希,配置它会报错而不是被忽略。 + # # 只改变「拿什么值去哈希」,不改变策略拿到哈希值之后如何选节点; + # # 不填时行为与旧版完全一致。 + # # in-user 用 inbound 的认证用户名作 key(与 IN-USER 规则读取的是 + # # 同一个字段),它不随目标地址变化,因此一件跨多个域名的任务不会 + # # 中途换节点、换出口 IP。未认证的请求回退到该策略原本的 key。 + # # 两种策略给出的一致性时长不同(前者永久、后者 10 分钟), + # # 取舍见 PR #3133。 # select 用户自行选择节点 - name: Proxy