-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
221 lines (184 loc) · 5.25 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/jonboulle/clockwork"
)
var (
client = &http.Client{}
lbServer *httptest.Server
servers []*http.Server
nodeManager *SafeNodeManager
nodeParams = []NodeParams{
{ID: 1, URL: "http://localhost:8081", ReqLimit: 2, BodyLimit: 76},
{ID: 2, URL: "http://localhost:8082", ReqLimit: 3, BodyLimit: 2 * 1024 * 1024},
{ID: 3, URL: "http://localhost:8083", ReqLimit: 5, BodyLimit: 1 * 1024 * 1024},
}
)
func startTestServer(id int) *http.Server {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("node: %d", id)))
})
server := &http.Server{
Addr: fmt.Sprintf(":%d", 8080 + id),
Handler: handler,
}
go server.ListenAndServe()
return server
}
func setup() {
nodes := make([]*Node, len(nodeParams))
for i, nodeParams := range nodeParams {
startTestServer(nodeParams.ID)
nodes[i] = NewNode(nodeParams)
}
nodeManager = NewSafeNodeManager(nodes, clockwork.NewFakeClock())
nodeManager.StartPeriodicTasks()
lb := NewLoadBalancer(nodeManager)
lbServer = httptest.NewServer(lb)
time.Sleep(1 * time.Second)
}
func teardown() {
lbServer.Close()
for _, server := range servers {
server.Close()
}
}
func resetRateLimits(m *SafeNodeManager) {
m.ResetLimits()
}
func resetHealthChecks(m *SafeNodeManager) {
for _, node := range m.nodes {
node.Healthy = 1
}
}
func TestLoadBalancer(t *testing.T) {
setup()
defer teardown()
t.Run("RoundRobin", testRoundRobin)
t.Run("RateLimitExceeded", testRateLimitExceededByRPM)
t.Run("NodeHealthHandling", testAllNodesUnhealthy)
t.Run("AllNodesBusy", testAllNodesBusy)
t.Run("RateLimitReset", testRateLimitReset)
t.Run("RateLimitExceededByBPM", testRateLimitExceededByBPM)
}
// Should work by round robin
func testRoundRobin(t *testing.T) {
next := 0
for i := 0; i <= len(nodeManager.nodes) + 1; i++ {
node := nodeManager.nodes[next]
if node.ID != next + 1 {
t.Errorf("Round robin not working correctly, expected %d, got %d", next+1, node.ID)
}
next = (next + 1) % len(nodeManager.nodes)
}
}
// Should hit rate limit by requests per minute for each node
func testRateLimitExceededByRPM(t *testing.T) {
resetRateLimits(nodeManager)
nodes := nodeManager.nodes
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
resp, err := client.Get(lbServer.URL)
if err != nil {
t.Errorf("Failed to send request: %v", err)
return
}
resp.Body.Close()
}()
}
wg.Wait()
if nodes[0].ReqCount < nodes[0].ReqLimit {
t.Errorf("Rate Limit should be hit; RPM %d/%d", nodes[0].ReqCount, nodes[0].ReqLimit)
}
t.Logf("Node2 ReqCount:%d, ReqLimit:%d", nodes[1].ReqCount, nodes[1].ReqLimit)
t.Logf("Node3 ReqCount:%d, ReqLimit:%d", nodes[2].ReqCount, nodes[2].ReqLimit)
}
// Should hit rate limit by request body size per minute for each node
func testRateLimitExceededByBPM(t *testing.T) {
resetRateLimits(nodeManager)
resetHealthChecks(nodeManager)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
resp, err := client.Post(lbServer.URL, "text/plain", bytes.NewBufferString("this should exceed the body limit!! this sentence is under 76 bytes"))
if err != nil {
t.Errorf("Failed to send request: %v", err)
return
}
resp.Body.Close()
}()
}
wg.Wait()
resp, err := client.Post(lbServer.URL, "text/plain", bytes.NewBufferString("this should skip the node1"))
if err != nil {
t.Errorf("Failed to send request: %v", err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Errorf("Failed to read response body: %v", err)
}
expected := "node: 2"
if string(body) != "node: 2" {
t.Errorf("Expected response body to be %s, got %s", expected, body)
}
}
// Should return 503 when all nodes are unhealthy
func testAllNodesUnhealthy(t *testing.T) {
resetRateLimits(nodeManager)
for _, node := range nodeManager.nodes {
node.Healthy = 0
}
resp, err := client.Get(lbServer.URL)
if err != nil && resp.StatusCode != http.StatusServiceUnavailable {
t.Errorf("Expected status code %d, got %d", http.StatusServiceUnavailable, resp.StatusCode)
t.Logf("Err: %v", err)
}
resp.Body.Close()
}
// Should return 503 when all nodes have hit rate limits
func testAllNodesBusy(t *testing.T) {
resetHealthChecks(nodeManager)
for _, node := range nodeManager.nodes {
node.ReqCount = node.ReqLimit
}
resp, err := client.Get(lbServer.URL)
if err != nil && resp.StatusCode != http.StatusServiceUnavailable {
t.Errorf("Expected status code %d, got %d", http.StatusServiceUnavailable, resp.StatusCode)
}
resp.Body.Close()
}
// Should reset RPM and BPM for each node every minute
func testRateLimitReset(t *testing.T) {
c := clockwork.NewFakeClock()
nodeManager := NewSafeNodeManager(nodeManager.nodes, c)
node := nodeManager.nodes[0]
node.ReqCount = 10
node.BodyCount = 100
var wg sync.WaitGroup
wg.Add(1)
go func() {
nodeManager.StartPeriodicTasks()
c.Advance(61 * time.Second)
wg.Done()
}()
c.BlockUntil(1)
wg.Wait()
if node.ReqCount != 0 || node.BodyCount != 0 {
t.Errorf("Expected counters to be reset to 0, got ReqCount=%d, BodyCount=%d", node.ReqCount, node.BodyCount)
}
}