-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool_test.go
More file actions
848 lines (722 loc) · 17.4 KB
/
Copy pathpool_test.go
File metadata and controls
848 lines (722 loc) · 17.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
package email
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// waitFor polls condition until it returns true or the timeout elapses.
func waitFor(t *testing.T, timeout time.Duration, interval time.Duration, condition func() bool) {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if condition() {
return
}
time.Sleep(interval)
}
t.Fatalf("waitFor timed out after %v", timeout)
}
// fakeSMTPServer is a minimal SMTP server for testing the connection pool.
type fakeSMTPServer struct {
listener net.Listener
addr string
connCount atomic.Int64
msgCount atomic.Int64
mu sync.Mutex
failAuth bool
failRSET bool
failAfterN int // fail DATA after N messages per connection
closed atomic.Bool
}
func newFakeSMTPServer(t *testing.T) *fakeSMTPServer {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
s := &fakeSMTPServer{
listener: ln,
addr: ln.Addr().String(),
}
go s.serve(t)
return s
}
func (s *fakeSMTPServer) serve(t *testing.T) {
t.Helper()
for {
conn, err := s.listener.Accept()
if err != nil {
if s.closed.Load() {
return
}
return
}
s.connCount.Add(1)
go s.handleConn(t, conn)
}
}
func (s *fakeSMTPServer) handleConn(t *testing.T, conn net.Conn) {
t.Helper()
defer conn.Close() //nolint:errcheck
reader := bufio.NewReader(conn)
write := func(msg string) {
fmt.Fprintf(conn, "%s\r\n", msg)
}
write("220 localhost ESMTP fake")
msgOnConn := 0
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
cmd := strings.ToUpper(strings.TrimRight(line, "\r\n"))
action := s.dispatch(cmd, reader, write, &msgOnConn)
if action == connClose {
return
}
}
}
// connAction indicates what the connection loop should do after handling a command.
type connAction int
const (
connContinue connAction = iota
connClose
)
func (s *fakeSMTPServer) dispatch(cmd string, reader *bufio.Reader, write func(string), msgOnConn *int) connAction {
switch {
case strings.HasPrefix(cmd, "EHLO") || strings.HasPrefix(cmd, "HELO"):
write("250-localhost")
write("250-AUTH PLAIN LOGIN")
write("250 OK")
case strings.HasPrefix(cmd, "AUTH"):
s.handleAuth(write)
case strings.HasPrefix(cmd, "MAIL FROM:"):
write("250 OK")
case strings.HasPrefix(cmd, "RCPT TO:"):
write("250 OK")
case cmd == "DATA":
if action := s.handleData(reader, write, msgOnConn); action != connContinue {
return action
}
case cmd == "RSET":
return s.handleReset(write)
case cmd == "QUIT":
write("221 Bye")
return connClose
case cmd == "NOOP":
write("250 OK")
case strings.HasPrefix(cmd, "STARTTLS"):
write("502 Not implemented")
default:
write("500 Unrecognized command")
}
return connContinue
}
func (s *fakeSMTPServer) handleAuth(write func(string)) {
s.mu.Lock()
fail := s.failAuth
s.mu.Unlock()
if fail {
write("535 Authentication failed")
} else {
write("235 Authentication successful")
}
}
func (s *fakeSMTPServer) handleData(reader *bufio.Reader, write func(string), msgOnConn *int) connAction {
s.mu.Lock()
failN := s.failAfterN
s.mu.Unlock()
if failN > 0 && *msgOnConn >= failN {
write("452 Too many messages")
return connContinue
}
write("354 Start mail input")
for {
dataLine, derr := reader.ReadString('\n')
if derr != nil {
return connClose
}
if strings.TrimRight(dataLine, "\r\n") == "." {
break
}
}
*msgOnConn++
s.msgCount.Add(1)
write("250 OK")
return connContinue
}
func (s *fakeSMTPServer) handleReset(write func(string)) connAction {
s.mu.Lock()
fail := s.failRSET
s.mu.Unlock()
if fail {
write("421 Service not available")
return connClose
}
write("250 OK")
return connContinue
}
func (s *fakeSMTPServer) close() {
s.closed.Store(true)
s.listener.Close() //nolint:errcheck
}
func (s *fakeSMTPServer) port() int {
return s.listener.Addr().(*net.TCPAddr).Port
}
// helper to create a pool pointing at the fake server
func newTestPool(t *testing.T, srv *fakeSMTPServer, poolSize int) *smtpPool {
t.Helper()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: poolSize,
}
p := newSMTPPool(cfg, NoOpLogger{})
t.Cleanup(func() { p.close() })
return p
}
func TestPoolBasicReuse(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
p := newTestPool(t, srv, 2)
ctx := context.Background()
// Get a connection
pc1, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
// Return it
p.put(pc1)
// Get again — should be the same connection (LIFO reuse)
pc2, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
if pc1 != pc2 {
t.Error("expected same connection to be reused")
}
p.put(pc2)
}
func TestPoolConnectionReuse(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
}
sender, err := NewSMTPSender(cfg)
if err != nil {
t.Fatalf("NewSMTPSender: %v", err)
}
defer sender.Close() //nolint:errcheck
ctx := context.Background()
// Send two emails
for i := range 2 {
e := &Email{
From: "sender@example.com",
To: []string{"recipient@example.com"},
Subject: fmt.Sprintf("Test %d", i),
Body: "Hello",
Headers: make(map[string]string),
}
if sendErr := sender.Send(ctx, e); sendErr != nil {
t.Fatalf("send %d: %v", i, sendErr)
}
}
// Should have used only 1 TCP connection
if n := srv.connCount.Load(); n != 1 {
t.Errorf("expected 1 TCP connection, got %d", n)
}
if n := srv.msgCount.Load(); n != 2 {
t.Errorf("expected 2 messages, got %d", n)
}
}
func TestPoolMaxConnections(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
poolSize := 3
p := newTestPool(t, srv, poolSize)
ctx := context.Background()
// Check out poolSize connections
conns := make([]*pooledConn, poolSize)
for i := range poolSize {
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get %d: %v", i, err)
}
conns[i] = pc
}
// Pool should be exhausted — verify numOpen
p.mu.Lock()
numOpen := p.numOpen
p.mu.Unlock()
if numOpen != poolSize {
t.Errorf("expected numOpen=%d, got %d", poolSize, numOpen)
}
// Return them
for _, pc := range conns {
p.put(pc)
}
}
func TestPoolWaitTimeout(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 1,
PoolWaitTimeout: 50 * time.Millisecond,
}
p := newSMTPPool(cfg, NoOpLogger{})
defer p.close()
ctx := context.Background()
// Check out the only connection
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
// Second get should timeout
_, err = p.get(ctx)
if !errors.Is(err, ErrPoolTimeout) {
t.Errorf("expected ErrPoolTimeout, got %v", err)
}
p.put(pc)
}
func TestPoolContextCancellation(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 1,
PoolWaitTimeout: 5 * time.Second,
}
p := newSMTPPool(cfg, NoOpLogger{})
defer p.close()
ctx := context.Background()
// Exhaust the pool
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
// Cancelled context
cancelCtx, cancel := context.WithCancel(ctx)
cancel()
_, err = p.get(cancelCtx)
if !errors.Is(err, context.Canceled) {
t.Errorf("expected context.Canceled, got %v", err)
}
p.put(pc)
}
func TestPoolHealthCheckFailure(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
p := newTestPool(t, srv, 2)
ctx := context.Background()
// Get and return a connection
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
p.put(pc)
// Now make RSET fail
srv.mu.Lock()
srv.failRSET = true
srv.mu.Unlock()
connsBefore := srv.connCount.Load()
// Get should discard the stale conn and dial a fresh one.
// But the fresh one will also fail RSET on health check if we don't
// restore RSET. Restore it so the fresh dial's first use works.
go func() {
time.Sleep(20 * time.Millisecond)
srv.mu.Lock()
srv.failRSET = false
srv.mu.Unlock()
}()
pc2, err := p.get(ctx)
if err != nil {
t.Fatalf("get after RSET failure: %v", err)
}
// Should have dialed at least one new connection
if srv.connCount.Load() <= connsBefore {
t.Error("expected a new connection to be dialed after health check failure")
}
p.put(pc2)
}
func TestPoolMaxMessages(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
MaxMessages: 2,
}
p := newSMTPPool(cfg, NoOpLogger{})
defer p.close()
ctx := context.Background()
// Get, increment message count to the limit, return
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
pc.msgCount = 2 // at the limit
p.put(pc)
connsBefore := srv.connCount.Load()
// Next get should discard the expired conn and dial fresh
pc2, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
if srv.connCount.Load() <= connsBefore {
t.Error("expected new connection after maxMessages exceeded")
}
p.put(pc2)
}
func TestPoolMaxLifetime(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
PoolMaxLifetime: 50 * time.Millisecond,
}
p := newSMTPPool(cfg, NoOpLogger{})
defer p.close()
ctx := context.Background()
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
p.put(pc)
// Wait for the connection to expire
waitFor(t, 200*time.Millisecond, 10*time.Millisecond, func() bool {
return time.Since(pc.createdAt) > 50*time.Millisecond
})
connsBefore := srv.connCount.Load()
pc2, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
if srv.connCount.Load() <= connsBefore {
t.Error("expected new connection after lifetime expired")
}
p.put(pc2)
}
func TestPoolIdleEviction(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
PoolMaxIdleTime: 30 * time.Millisecond,
}
p := newSMTPPool(cfg, NoOpLogger{})
defer p.close()
ctx := context.Background()
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
p.put(pc)
// Verify there's one idle conn
p.mu.Lock()
idleBefore := len(p.idle)
p.mu.Unlock()
if idleBefore != 1 {
t.Fatalf("expected 1 idle conn, got %d", idleBefore)
}
// Wait for cleaner to evict (cleaner runs every 100ms minimum interval)
// After 300ms the 30ms idle limit is well exceeded.
time.Sleep(300 * time.Millisecond)
p.mu.Lock()
idleAfter := len(p.idle)
p.mu.Unlock()
if idleAfter != 0 {
t.Errorf("expected 0 idle conns after eviction, got %d", idleAfter)
}
}
func TestPoolClose(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
}
p := newSMTPPool(cfg, NoOpLogger{})
ctx := context.Background()
// Get and return a connection
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
p.put(pc)
// Close the pool
closeErr := p.close()
if closeErr != nil {
t.Fatalf("close: %v", closeErr)
}
// Subsequent get should fail
_, err = p.get(ctx)
if !errors.Is(err, ErrPoolClosed) {
t.Errorf("expected ErrPoolClosed, got %v", err)
}
// Double close should be safe
closeErr = p.close()
if closeErr != nil {
t.Errorf("double close: %v", closeErr)
}
}
func TestPoolCloseWithActive(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
}
p := newSMTPPool(cfg, NoOpLogger{})
ctx := context.Background()
// Check out a connection
pc, err := p.get(ctx)
if err != nil {
t.Fatalf("get: %v", err)
}
// Close the pool while connection is checked out
if err := p.close(); err != nil {
t.Fatalf("close: %v", err)
}
// Returning the connection should clean it up without panic
p.put(pc)
p.mu.Lock()
numOpen := p.numOpen
p.mu.Unlock()
if numOpen != 0 {
t.Errorf("expected numOpen=0 after put on closed pool, got %d", numOpen)
}
}
func TestPoolConcurrentBatch(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
poolSize := 5
numEmails := 20
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: poolSize,
MaxIdleConns: poolSize, // match pool size to prevent idle eviction under -race
RateLimit: -1, // disable rate limiter
}
sender, err := NewSMTPSender(cfg)
if err != nil {
t.Fatalf("NewSMTPSender: %v", err)
}
defer sender.Close() //nolint:errcheck
ctx := context.Background()
var wg sync.WaitGroup
errCh := make(chan error, numEmails)
for i := range numEmails {
wg.Add(1)
go func() {
defer wg.Done()
e := &Email{
From: "sender@example.com",
To: []string{"recipient@example.com"},
Subject: fmt.Sprintf("Batch %d", i),
Body: "Hello",
Headers: make(map[string]string),
}
if sendErr := sender.Send(ctx, e); sendErr != nil {
errCh <- sendErr
}
}()
}
wg.Wait()
close(errCh)
for sendErr := range errCh {
t.Errorf("send error: %v", sendErr)
}
if n := srv.msgCount.Load(); n != int64(numEmails) {
t.Errorf("expected %d messages, got %d", numEmails, n)
}
// Should not exceed pool size connections
if n := srv.connCount.Load(); n > int64(poolSize) {
t.Errorf("expected at most %d connections, got %d", poolSize, n)
}
}
func TestPoolDialFailure(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
PoolWaitTimeout: 100 * time.Millisecond,
}
p := newSMTPPool(cfg, NoOpLogger{})
defer p.close()
// Override dial to fail
dialErr := errors.New("simulated dial failure")
p.dialFn = func(_ context.Context) (*pooledConn, error) {
return nil, dialErr
}
ctx := context.Background()
_, err := p.get(ctx)
if !errors.Is(err, dialErr) {
t.Errorf("expected dial error, got %v", err)
}
// numOpen should be back to 0
p.mu.Lock()
numOpen := p.numOpen
p.mu.Unlock()
if numOpen != 0 {
t.Errorf("expected numOpen=0 after dial failure, got %d", numOpen)
}
}
func TestPoolNoPoolBackwardCompat(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 0, // pooling disabled
}
sender, err := NewSMTPSender(cfg)
if err != nil {
t.Fatalf("NewSMTPSender: %v", err)
}
defer sender.Close() //nolint:errcheck
if sender.pool != nil {
t.Error("expected pool to be nil when PoolSize=0")
}
ctx := context.Background()
// Send two emails — should use separate connections (no reuse)
for i := range 2 {
e := &Email{
From: "sender@example.com",
To: []string{"recipient@example.com"},
Subject: fmt.Sprintf("Test %d", i),
Body: "Hello",
Headers: make(map[string]string),
}
if sendErr := sender.Send(ctx, e); sendErr != nil {
t.Fatalf("send %d: %v", i, sendErr)
}
}
if n := srv.connCount.Load(); n != 2 {
t.Errorf("expected 2 separate connections (no pool), got %d", n)
}
}
func TestPoolCleanerStops(t *testing.T) {
srv := newFakeSMTPServer(t)
defer srv.close()
cfg := SMTPConfig{
Host: "127.0.0.1",
Port: srv.port(),
Timeout: 5 * time.Second,
PoolSize: 2,
PoolMaxIdleTime: 100 * time.Millisecond,
}
p := newSMTPPool(cfg, NoOpLogger{})
// Close the pool and verify cleaner channel is closed
p.close()
// cleanerCh should be closed — reading should not block
select {
case <-p.cleanerCh:
// ok — channel is closed
case <-time.After(time.Second):
t.Error("cleanerCh should be closed after pool.close()")
}
}
func TestPoolConfigValidation(t *testing.T) {
tests := []struct {
name string
config SMTPConfig
wantErr bool
}{
{
name: "negative pool size",
config: SMTPConfig{
Host: "smtp.example.com",
Port: 587,
PoolSize: -1,
},
wantErr: true,
},
{
name: "negative max idle",
config: SMTPConfig{
Host: "smtp.example.com",
Port: 587,
PoolSize: 5,
MaxIdleConns: -1,
},
wantErr: true,
},
{
name: "max idle exceeds pool size",
config: SMTPConfig{
Host: "smtp.example.com",
Port: 587,
PoolSize: 2,
MaxIdleConns: 5,
},
wantErr: true,
},
{
name: "negative max messages",
config: SMTPConfig{
Host: "smtp.example.com",
Port: 587,
PoolSize: 5,
MaxMessages: -1,
},
wantErr: true,
},
{
name: "valid pool config",
config: SMTPConfig{
Host: "smtp.example.com",
Port: 587,
PoolSize: 5,
MaxIdleConns: 3,
MaxMessages: 50,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate()
if tt.wantErr && err == nil {
t.Error("expected error, got nil")
}
if !tt.wantErr && err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
}