-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi_health_test.go
More file actions
256 lines (220 loc) · 7.39 KB
/
Copy pathapi_health_test.go
File metadata and controls
256 lines (220 loc) · 7.39 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main
import (
"encoding/json"
"io"
"net/http/httptest"
"testing"
fiber "github.com/gofiber/fiber/v3"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
libpack_monitoring "github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring"
"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
)
// ---- helpers ---------------------------------------------------------------
func setupMinimalCfg(t *testing.T) {
t.Helper()
logger := libpack_logger.New()
monitoring := libpack_monitoring.NewMonitoring(&libpack_monitoring.InitConfig{})
cfg = &config{
Logger: logger,
Monitoring: monitoring,
}
}
func newHealthApp(t *testing.T) *fiber.App {
t.Helper()
app := fiber.New(fiber.Config{
// suppress stack-trace noise in test output
})
app.Get("/api/backend/health", apiBackendHealth)
app.Get("/api/pool/health", apiConnectionPoolHealth)
app.Get("/api/circuit-breaker/health", apiCircuitBreakerHealth)
return app
}
// ---- apiBackendHealth ------------------------------------------------------
func TestApiBackendHealth_NilManager_Returns503(t *testing.T) {
// Ensure global manager is nil for this test.
orig := backendHealthManager
backendHealthManager = nil
defer func() { backendHealthManager = orig }()
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/backend/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 503, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "unknown", body["status"])
assert.NotEmpty(t, body["message"])
}
func TestApiBackendHealth_HealthyManager_Returns200(t *testing.T) {
orig := backendHealthManager
defer func() { backendHealthManager = orig }()
// inject a healthy manager directly (bypassing sync.Once)
mgr := NewBackendHealthManager(&fasthttp.Client{}, "http://localhost:8080", libpack_logger.New())
mgr.isHealthy.Store(true)
backendHealthManager = mgr
setupMinimalCfg(t)
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/backend/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "healthy", body["status"])
assert.NotNil(t, body["backend_url"])
assert.NotNil(t, body["consecutive_failures"])
assert.NotNil(t, body["check_interval"])
}
func TestApiBackendHealth_UnhealthyManager_Returns503(t *testing.T) {
orig := backendHealthManager
defer func() { backendHealthManager = orig }()
mgr := NewBackendHealthManager(&fasthttp.Client{}, "http://localhost:8080", libpack_logger.New())
mgr.isHealthy.Store(false)
backendHealthManager = mgr
setupMinimalCfg(t)
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/backend/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 503, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "unhealthy", body["status"])
}
// ---- apiConnectionPoolHealth -----------------------------------------------
func TestApiConnectionPoolHealth_NilManager_Returns503(t *testing.T) {
connectionPoolMutex.Lock()
orig := connectionPoolManager
connectionPoolManager = nil
connectionPoolMutex.Unlock()
defer func() {
connectionPoolMutex.Lock()
connectionPoolManager = orig
connectionPoolMutex.Unlock()
}()
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/pool/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 503, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "unknown", body["status"])
assert.NotEmpty(t, body["message"])
}
func TestApiConnectionPoolHealth_HealthyPool_Returns200(t *testing.T) {
connectionPoolMutex.Lock()
orig := connectionPoolManager
mgr := NewConnectionPoolManager(&fasthttp.Client{})
connectionPoolManager = mgr
connectionPoolMutex.Unlock()
defer func() {
connectionPoolMutex.Lock()
_ = mgr.Shutdown()
connectionPoolManager = orig
connectionPoolMutex.Unlock()
}()
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/pool/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "healthy", body["status"])
assert.NotNil(t, body["active_connections"])
assert.NotNil(t, body["total_connections"])
assert.NotNil(t, body["connection_failures"])
}
func TestApiConnectionPoolHealth_DegradedPool_Returns200WithDegradedStatus(t *testing.T) {
connectionPoolMutex.Lock()
orig := connectionPoolManager
mgr := NewConnectionPoolManager(&fasthttp.Client{})
// push failure counter above threshold (10)
for range 15 {
mgr.connectionFailures.Add(1)
}
connectionPoolManager = mgr
connectionPoolMutex.Unlock()
defer func() {
connectionPoolMutex.Lock()
_ = mgr.Shutdown()
connectionPoolManager = orig
connectionPoolMutex.Unlock()
}()
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/pool/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
// handler returns 200 even for degraded
assert.Equal(t, 200, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "degraded", body["status"])
}
// ---- apiCircuitBreakerHealth -----------------------------------------------
func TestApiCircuitBreakerHealth_NilCB_Returns503(t *testing.T) {
cbMutex.Lock()
origCB := cb
cb = nil
cbMutex.Unlock()
defer func() {
cbMutex.Lock()
cb = origCB
cbMutex.Unlock()
}()
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/circuit-breaker/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 503, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "disabled", body["status"])
assert.NotEmpty(t, body["message"])
}
func TestApiCircuitBreakerHealth_ClosedCB_Returns200Healthy(t *testing.T) {
cbMutex.Lock()
origCB := cb
cbMutex.Unlock()
defer func() {
cbMutex.Lock()
cb = origCB
cbMutex.Unlock()
}()
logger := libpack_logger.New()
monitoring := libpack_monitoring.NewMonitoring(&libpack_monitoring.InitConfig{})
cfg = &config{Logger: logger, Monitoring: monitoring}
cfg.CircuitBreaker.Enable = true
cfg.CircuitBreaker.MaxFailures = 5
cfg.CircuitBreaker.Timeout = 30
initCircuitBreaker(cfg)
// cb is now set by initCircuitBreaker; circuit starts closed (healthy)
app := newHealthApp(t)
req := httptest.NewRequest("GET", "/api/circuit-breaker/health", nil)
resp, err := app.Test(req)
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
var body map[string]any
raw, _ := io.ReadAll(resp.Body)
assert.NoError(t, json.Unmarshal(raw, &body))
assert.Equal(t, "healthy", body["status"])
assert.NotNil(t, body["state"])
assert.NotNil(t, body["counts"])
assert.NotNil(t, body["configuration"])
counts, ok := body["counts"].(map[string]any)
assert.True(t, ok)
assert.NotNil(t, counts["requests"])
assert.NotNil(t, counts["total_successes"])
assert.NotNil(t, counts["total_failures"])
assert.NotNil(t, counts["consecutive_successes"])
assert.NotNil(t, counts["consecutive_failures"])
}