-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver_handlers_test.go
More file actions
601 lines (512 loc) · 16.5 KB
/
Copy pathserver_handlers_test.go
File metadata and controls
601 lines (512 loc) · 16.5 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v3"
libpack_cache "github.com/lukaszraczylo/graphql-monitoring-proxy/cache"
"github.com/valyala/fasthttp"
)
// ---------------------------------------------------------------------------
// AddRequestUUID
// ---------------------------------------------------------------------------
func TestAddRequestUUID_SetsLocalsAndCallsNext(t *testing.T) {
app := fiber.New()
app.Use(AddRequestUUID)
var captured string
app.Get("/", func(c fiber.Ctx) error {
if v, ok := c.Locals("request_uuid").(string); ok {
captured = v
}
return c.SendStatus(200)
})
req := httptest.NewRequest("GET", "/", nil)
resp, err := app.Test(req, fiber.TestConfig{Timeout: 0})
if err != nil {
t.Fatalf("app.Test: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("want 200, got %d", resp.StatusCode)
}
if captured == "" {
t.Fatal("request_uuid not set in Locals")
}
// UUIDs are 36 chars (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
if len(captured) != 36 {
t.Errorf("unexpected UUID length: %q", captured)
}
}
func TestAddRequestUUID_UniquePerRequest(t *testing.T) {
app := fiber.New()
app.Use(AddRequestUUID)
seen := make([]string, 0, 5)
app.Get("/", func(c fiber.Ctx) error {
if v, ok := c.Locals("request_uuid").(string); ok {
seen = append(seen, v)
}
return c.SendStatus(200)
})
for i := range 5 {
req := httptest.NewRequest("GET", "/", nil)
resp, err := app.Test(req, fiber.TestConfig{Timeout: 0})
if err != nil {
t.Fatalf("request %d: %v", i, err)
}
_ = resp.Body.Close()
}
set := make(map[string]struct{}, len(seen))
for _, id := range seen {
set[id] = struct{}{}
}
if len(set) != 5 {
t.Errorf("expected 5 unique UUIDs, got %d unique in %v", len(set), seen)
}
}
// ---------------------------------------------------------------------------
// healthCheck
// ---------------------------------------------------------------------------
func TestHealthCheck_Returns200WithJSON(t *testing.T) {
// Ensure cfg is ready and GraphQL check is disabled via query param
parseConfig()
_ = StartMonitoringServer()
app := fiber.New()
app.Get("/health", healthCheck)
// Pass check_graphql=false to avoid real network call
req := httptest.NewRequest("GET", "/health?check_graphql=false&check_redis=false", nil)
resp, err := app.Test(req, fiber.TestConfig{Timeout: 10000 * time.Millisecond})
if err != nil {
t.Fatalf("app.Test: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
t.Fatalf("want 200, got %d", resp.StatusCode)
}
var body map[string]any
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("decode response: %v", err)
}
if _, ok := body["status"]; !ok {
t.Error("response missing 'status' field")
}
if _, ok := body["timestamp"]; !ok {
t.Error("response missing 'timestamp' field")
}
if body["status"] != "healthy" {
t.Errorf("want status=healthy, got %v", body["status"])
}
}
func TestHealthCheck_UnhealthyWhenGraphQLDown(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
// Point to a server that refuses connections
cfgMutex.Lock()
origHost := cfg.Server.HostGraphQL
cfg.Server.HostGraphQL = "http://127.0.0.1:1" // port 1 always refused
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Server.HostGraphQL = origHost
cfgMutex.Unlock()
}()
app := fiber.New()
app.Get("/health", healthCheck)
req := httptest.NewRequest("GET", "/health?check_redis=false", nil)
resp, err := app.Test(req, fiber.TestConfig{Timeout: 15000 * time.Millisecond})
if err != nil {
t.Fatalf("app.Test: %v", err)
}
defer func() { _ = resp.Body.Close() }()
// Should return 503 when backend is unreachable
if resp.StatusCode != fiber.StatusServiceUnavailable {
t.Fatalf("want 503, got %d", resp.StatusCode)
}
var body map[string]any
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("decode: %v", err)
}
if body["status"] != "unhealthy" {
t.Errorf("want unhealthy, got %v", body["status"])
}
}
// ---------------------------------------------------------------------------
// processGraphQLRequest
// ---------------------------------------------------------------------------
func TestProcessGraphQLRequest_ValidBodyProxiesToBackend(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"data":{"test":"ok"}}`))
}))
defer backend.Close()
cfgMutex.Lock()
origHost := cfg.Server.HostGraphQL
origHostRO := cfg.Server.HostGraphQLReadOnly
origCache := cfg.Cache.CacheEnable
cfg.Server.HostGraphQL = backend.URL
cfg.Server.HostGraphQLReadOnly = backend.URL
cfg.Cache.CacheEnable = false
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Server.HostGraphQL = origHost
cfg.Server.HostGraphQLReadOnly = origHostRO
cfg.Cache.CacheEnable = origCache
cfgMutex.Unlock()
}()
app := fiber.New()
app.Post("/*", processGraphQLRequest)
body := `{"query":"query { __typename }"}`
req := httptest.NewRequest("POST", "/v1/graphql", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req, fiber.TestConfig{Timeout: 10000 * time.Millisecond})
if err != nil {
t.Fatalf("app.Test: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
t.Errorf("want 200, got %d", resp.StatusCode)
}
}
func TestProcessGraphQLRequest_MalformedBodyStillHandled(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
// Backend that always returns 200 (malformed body is handled by proxy layer)
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"errors":[{"message":"parse error"}]}`))
}))
defer backend.Close()
cfgMutex.Lock()
origHost := cfg.Server.HostGraphQL
origHostRO := cfg.Server.HostGraphQLReadOnly
origCache := cfg.Cache.CacheEnable
cfg.Server.HostGraphQL = backend.URL
cfg.Server.HostGraphQLReadOnly = backend.URL
cfg.Cache.CacheEnable = false
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Server.HostGraphQL = origHost
cfg.Server.HostGraphQLReadOnly = origHostRO
cfg.Cache.CacheEnable = origCache
cfgMutex.Unlock()
}()
app := fiber.New()
app.Post("/*", processGraphQLRequest)
// Not valid JSON — proxy should still forward or return gracefully
body := `not-json-at-all`
req := httptest.NewRequest("POST", "/v1/graphql", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req, fiber.TestConfig{Timeout: 10000 * time.Millisecond})
if err != nil {
t.Fatalf("app.Test: %v", err)
}
defer func() { _ = resp.Body.Close() }()
// Should not panic; any 2xx or 5xx is acceptable — just must not crash
if resp.StatusCode < 100 || resp.StatusCode > 599 {
t.Errorf("unexpected status %d", resp.StatusCode)
}
}
// ---------------------------------------------------------------------------
// handleCaching — wasCached=true path (cache hit)
// ---------------------------------------------------------------------------
func TestHandleCaching_CacheHitReturnsStoredResponse(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
// Enable in-memory cache
libpack_cache.EnableCache(&libpack_cache.CacheConfig{
Logger: cfg.Logger,
TTL: 60,
})
libpack_cache.CacheClear()
cfgMutex.Lock()
origEnable := cfg.Cache.CacheEnable
cfg.Cache.CacheEnable = true
cfg.Cache.CacheTTL = 60
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Cache.CacheEnable = origEnable
cfgMutex.Unlock()
}()
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"data":{"users":[]}}`))
}))
defer backend.Close()
cfgMutex.Lock()
origHost := cfg.Server.HostGraphQL
origHostRO := cfg.Server.HostGraphQLReadOnly
cfg.Server.HostGraphQL = backend.URL
cfg.Server.HostGraphQLReadOnly = backend.URL
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Server.HostGraphQL = origHost
cfg.Server.HostGraphQLReadOnly = origHostRO
cfgMutex.Unlock()
}()
app := fiber.New()
app.Post("/*", processGraphQLRequest)
queryBody := `{"query":"query { users { id } }"}`
// First request — cache miss, hits backend
req1 := httptest.NewRequest("POST", "/v1/graphql", strings.NewReader(queryBody))
req1.Header.Set("Content-Type", "application/json")
resp1, err := app.Test(req1, fiber.TestConfig{Timeout: 10000 * time.Millisecond})
if err != nil {
t.Fatalf("first request: %v", err)
}
_ = resp1.Body.Close()
if resp1.StatusCode != 200 {
t.Fatalf("first request want 200, got %d", resp1.StatusCode)
}
// Second identical request — should hit cache
req2 := httptest.NewRequest("POST", "/v1/graphql", strings.NewReader(queryBody))
req2.Header.Set("Content-Type", "application/json")
resp2, err := app.Test(req2, fiber.TestConfig{Timeout: 10000 * time.Millisecond})
if err != nil {
t.Fatalf("second request: %v", err)
}
_ = resp2.Body.Close()
if resp2.StatusCode != 200 {
t.Fatalf("second request want 200, got %d", resp2.StatusCode)
}
if resp2.Header.Get("X-Cache-Hit") != "true" {
t.Error("second request should have X-Cache-Hit: true header")
}
}
func TestHandleCaching_CacheMissProxiesRequest(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
libpack_cache.EnableCache(&libpack_cache.CacheConfig{
Logger: cfg.Logger,
TTL: 60,
})
libpack_cache.CacheClear()
cfgMutex.Lock()
origEnable := cfg.Cache.CacheEnable
cfg.Cache.CacheEnable = true
cfg.Cache.CacheTTL = 60
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Cache.CacheEnable = origEnable
cfgMutex.Unlock()
}()
backendCalled := 0
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
backendCalled++
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = fmt.Fprintf(w, `{"data":{"call":%d}}`, backendCalled)
}))
defer backend.Close()
cfgMutex.Lock()
origHost := cfg.Server.HostGraphQL
origHostRO := cfg.Server.HostGraphQLReadOnly
cfg.Server.HostGraphQL = backend.URL
cfg.Server.HostGraphQLReadOnly = backend.URL
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Server.HostGraphQL = origHost
cfg.Server.HostGraphQLReadOnly = origHostRO
cfgMutex.Unlock()
}()
app := fiber.New()
app.Post("/*", processGraphQLRequest)
// Unique query so no prior cache entry
queryBody := `{"query":"query { uniqueMissTest_12345 { id } }"}`
req := httptest.NewRequest("POST", "/v1/graphql", strings.NewReader(queryBody))
req.Header.Set("Content-Type", "application/json")
resp, err := app.Test(req, fiber.TestConfig{Timeout: 10000 * time.Millisecond})
if err != nil {
t.Fatalf("app.Test: %v", err)
}
_ = resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("want 200, got %d", resp.StatusCode)
}
if resp.Header.Get("X-Cache-Hit") == "true" {
t.Error("first request should not be a cache hit")
}
if backendCalled == 0 {
t.Error("backend should have been called on cache miss")
}
}
// ---------------------------------------------------------------------------
// handleCaching — direct unit test for wasCached=true branch
// ---------------------------------------------------------------------------
func TestHandleCaching_DirectCacheHitBranch(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
libpack_cache.EnableCache(&libpack_cache.CacheConfig{
Logger: cfg.Logger,
TTL: 60,
})
libpack_cache.CacheClear()
cfgMutex.Lock()
origEnable := cfg.Cache.CacheEnable
cfg.Cache.CacheEnable = true
cfg.Cache.CacheTTL = 60
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Cache.CacheEnable = origEnable
cfgMutex.Unlock()
}()
app := fiber.New()
var wasCachedResult bool
app.Post("/test", func(c fiber.Ctx) error {
parsedResult := &parseGraphQLQueryResult{
cacheTime: 60,
cacheRequest: true,
activeEndpoint: cfg.Server.HostGraphQL,
}
// Pre-populate the cache so lookup hits
cacheKey := libpack_cache.CalculateHash(c, "-", "-")
libpack_cache.CacheStore(cacheKey, []byte(`{"data":{"cached":true}}`))
var err error
wasCachedResult, err = handleCaching(c, parsedResult, "-", "-")
return err
})
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/test")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query":"query { cachedQuery }"}`))
ctx := app.AcquireCtx(reqCtx)
defer app.ReleaseCtx(ctx)
parsedResult := &parseGraphQLQueryResult{
cacheTime: 60,
cacheRequest: true,
activeEndpoint: cfg.Server.HostGraphQL,
}
cacheKey := libpack_cache.CalculateHash(ctx, "-", "-")
libpack_cache.CacheStore(cacheKey, []byte(`{"data":{"cached":true}}`))
wasCached, err := handleCaching(ctx, parsedResult, "-", "-")
if err != nil {
t.Fatalf("handleCaching returned error: %v", err)
}
if !wasCached {
t.Error("expected wasCached=true when cache hit")
}
_ = wasCachedResult
}
func TestHandleCaching_NoCacheEnabled_ProxiesDirect(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"data":{"noCacheTest":true}}`))
}))
defer backend.Close()
cfgMutex.Lock()
origEnable := cfg.Cache.CacheEnable
origRedis := cfg.Cache.CacheRedisEnable
origHost := cfg.Server.HostGraphQL
origHostRO := cfg.Server.HostGraphQLReadOnly
cfg.Cache.CacheEnable = false
cfg.Cache.CacheRedisEnable = false
cfg.Server.HostGraphQL = backend.URL
cfg.Server.HostGraphQLReadOnly = backend.URL
cfgMutex.Unlock()
defer func() {
cfgMutex.Lock()
cfg.Cache.CacheEnable = origEnable
cfg.Cache.CacheRedisEnable = origRedis
cfg.Server.HostGraphQL = origHost
cfg.Server.HostGraphQLReadOnly = origHostRO
cfgMutex.Unlock()
}()
app := fiber.New()
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/v1/graphql")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query":"query { noCacheTest }"}`))
fCtx := app.AcquireCtx(reqCtx)
defer app.ReleaseCtx(fCtx)
parsedResult := &parseGraphQLQueryResult{
cacheRequest: false,
cacheTime: 0,
activeEndpoint: backend.URL,
}
wasCached, err := handleCaching(fCtx, parsedResult, "-", "-")
if err != nil {
t.Fatalf("handleCaching error: %v", err)
}
if wasCached {
t.Error("expected wasCached=false when cache disabled")
}
}
// ---------------------------------------------------------------------------
// StartHTTPProxy — starts then shuts down cleanly
// ---------------------------------------------------------------------------
func TestStartHTTPProxy_StartsAndShutdown(t *testing.T) {
parseConfig()
_ = StartMonitoringServer()
// Grab a free port
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("net.Listen: %v", err)
}
port := l.Addr().(*net.TCPAddr).Port
_ = l.Close()
cfgMutex.Lock()
origPort := cfg.Server.PortGraphQL
origTimeout := cfg.Client.ClientTimeout
origWS := cfg.WebSocket.Enable
origAdmin := cfg.AdminDashboard.Enable
cfg.Server.PortGraphQL = port
cfg.Client.ClientTimeout = 5
cfg.WebSocket.Enable = false
cfg.AdminDashboard.Enable = false
cfgMutex.Unlock()
t.Cleanup(func() {
cfgMutex.Lock()
cfg.Server.PortGraphQL = origPort
cfg.Client.ClientTimeout = origTimeout
cfg.WebSocket.Enable = origWS
cfg.AdminDashboard.Enable = origAdmin
cfgMutex.Unlock()
})
errCh := make(chan error, 1)
go func() {
errCh <- StartHTTPProxy()
}()
// Wait for server to bind
deadline := time.Now().Add(3 * time.Second)
var conn net.Conn
for time.Now().Before(deadline) {
conn, err = net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 100*time.Millisecond)
if err == nil {
break
}
time.Sleep(50 * time.Millisecond)
}
if conn == nil {
t.Fatalf("server did not start on port %d within 3s", port)
}
_ = conn.Close()
// Send a health check to confirm it's serving
httpResp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/health?check_graphql=false&check_redis=false", port))
if err != nil {
t.Fatalf("GET /health: %v", err)
}
_ = httpResp.Body.Close()
if httpResp.StatusCode != 200 {
t.Errorf("want 200, got %d", httpResp.StatusCode)
}
}