-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmetrics_aggregator_test.go
More file actions
630 lines (535 loc) · 19.4 KB
/
Copy pathmetrics_aggregator_test.go
File metadata and controls
630 lines (535 loc) · 19.4 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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package main
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging"
libpack_monitoring "github.com/lukaszraczylo/graphql-monitoring-proxy/monitoring"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newTestAggregator spins up a miniredis, creates a redis.Client against it,
// and returns a MetricsAggregator wired to that client.
// The caller must call t.Cleanup to shut down the aggregator and the server.
func newTestAggregator(t *testing.T) (*MetricsAggregator, *miniredis.Miniredis) {
t.Helper()
mr, err := miniredis.Run()
require.NoError(t, err, "miniredis.Run")
client := redis.NewClient(&redis.Options{
Addr: mr.Addr(),
})
ctx, cancel := context.WithCancel(context.Background())
ma := &MetricsAggregator{
redisClient: client,
logger: libpack_logger.New(),
instanceID: "test-instance-001",
publishKey: "graphql-proxy:metrics:instances",
ttl: 30 * time.Second,
publishTimer: time.NewTicker(100 * time.Millisecond),
ctx: ctx,
cancel: cancel,
}
t.Cleanup(func() {
ma.Shutdown()
mr.Close()
})
return ma, mr
}
// minimalCfg sets the package-level cfg to a minimal valid value so publishMetrics
// does not bail out on the nil-cfg guard. Restores the original on cleanup.
func minimalCfg(t *testing.T) {
t.Helper()
old := cfg
cfgMutex.Lock()
cfg = &config{
Logger: libpack_logger.New(),
Monitoring: libpack_monitoring.NewMonitoring(&libpack_monitoring.InitConfig{}),
}
cfgMutex.Unlock()
t.Cleanup(func() {
cfgMutex.Lock()
cfg = old
cfgMutex.Unlock()
})
}
// ----- InitializeMetricsAggregator ----------------------------------------
func TestMetricsAggregator_InitializeMetricsAggregator_AlreadyInitialized(t *testing.T) {
// If the singleton is already set, Init must be a no-op and return nil.
mr, err := miniredis.Run()
require.NoError(t, err)
defer mr.Close()
client := redis.NewClient(&redis.Options{Addr: mr.Addr()})
ctx, cancel := context.WithCancel(context.Background())
existing := &MetricsAggregator{
redisClient: client,
instanceID: "existing",
publishKey: "graphql-proxy:metrics:instances",
ttl: 30 * time.Second,
publishTimer: time.NewTicker(time.Hour),
ctx: ctx,
cancel: cancel,
}
// Inject singleton directly (bypass constructor).
aggregatorMutex.Lock()
old := metricsAggregator
metricsAggregator = existing
aggregatorMutex.Unlock()
t.Cleanup(func() {
aggregatorMutex.Lock()
metricsAggregator = old
aggregatorMutex.Unlock()
existing.publishTimer.Stop()
cancel()
_ = client.Close()
})
err = InitializeMetricsAggregator(mr.Addr(), "", 0, libpack_logger.New())
assert.NoError(t, err, "should return nil when already initialized")
// Singleton must still be the original instance.
aggregatorMutex.RLock()
got := metricsAggregator
aggregatorMutex.RUnlock()
assert.Equal(t, existing, got, "singleton must not be replaced")
}
func TestMetricsAggregator_InitializeMetricsAggregator_BadURL(t *testing.T) {
// Ensure the singleton is clear for this sub-test.
aggregatorMutex.Lock()
old := metricsAggregator
metricsAggregator = nil
aggregatorMutex.Unlock()
t.Cleanup(func() {
aggregatorMutex.Lock()
if metricsAggregator != nil {
metricsAggregator.Shutdown()
}
metricsAggregator = old
aggregatorMutex.Unlock()
})
// An unreachable address should cause Ping to fail and return an error.
err := InitializeMetricsAggregator("127.0.0.1:1", "", 0, nil)
assert.Error(t, err, "should fail when Redis is unreachable")
}
// ----- removeInstanceMetrics -----------------------------------------------
func TestMetricsAggregator_RemoveInstanceMetrics_CleansKeys(t *testing.T) {
ma, mr := newTestAggregator(t)
ctx := context.Background()
// Pre-populate keys that removeInstanceMetrics should delete.
key := fmt.Sprintf("%s:%s", ma.publishKey, ma.instanceID)
err := mr.Set(key, `{"instance_id":"test-instance-001"}`)
require.NoError(t, err)
err = ma.redisClient.SAdd(ctx, ma.publishKey, ma.instanceID).Err()
require.NoError(t, err)
// Verify keys exist before removal.
exists, err := ma.redisClient.Exists(ctx, key).Result()
require.NoError(t, err)
assert.Equal(t, int64(1), exists, "key should exist before removal")
ma.removeInstanceMetrics()
// Verify instance key is gone.
exists, err = ma.redisClient.Exists(ctx, key).Result()
require.NoError(t, err)
assert.Equal(t, int64(0), exists, "key should be deleted after removeInstanceMetrics")
// Verify instance ID removed from the set.
isMember, err := ma.redisClient.SIsMember(ctx, ma.publishKey, ma.instanceID).Result()
require.NoError(t, err)
assert.False(t, isMember, "instanceID should be removed from the set")
}
// ----- publishMetrics -------------------------------------------------------
func TestMetricsAggregator_PublishMetrics_WritesRedisKey(t *testing.T) {
minimalCfg(t)
ma, _ := newTestAggregator(t)
ma.publishMetrics()
ctx := context.Background()
key := fmt.Sprintf("%s:%s", ma.publishKey, ma.instanceID)
val, err := ma.redisClient.Get(ctx, key).Result()
require.NoError(t, err, "publishMetrics should have written the key to Redis")
assert.NotEmpty(t, val, "stored value must not be empty")
// Must be valid JSON.
var im InstanceMetrics
require.NoError(t, json.Unmarshal([]byte(val), &im), "stored value must be valid JSON")
assert.Equal(t, ma.instanceID, im.InstanceID)
}
func TestMetricsAggregator_PublishMetrics_NilCfgNoWrite(t *testing.T) {
// Ensure cfg is nil so publishMetrics bails out early.
cfgMutex.Lock()
old := cfg
cfg = nil
cfgMutex.Unlock()
t.Cleanup(func() {
cfgMutex.Lock()
cfg = old
cfgMutex.Unlock()
})
ma, _ := newTestAggregator(t)
ma.publishMetrics() // Must not panic.
ctx := context.Background()
key := fmt.Sprintf("%s:%s", ma.publishKey, ma.instanceID)
exists, err := ma.redisClient.Exists(ctx, key).Result()
require.NoError(t, err)
assert.Equal(t, int64(0), exists, "no key should be written when cfg is nil")
}
// ----- startPublishing (one tick) ------------------------------------------
func TestMetricsAggregator_StartPublishing_PublishesOnStart(t *testing.T) {
minimalCfg(t)
ma, _ := newTestAggregator(t)
// Run startPublishing in background; it calls publishMetrics immediately.
go ma.startPublishing()
// Give the initial synchronous publish time to complete, then cancel.
time.Sleep(80 * time.Millisecond)
ma.cancel()
// Allow the goroutine to finish cleanup.
time.Sleep(50 * time.Millisecond)
ctx := context.Background()
key := fmt.Sprintf("%s:%s", ma.publishKey, ma.instanceID)
val, err := ma.redisClient.Get(ctx, key).Result()
// After startPublishing runs publishMetrics on start, the key must be present
// (unless cfg is nil — but we set it above). If removeInstanceMetrics ran on
// shutdown it deletes the key; that is fine — what we assert is no panic + the
// goroutine exits cleanly (verified by the race detector).
_ = val
_ = err
// Primary assertion: no goroutine leak (race detector) and no panic.
}
// ----- GetAggregatedMetrics ------------------------------------------------
func TestMetricsAggregator_GetAggregatedMetrics_EmptySet(t *testing.T) {
ma, _ := newTestAggregator(t)
result, err := ma.GetAggregatedMetrics()
require.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, 0, result.TotalInstances)
assert.Equal(t, 0, result.HealthyInstances)
assert.Empty(t, result.Instances)
}
func TestMetricsAggregator_GetAggregatedMetrics_TwoInstances_Aggregated(t *testing.T) {
ma, _ := newTestAggregator(t)
ctx := context.Background()
instances := []InstanceMetrics{
{
InstanceID: "inst-A",
Hostname: "host-a",
LastUpdate: time.Now(),
UptimeSeconds: 120,
Stats: map[string]any{
"requests": map[string]any{
"total": float64(100),
"succeeded": float64(95),
"failed": float64(5),
"skipped": float64(0),
"current_requests_per_second": float64(10),
"avg_requests_per_second": float64(8),
},
},
Health: map[string]any{"status": "healthy"},
},
{
InstanceID: "inst-B",
Hostname: "host-b",
LastUpdate: time.Now(),
UptimeSeconds: 60,
Stats: map[string]any{
"requests": map[string]any{
"total": float64(200),
"succeeded": float64(180),
"failed": float64(20),
"skipped": float64(0),
"current_requests_per_second": float64(20),
"avg_requests_per_second": float64(15),
},
},
Health: map[string]any{"status": "healthy"},
},
}
for _, inst := range instances {
data, err := json.Marshal(inst)
require.NoError(t, err)
key := fmt.Sprintf("%s:%s", ma.publishKey, inst.InstanceID)
pipe := ma.redisClient.Pipeline()
pipe.Set(ctx, key, data, 30*time.Second)
pipe.SAdd(ctx, ma.publishKey, inst.InstanceID)
_, err = pipe.Exec(ctx)
require.NoError(t, err)
}
result, err := ma.GetAggregatedMetrics()
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, 2, result.TotalInstances)
assert.Equal(t, 2, result.HealthyInstances)
assert.Len(t, result.Instances, 2)
// CombinedStats.requests.total must be sum of both.
reqs, ok := result.CombinedStats["requests"].(map[string]any)
require.True(t, ok, "combined_stats.requests must be present")
assert.Equal(t, int64(300), reqs["total"])
assert.Equal(t, int64(275), reqs["succeeded"])
assert.Equal(t, int64(25), reqs["failed"])
}
func TestMetricsAggregator_GetAggregatedMetrics_StaleInstanceSkipped(t *testing.T) {
ma, _ := newTestAggregator(t)
ctx := context.Background()
stale := InstanceMetrics{
InstanceID: "stale-inst",
Hostname: "host-stale",
LastUpdate: time.Now().Add(-2 * time.Minute), // older than 1 minute threshold
UptimeSeconds: 9999,
Stats: map[string]any{},
Health: map[string]any{"status": "healthy"},
}
data, err := json.Marshal(stale)
require.NoError(t, err)
key := fmt.Sprintf("%s:%s", ma.publishKey, stale.InstanceID)
pipe := ma.redisClient.Pipeline()
pipe.Set(ctx, key, data, 30*time.Second)
pipe.SAdd(ctx, ma.publishKey, stale.InstanceID)
_, err = pipe.Exec(ctx)
require.NoError(t, err)
result, err := ma.GetAggregatedMetrics()
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, 0, result.TotalInstances, "stale instance should be excluded")
}
// ----- aggregateStats -------------------------------------------------------
func TestMetricsAggregator_AggregateStats_EmptyInstances(t *testing.T) {
ma, _ := newTestAggregator(t)
result := ma.aggregateStats([]InstanceMetrics{})
assert.NotNil(t, result)
assert.Empty(t, result, "empty input should return empty map")
}
func TestMetricsAggregator_AggregateStats_SingleInstance(t *testing.T) {
ma, _ := newTestAggregator(t)
instances := []InstanceMetrics{
{
InstanceID: "inst-1",
UptimeSeconds: 300,
Stats: map[string]any{
"requests": map[string]any{
"total": float64(50),
"succeeded": float64(45),
"failed": float64(5),
"skipped": float64(2),
"current_requests_per_second": float64(5),
"avg_requests_per_second": float64(4),
},
},
CacheSummary: map[string]any{
"hits": float64(30),
"misses": float64(20),
"total_cached": float64(10),
},
Health: map[string]any{"status": "healthy"},
},
}
result := ma.aggregateStats(instances)
require.NotEmpty(t, result)
reqs, ok := result["requests"].(map[string]any)
require.True(t, ok)
assert.Equal(t, int64(50), reqs["total"])
assert.Equal(t, int64(45), reqs["succeeded"])
assert.Equal(t, int64(5), reqs["failed"])
cache, ok := result["cache_summary"].(map[string]any)
require.True(t, ok)
assert.Equal(t, int64(30), cache["hits"])
assert.Equal(t, int64(20), cache["misses"])
// success_rate: 45/50 * 100 = 90%
successRate, ok := reqs["success_rate_pct"].(float64)
require.True(t, ok)
assert.InDelta(t, 90.0, successRate, 0.01)
}
func TestMetricsAggregator_AggregateStats_MultipleInstances_Sums(t *testing.T) {
ma, _ := newTestAggregator(t)
instances := []InstanceMetrics{
{
InstanceID: "inst-1",
UptimeSeconds: 100,
Stats: map[string]any{
"requests": map[string]any{
"total": float64(100),
"succeeded": float64(90),
"failed": float64(10),
"skipped": float64(0),
"current_requests_per_second": float64(10),
"avg_requests_per_second": float64(8),
},
},
Health: map[string]any{"status": "healthy"},
},
{
InstanceID: "inst-2",
UptimeSeconds: 200,
Stats: map[string]any{
"requests": map[string]any{
"total": float64(400),
"succeeded": float64(360),
"failed": float64(40),
"skipped": float64(0),
"current_requests_per_second": float64(40),
"avg_requests_per_second": float64(30),
},
},
Health: map[string]any{"status": "degraded"},
},
}
result := ma.aggregateStats(instances)
require.NotEmpty(t, result)
reqs := result["requests"].(map[string]any)
assert.Equal(t, int64(500), reqs["total"])
assert.Equal(t, int64(450), reqs["succeeded"])
assert.Equal(t, int64(50), reqs["failed"])
// cluster_uptime should be the oldest (smallest) uptime = 100.
assert.Equal(t, float64(100), result["cluster_uptime"])
assert.Equal(t, 2, result["total_instances"])
}
func TestMetricsAggregator_AggregateStats_CircuitBreaker(t *testing.T) {
ma, _ := newTestAggregator(t)
instances := []InstanceMetrics{
{
InstanceID: "inst-open",
UptimeSeconds: 50,
Stats: map[string]any{"requests": map[string]any{"total": float64(10), "succeeded": float64(5), "failed": float64(5), "skipped": float64(0), "current_requests_per_second": float64(1), "avg_requests_per_second": float64(1)}},
CircuitBreaker: map[string]any{
"enabled": true,
"state": "open",
},
Health: map[string]any{},
},
{
InstanceID: "inst-closed",
UptimeSeconds: 60,
Stats: map[string]any{"requests": map[string]any{"total": float64(10), "succeeded": float64(10), "failed": float64(0), "skipped": float64(0), "current_requests_per_second": float64(1), "avg_requests_per_second": float64(1)}},
CircuitBreaker: map[string]any{
"enabled": true,
"state": "closed",
},
Health: map[string]any{},
},
}
result := ma.aggregateStats(instances)
cb := result["circuit_breaker"].(map[string]any)
assert.Equal(t, true, cb["enabled"])
assert.Equal(t, "open", cb["state"], "any open instance means cluster state = open")
assert.Equal(t, 1, cb["instances_open"])
assert.Equal(t, 1, cb["instances_closed"])
}
func TestMetricsAggregator_AggregateStats_RetryBudget(t *testing.T) {
ma, _ := newTestAggregator(t)
instances := []InstanceMetrics{
{
InstanceID: "inst-rb",
UptimeSeconds: 10,
Stats: map[string]any{"requests": map[string]any{"total": float64(1), "succeeded": float64(1), "failed": float64(0), "skipped": float64(0), "current_requests_per_second": float64(0), "avg_requests_per_second": float64(0)}},
RetryBudget: map[string]any{
"enabled": true,
"allowed_retries": float64(50),
"denied_retries": float64(10),
"total_attempts": float64(60),
"current_tokens": float64(80),
"max_tokens": float64(100),
"tokens_per_sec": float64(5),
},
Health: map[string]any{},
},
}
result := ma.aggregateStats(instances)
rb := result["retry_budget"].(map[string]any)
assert.Equal(t, true, rb["enabled"])
assert.Equal(t, int64(50), rb["allowed_retries"])
assert.Equal(t, int64(10), rb["denied_retries"])
assert.InDelta(t, 16.67, rb["denial_rate_pct"].(float64), 0.1)
}
func TestMetricsAggregator_AggregateStats_NilStats_DoesNotPanic(t *testing.T) {
ma, _ := newTestAggregator(t)
// Instance with nil Stats should not cause a panic; it is skipped.
instances := []InstanceMetrics{
{
InstanceID: "bad-inst",
UptimeSeconds: 10,
Stats: nil,
Health: map[string]any{},
},
}
assert.NotPanics(t, func() {
result := ma.aggregateStats(instances)
// cluster_uptime is set before the nil-stats guard, so it must be non-zero.
assert.Equal(t, float64(10), result["cluster_uptime"])
})
}
func TestMetricsAggregator_AggregateStats_MemoryTracking(t *testing.T) {
ma, _ := newTestAggregator(t)
instances := []InstanceMetrics{
{
InstanceID: "inst-mem",
UptimeSeconds: 10,
Stats: map[string]any{"requests": map[string]any{"total": float64(1), "succeeded": float64(1), "failed": float64(0), "skipped": float64(0), "current_requests_per_second": float64(0), "avg_requests_per_second": float64(0)}},
Cache: map[string]any{"memory_usage_mb": float64(42.5)},
Health: map[string]any{},
},
{
InstanceID: "inst-mem2",
UptimeSeconds: 20,
Stats: map[string]any{"requests": map[string]any{"total": float64(1), "succeeded": float64(1), "failed": float64(0), "skipped": float64(0), "current_requests_per_second": float64(0), "avg_requests_per_second": float64(0)}},
Cache: map[string]any{"memory_usage_mb": float64(57.5)},
Health: map[string]any{},
},
}
result := ma.aggregateStats(instances)
mem := result["memory"].(map[string]any)
assert.Equal(t, true, mem["available"])
assert.InDelta(t, 100.0, mem["total_usage_mb"].(float64), 0.01)
}
func TestMetricsAggregator_AggregateStats_MemoryNegativeSkipped(t *testing.T) {
ma, _ := newTestAggregator(t)
// -1 means Redis cache where memory tracking is unavailable; must be skipped.
instances := []InstanceMetrics{
{
InstanceID: "inst-redis-cache",
UptimeSeconds: 10,
Stats: map[string]any{"requests": map[string]any{"total": float64(1), "succeeded": float64(1), "failed": float64(0), "skipped": float64(0), "current_requests_per_second": float64(0), "avg_requests_per_second": float64(0)}},
Cache: map[string]any{"memory_usage_mb": float64(-1)},
Health: map[string]any{},
},
}
result := ma.aggregateStats(instances)
mem := result["memory"].(map[string]any)
assert.Equal(t, false, mem["available"])
assert.Equal(t, float64(-1), mem["total_usage_mb"].(float64))
}
// ----- Shutdown ------------------------------------------------------------
func TestMetricsAggregator_Shutdown_CancelsContext(t *testing.T) {
mr, err := miniredis.Run()
require.NoError(t, err)
t.Cleanup(func() { mr.Close() })
client := redis.NewClient(&redis.Options{Addr: mr.Addr()})
ctx, cancel := context.WithCancel(context.Background())
ma := &MetricsAggregator{
redisClient: client,
logger: libpack_logger.New(),
instanceID: "shutdown-test",
publishKey: "graphql-proxy:metrics:instances",
ttl: 30 * time.Second,
publishTimer: time.NewTicker(time.Hour),
ctx: ctx,
cancel: cancel,
}
// Context must not be done before Shutdown.
select {
case <-ctx.Done():
t.Fatal("context should not be done before Shutdown()")
default:
}
ma.Shutdown()
// Context must be cancelled after Shutdown.
select {
case <-ctx.Done():
// expected
case <-time.After(500 * time.Millisecond):
t.Fatal("context was not cancelled after Shutdown()")
}
}
func TestMetricsAggregator_Shutdown_Idempotent(t *testing.T) {
ma, _ := newTestAggregator(t)
// Calling Shutdown twice must not panic.
assert.NotPanics(t, func() {
ma.Shutdown()
ma.Shutdown()
})
}