From e6d21e17320e707f813b10d3ad1e44c49336eb57 Mon Sep 17 00:00:00 2001 From: Kirill Sysoev Date: Sat, 22 Jun 2024 15:41:29 +0800 Subject: [PATCH] chore: Refactor LoadBalancer struct and related code to use LoadBalancerNode instead of BackendNode --- backend/loadbalancer.go | 14 ++++++++------ backend/loadbalancer_test.go | 3 +++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/backend/loadbalancer.go b/backend/loadbalancer.go index 5bc8b65..2965752 100644 --- a/backend/loadbalancer.go +++ b/backend/loadbalancer.go @@ -9,26 +9,28 @@ import ( var ErrNotEnoughBackends = fmt.Errorf("load balancer requires at least 2 backends") -type BackendNode struct { +const minRequiredBackends = 2 + +type LoadBalancerNode struct { backend wasabi.RequestHandler counter atomic.Int32 } type LoadBalancer struct { - backends []*BackendNode + backends []*LoadBalancerNode } // NewLoadBalancer creates a new instance of LoadBalancer with the given backends. // It takes a slice of RequestHandler as a parameter and returns a new instance of LoadBalancer. func NewLoadBalancer(backends []wasabi.RequestHandler) (*LoadBalancer, error) { - if len(backends) < 2 { + if len(backends) < minRequiredBackends { return nil, ErrNotEnoughBackends } - nodes := make([]*BackendNode, len(backends)) + nodes := make([]*LoadBalancerNode, len(backends)) for i, backend := range backends { - nodes[i] = &BackendNode{ + nodes[i] = &LoadBalancerNode{ backend: backend, counter: atomic.Int32{}, } @@ -52,7 +54,7 @@ func (lb *LoadBalancer) Handle(conn wasabi.Connection, r wasabi.Request) error { // getLeastBusyNode returns the least busy backend node. // It returns the least busy backend node. -func (lb *LoadBalancer) getLeastBusyNode() *BackendNode { +func (lb *LoadBalancer) getLeastBusyNode() *LoadBalancerNode { minRequests := lb.backends[0].counter.Load() minBackend := lb.backends[0] diff --git a/backend/loadbalancer_test.go b/backend/loadbalancer_test.go index aefa722..d5feb6b 100644 --- a/backend/loadbalancer_test.go +++ b/backend/loadbalancer_test.go @@ -18,6 +18,7 @@ func TestNewLoadBalancer(t *testing.T) { } backends = append(backends, mocks.NewMockBackend(t)) + lb, err := NewLoadBalancer(backends) if err != nil { t.Fatalf("Failed to create load balancer: %v", err) @@ -31,6 +32,7 @@ func TestNewLoadBalancer(t *testing.T) { if backend.backend != backends[i] { t.Errorf("Expected backend at index %d to be %v, but got %v", i, backends[i], backend.backend) } + if backend.counter.Load() != 0 { t.Errorf("Expected backend counter at index %d to be 0, but got %d", i, backend.counter.Load()) } @@ -68,6 +70,7 @@ func TestLoadBalancer_Handle(t *testing.T) { mocks.NewMockBackend(t), mocks.NewMockBackend(t), } + lb, err := NewLoadBalancer(backends) if err != nil { t.Fatalf("Failed to create load balancer: %v", err)