36 lines
779 B
Go
36 lines
779 B
Go
package dbx
|
|
|
|
import "sync/atomic"
|
|
|
|
// Balancer selects the next node from a list.
|
|
// It must return nil if no suitable node is available.
|
|
type Balancer interface {
|
|
Next(nodes []*Node) *Node
|
|
}
|
|
|
|
// RoundRobinBalancer distributes load evenly across healthy nodes.
|
|
type RoundRobinBalancer struct {
|
|
counter atomic.Uint64
|
|
}
|
|
|
|
// NewRoundRobinBalancer creates a new round-robin balancer.
|
|
func NewRoundRobinBalancer() *RoundRobinBalancer {
|
|
return &RoundRobinBalancer{}
|
|
}
|
|
|
|
// Next returns the next healthy node, or nil if none are healthy.
|
|
func (b *RoundRobinBalancer) Next(nodes []*Node) *Node {
|
|
n := len(nodes)
|
|
if n == 0 {
|
|
return nil
|
|
}
|
|
idx := b.counter.Add(1)
|
|
for i := 0; i < n; i++ {
|
|
node := nodes[(int(idx)+i)%n]
|
|
if node.IsHealthy() {
|
|
return node
|
|
}
|
|
}
|
|
return nil
|
|
}
|