You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.5 KiB

2 years ago
package selector
import (
"context"
"sync/atomic"
)
var (
_ Rebalancer = (*Default)(nil)
_ Builder = (*DefaultBuilder)(nil)
)
type Default struct {
2 years ago
NodeBuilder WeightedNodeBuilder
Balancer Balancer
2 years ago
nodes atomic.Value
2 years ago
}
func (d *Default) Select(ctx context.Context, opts ...SelectOption) (selected Node, done DoneFunc, err error) {
var (
options SelectOptions
candidates []WeightedNode
)
2 years ago
nodes, ok := d.nodes.Load().([]WeightedNode)
if !ok {
return nil, nil, ErrNoAvailable
}
for _, o := range opts {
o(&options)
}
2 years ago
if len(options.NodeFilters) > 0 {
newNodes := make([]Node, len(nodes))
for i, wc := range nodes {
newNodes[i] = wc
2 years ago
}
for _, filter := range options.NodeFilters {
newNodes = filter(ctx, newNodes)
}
candidates = make([]WeightedNode, len(newNodes))
for i, n := range newNodes {
candidates[i] = n.(WeightedNode)
2 years ago
}
} else {
candidates = nodes
2 years ago
}
wn, done, err := d.Balancer.Pick(ctx, candidates)
2 years ago
if err != nil {
return nil, nil, err
}
p, ok := FromPeerContext(ctx)
if ok {
p.Node = wn.Raw()
}
return wn.Raw(), done, nil
}
func (d *Default) Apply(nodes []Node) {
weightedNodes := make([]WeightedNode, 0, len(nodes))
for _, v := range nodes {
weightedNodes = append(weightedNodes, d.NodeBuilder.Build(v))
2 years ago
}
d.nodes.Store(weightedNodes)
2 years ago
}
type DefaultBuilder struct {
Node WeightedNodeBuilder
Balancer BalancerBuilder
}
func (d *DefaultBuilder) Build() Selector {
return &Default{
2 years ago
NodeBuilder: d.Node,
Balancer: d.Balancer.Builder(),
2 years ago
}
}