github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/app/router/balancing.go (about)

     1  // +build !confonly
     2  
     3  package router
     4  
     5  import (
     6  	"v2ray.com/core/common/dice"
     7  	"v2ray.com/core/features/outbound"
     8  )
     9  
    10  type BalancingStrategy interface {
    11  	PickOutbound([]string) string
    12  }
    13  
    14  type RandomStrategy struct {
    15  }
    16  
    17  func (s *RandomStrategy) PickOutbound(tags []string) string {
    18  	n := len(tags)
    19  	if n == 0 {
    20  		panic("0 tags")
    21  	}
    22  
    23  	return tags[dice.Roll(n)]
    24  }
    25  
    26  type Balancer struct {
    27  	selectors []string
    28  	strategy  BalancingStrategy
    29  	ohm       outbound.Manager
    30  }
    31  
    32  func (b *Balancer) PickOutbound() (string, error) {
    33  	hs, ok := b.ohm.(outbound.HandlerSelector)
    34  	if !ok {
    35  		return "", newError("outbound.Manager is not a HandlerSelector")
    36  	}
    37  	tags := hs.Select(b.selectors)
    38  	if len(tags) == 0 {
    39  		return "", newError("no available outbounds selected")
    40  	}
    41  	tag := b.strategy.PickOutbound(tags)
    42  	if tag == "" {
    43  		return "", newError("balancing strategy returns empty tag")
    44  	}
    45  	return tag, nil
    46  }