-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrv_test.go
More file actions
543 lines (463 loc) · 17.1 KB
/
srv_test.go
File metadata and controls
543 lines (463 loc) · 17.1 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
package main
import (
"context"
"errors"
"net"
"net/url"
"testing"
"time"
)
// TestDeriveSRVDomain tests the SRV domain derivation from hostnames.
func TestDeriveSRVDomain(t *testing.T) {
tests := []struct {
hostname string
want string
}{
{"logferry-api.ntppool.net", "ntppool.net"},
{"api.logs.example.com", "logs.example.com"},
{"server.deep.nested.domain.org", "deep.nested.domain.org"},
{"example.com", "example.com"}, // Two-part domain stays as-is
{"localhost", "localhost"}, // Single label stays as-is
{"a.b.c.d.e.f", "b.c.d.e.f"}, // Deep nesting
}
for _, tt := range tests {
t.Run(tt.hostname, func(t *testing.T) {
got := deriveSRVDomain(tt.hostname)
if got != tt.want {
t.Errorf("deriveSRVDomain(%q) = %q, want %q", tt.hostname, got, tt.want)
}
})
}
}
// TestSRVTargetAddress tests the Address() method.
func TestSRVTargetAddress(t *testing.T) {
tests := []struct {
host string
port uint16
want string
}{
{"server1.example.com", 443, "server1.example.com:443"},
{"server2.example.com", 8443, "server2.example.com:8443"},
{"192.0.2.1", 443, "192.0.2.1:443"},
}
for _, tt := range tests {
t.Run(tt.want, func(t *testing.T) {
target := SRVTarget{Host: tt.host, Port: tt.port}
if got := target.Address(); got != tt.want {
t.Errorf("Address() = %q, want %q", got, tt.want)
}
})
}
}
// mockResolver creates a test resolver function.
func mockResolver(targets []*net.SRV, err error) func(context.Context, string, string, string) (string, []*net.SRV, error) {
return func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) {
return "", targets, err
}
}
// TestTargetPoolResolveSRV tests SRV resolution with various scenarios.
func TestTargetPoolResolveSRV(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
t.Run("successful resolution", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 50},
{Target: "server2.example.com.", Port: 443, Priority: 10, Weight: 50},
}, nil)
result := tp.ResolveSRV(context.Background())
if !result {
t.Error("ResolveSRV returned false, expected true")
}
if tp.IsFallbackMode() {
t.Error("TargetPool should not be in fallback mode after successful resolution")
}
if tp.TargetCount() != 2 {
t.Errorf("TargetCount() = %d, want 2", tp.TargetCount())
}
})
t.Run("empty targets falls back", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{}, nil)
result := tp.ResolveSRV(context.Background())
if result {
t.Error("ResolveSRV returned true, expected false")
}
if !tp.IsFallbackMode() {
t.Error("TargetPool should be in fallback mode")
}
})
t.Run("error falls back", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver(nil, errors.New("DNS lookup failed"))
result := tp.ResolveSRV(context.Background())
if result {
t.Error("ResolveSRV returned true, expected false")
}
if !tp.IsFallbackMode() {
t.Error("TargetPool should be in fallback mode")
}
})
t.Run("trailing dot removed from hostname", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 50},
}, nil)
tp.ResolveSRV(context.Background())
// Get the target URL and check the hostname
targetURL := tp.SelectTarget()
if targetURL != "https://server1.example.com:443/" {
t.Errorf("SelectTarget() = %q, expected no trailing dot in hostname", targetURL)
}
})
}
// TestTargetPoolSelectTarget tests target selection logic.
func TestTargetPoolSelectTarget(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
t.Run("fallback mode returns upstream URL", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
targetURL := tp.SelectTarget()
if targetURL != "https://logferry-api.example.com/" {
t.Errorf("SelectTarget() = %q, want upstream URL", targetURL)
}
})
t.Run("single target", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
targetURL := tp.SelectTarget()
if targetURL != "https://server1.example.com:443/" {
t.Errorf("SelectTarget() = %q, want server1 URL", targetURL)
}
})
t.Run("priority ordering", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "backup.example.com", Port: 443, Priority: 20, Weight: 100},
{Target: "primary.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
// Mark primary as unhealthy
tp.MarkUnhealthy("primary.example.com:443", errors.New("test"))
// Should now select backup
targetURL := tp.SelectTarget()
if targetURL != "https://backup.example.com:443/" {
t.Errorf("SelectTarget() = %q, expected backup server", targetURL)
}
})
}
// TestTargetPoolHealthTracking tests health state management.
func TestTargetPoolHealthTracking(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
t.Run("mark healthy", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
// Initially healthy
tp.MarkHealthy("server1.example.com:443")
// Should still select the target
targetURL := tp.SelectTarget()
if targetURL != "https://server1.example.com:443/" {
t.Errorf("SelectTarget() = %q, expected server1", targetURL)
}
})
t.Run("mark unhealthy triggers backoff", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
{Target: "server2.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
// Mark server1 as unhealthy
tp.MarkUnhealthy("server1.example.com:443", errors.New("connection failed"))
// Check that server1 is in backoff
tp.mu.RLock()
info := tp.healthState["server1.example.com:443"]
tp.mu.RUnlock()
if info.healthy {
t.Error("server1 should be unhealthy")
}
if info.backoffUntil.Before(time.Now()) {
t.Error("backoff should be in the future")
}
})
t.Run("recovery resets backoff", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
// Mark unhealthy then healthy
tp.MarkUnhealthy("server1.example.com:443", errors.New("test"))
tp.MarkHealthy("server1.example.com:443")
tp.mu.RLock()
info := tp.healthState["server1.example.com:443"]
tp.mu.RUnlock()
if !info.healthy {
t.Error("server1 should be healthy after recovery")
}
if info.backoffLevel != 0 {
t.Errorf("backoff level should be reset, got %d", info.backoffLevel)
}
})
}
// TestBackoffDurations verifies the backoff schedule.
func TestBackoffDurations(t *testing.T) {
expected := []time.Duration{
5 * time.Second,
10 * time.Second,
20 * time.Second,
40 * time.Second,
80 * time.Second,
160 * time.Second,
300 * time.Second,
}
if len(backoffDurations) != len(expected) {
t.Fatalf("backoffDurations length = %d, want %d", len(backoffDurations), len(expected))
}
for i, want := range expected {
if backoffDurations[i] != want {
t.Errorf("backoffDurations[%d] = %v, want %v", i, backoffDurations[i], want)
}
}
}
// TestSelectLeastUnhealthy tests selection when all targets are unhealthy.
func TestSelectLeastUnhealthy(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
{Target: "server2.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
// Mark both as unhealthy with different backoff levels
tp.MarkUnhealthy("server1.example.com:443", errors.New("test"))
time.Sleep(10 * time.Millisecond) // Small delay
tp.MarkUnhealthy("server2.example.com:443", errors.New("test"))
// Both are unhealthy, should select one (the one with shorter remaining backoff)
targetURL := tp.SelectTarget()
// Should return a valid target URL (not the upstream URL)
if targetURL == "https://logferry-api.example.com/" {
t.Error("Should select from unhealthy targets when all are unhealthy")
}
}
// TestGetTargetAddress tests URL parsing for health tracking.
func TestGetTargetAddress(t *testing.T) {
tests := []struct {
url string
want string
}{
{"https://server1.example.com:443/", "server1.example.com:443"},
{"https://server2.example.com:8443/api/v1", "server2.example.com:8443"},
{"https://example.com/", "example.com:443"},
{"http://example.com/path", "example.com:80"},
{"invalid", ""},
}
for _, tt := range tests {
t.Run(tt.url, func(t *testing.T) {
got := GetTargetAddress(tt.url)
if got != tt.want {
t.Errorf("GetTargetAddress(%q) = %q, want %q", tt.url, got, tt.want)
}
})
}
}
// TestWeightDistribution tests that weight-based selection is statistically correct.
func TestWeightDistribution(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "heavy.example.com", Port: 443, Priority: 10, Weight: 90},
{Target: "light.example.com", Port: 443, Priority: 10, Weight: 10},
}, nil)
tp.ResolveSRV(context.Background())
// Run many selections and count distribution
counts := make(map[string]int)
iterations := 10000
for i := 0; i < iterations; i++ {
targetURL := tp.SelectTarget()
counts[targetURL]++
}
heavyCount := counts["https://heavy.example.com:443/"]
lightCount := counts["https://light.example.com:443/"]
// With 90/10 weight ratio, heavy should get ~90% of selections
// Allow 5% margin for randomness
heavyRatio := float64(heavyCount) / float64(iterations)
if heavyRatio < 0.85 || heavyRatio > 0.95 {
t.Errorf("Weight distribution incorrect: heavy=%.2f%%, expected ~90%%", heavyRatio*100)
}
t.Logf("Distribution: heavy=%d (%.1f%%), light=%d (%.1f%%)",
heavyCount, heavyRatio*100, lightCount, float64(lightCount)/float64(iterations)*100)
}
// TestZeroWeightTreatedAsOne tests RFC 2782 weight=0 handling.
func TestZeroWeightTreatedAsOne(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 0},
{Target: "server2.example.com", Port: 443, Priority: 10, Weight: 0},
}, nil)
tp.ResolveSRV(context.Background())
// Both have weight 0 (treated as 1), should distribute roughly equally
counts := make(map[string]int)
iterations := 1000
for i := 0; i < iterations; i++ {
targetURL := tp.SelectTarget()
counts[targetURL]++
}
server1Count := counts["https://server1.example.com:443/"]
ratio := float64(server1Count) / float64(iterations)
// Should be roughly 50/50 with weight=0 (treated as 1 each)
if ratio < 0.40 || ratio > 0.60 {
t.Errorf("Zero weight distribution incorrect: server1=%.1f%%, expected ~50%%", ratio*100)
}
}
// TestStaleHealthStateCleanup tests that stale health state is cleaned up.
func TestStaleHealthStateCleanup(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
tp := NewTargetPool(upstreamURL, nil)
// Initial resolve with server1
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
// Mark server1 unhealthy to create health state
tp.MarkUnhealthy("server1.example.com:443", errors.New("test"))
// Now resolve without server1 (simulate removal)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server2.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
// First refresh - server1 should still have health state (staleness = 1)
tp.ResolveSRV(context.Background())
tp.mu.RLock()
_, hasServer1 := tp.healthState["server1.example.com:443"]
tp.mu.RUnlock()
if !hasServer1 {
t.Error("server1 health state should still exist after 1 refresh")
}
// Second refresh - server1 should still have health state (staleness = 2)
tp.ResolveSRV(context.Background())
tp.mu.RLock()
_, hasServer1 = tp.healthState["server1.example.com:443"]
tp.mu.RUnlock()
if !hasServer1 {
t.Error("server1 health state should still exist after 2 refreshes")
}
// Third refresh - server1 health state should be cleaned up (staleness = 3)
tp.ResolveSRV(context.Background())
tp.mu.RLock()
_, hasServer1 = tp.healthState["server1.example.com:443"]
tp.mu.RUnlock()
if hasServer1 {
t.Error("server1 health state should be cleaned up after 3 refreshes")
}
}
// TestUpdateTargetsChangeDetection tests that updateTargets correctly detects changes.
func TestUpdateTargetsChangeDetection(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
t.Run("identical targets report no change", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
targets := []*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 60},
{Target: "server2.example.com.", Port: 443, Priority: 10, Weight: 40},
}
tp.resolver = mockResolver(targets, nil)
tp.ResolveSRV(context.Background())
// Second call with same targets should not report a change
srvTargets := []SRVTarget{
{Host: "server1.example.com", Port: 443, Priority: 10, Weight: 60},
{Host: "server2.example.com", Port: 443, Priority: 10, Weight: 40},
}
changed := tp.updateTargets(srvTargets)
if changed {
t.Error("updateTargets should return false for identical targets")
}
})
t.Run("weight change detected", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 60},
{Target: "server2.example.com.", Port: 443, Priority: 10, Weight: 40},
}, nil)
tp.ResolveSRV(context.Background())
// Change weight on server1
srvTargets := []SRVTarget{
{Host: "server1.example.com", Port: 443, Priority: 10, Weight: 80},
{Host: "server2.example.com", Port: 443, Priority: 10, Weight: 20},
}
changed := tp.updateTargets(srvTargets)
if !changed {
t.Error("updateTargets should return true when weights change")
}
})
t.Run("added target detected", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
srvTargets := []SRVTarget{
{Host: "server1.example.com", Port: 443, Priority: 10, Weight: 60},
{Host: "server2.example.com", Port: 443, Priority: 10, Weight: 40},
}
changed := tp.updateTargets(srvTargets)
if !changed {
t.Error("updateTargets should return true when a target is added")
}
})
t.Run("removed target detected", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 60},
{Target: "server2.example.com.", Port: 443, Priority: 10, Weight: 40},
}, nil)
tp.ResolveSRV(context.Background())
srvTargets := []SRVTarget{
{Host: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
}
changed := tp.updateTargets(srvTargets)
if !changed {
t.Error("updateTargets should return true when a target is removed")
}
})
t.Run("priority change detected", func(t *testing.T) {
tp := NewTargetPool(upstreamURL, nil)
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com.", Port: 443, Priority: 10, Weight: 50},
{Target: "server2.example.com.", Port: 443, Priority: 10, Weight: 50},
}, nil)
tp.ResolveSRV(context.Background())
srvTargets := []SRVTarget{
{Host: "server1.example.com", Port: 443, Priority: 10, Weight: 50},
{Host: "server2.example.com", Port: 443, Priority: 20, Weight: 50},
}
changed := tp.updateTargets(srvTargets)
if !changed {
t.Error("updateTargets should return true when priority changes")
}
})
}
// TestNeedsRefresh tests TTL-based refresh checking.
func TestNeedsRefresh(t *testing.T) {
upstreamURL, _ := url.Parse("https://logferry-api.example.com/")
tp := NewTargetPool(upstreamURL, nil)
// Before any lookup, should need refresh
if !tp.NeedsRefresh(time.Minute) {
t.Error("Should need refresh before first lookup")
}
// After lookup, should not need refresh immediately
tp.resolver = mockResolver([]*net.SRV{
{Target: "server1.example.com", Port: 443, Priority: 10, Weight: 100},
}, nil)
tp.ResolveSRV(context.Background())
if tp.NeedsRefresh(time.Minute) {
t.Error("Should not need refresh immediately after lookup")
}
// With very short TTL, should need refresh
if !tp.NeedsRefresh(time.Nanosecond) {
t.Error("Should need refresh with expired TTL")
}
}