-
Notifications
You must be signed in to change notification settings - Fork 0
/
pooler_test.go
1158 lines (955 loc) · 30.1 KB
/
pooler_test.go
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package retrypool
import (
"context"
"errors"
"log"
"sync"
"testing"
"time"
)
// Define a simple worker that increments a counter
type IncrementWorker struct {
mu sync.Mutex
counter int
}
func (w *IncrementWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
defer w.mu.Unlock()
w.counter += data
return nil
}
// Define a worker that fails a certain number of times before succeeding
type FlakyWorker struct {
failuresLeft int
mu sync.Mutex
count int
}
func (w *FlakyWorker) Inc() int {
w.mu.Lock()
defer w.mu.Unlock()
w.count++
return w.count
}
func (w *FlakyWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
defer w.mu.Unlock()
time.Sleep(100 * time.Millisecond) // Simulate processing time
if w.failuresLeft > 0 {
w.failuresLeft--
return errors.New("temporary error")
}
return nil
}
// Define a worker that always returns an unrecoverable error
type UnrecoverableWorker struct{}
func (w *UnrecoverableWorker) Run(ctx context.Context, data int) error {
return Unrecoverable(errors.New("unrecoverable error"))
}
// Test basic task dispatch and processing
func TestBasicDispatch(t *testing.T) {
ctx := context.Background()
worker := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker})
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for the task to be processed
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.Close()
if worker.counter != 1 {
t.Errorf("Expected counter to be 1, got %d", worker.counter)
}
}
// Test task retries with a fixed delay
func TestRetriesWithFixedDelay(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 2}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithDelay[int](50*time.Millisecond),
WithDelayType[int](FixedDelay[int]),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for the task to be processed
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.Close()
if worker.failuresLeft != 0 {
t.Errorf("Expected failuresLeft to be 0, got %d", worker.failuresLeft)
}
}
// Test unlimited retries with backoff delay
func TestUnlimitedRetriesWithBackoff(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
worker := &FlakyWorker{failuresLeft: 5}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](UnlimitedAttempts),
WithDelay[int](100*time.Millisecond),
WithDelayType[int](BackOffDelay[int]),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 100*time.Millisecond)
if worker.failuresLeft != 0 {
t.Errorf("Expected failuresLeft to be 0, got %d", worker.failuresLeft)
}
}
// Test task time limit
func TestTaskTimeLimit(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 5}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](UnlimitedAttempts),
WithDelay[int](100*time.Millisecond),
WithDelayType[int](FixedDelay[int]),
)
err := pool.Dispatch(1, WithTimeLimit[int](500*time.Millisecond))
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.Close()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
if worker.failuresLeft > 3 {
t.Errorf("Expected failuresLeft to be less than or equal to 3, got %d", worker.failuresLeft)
}
}
// Test custom RetryIf function
func TestCustomRetryIf(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 2}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithRetryIf[int](func(err error) bool {
return err.Error() == "temporary error"
}),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.Close()
if worker.failuresLeft != 0 {
t.Errorf("Expected failuresLeft to be 0, got %d", worker.failuresLeft)
}
}
// Test OnRetry callback
func TestOnRetryCallback(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 2}
retryAttempts := 0
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithOnRetry[int](func(attempt int, err error, task *TaskWrapper[int]) {
retryAttempts++
log.Printf("Retry attempt %d for task %d due to error: %v", attempt, task.data, err)
}),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.Close()
if retryAttempts != 2 {
t.Errorf("Expected 2 retry attempts, got %d", retryAttempts)
}
if worker.failuresLeft != 0 {
t.Errorf("Expected failuresLeft to be 0, got %d", worker.failuresLeft)
}
}
// Test handling unrecoverable errors
func TestUnrecoverableError(t *testing.T) {
ctx := context.Background()
worker := &UnrecoverableWorker{}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.Close()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
if len(deadTasks[0].Errors) != 1 {
t.Errorf("Expected 1 error, got %d", len(deadTasks[0].Errors))
}
if deadTasks[0].Errors[0].Error() != "unrecoverable error" {
t.Errorf("Expected unrecoverable error, got %v", deadTasks[0].Errors[0])
}
}
// Test handling of multiple workers
func TestMultipleWorkers(t *testing.T) {
ctx := context.Background()
worker1 := &IncrementWorker{}
worker2 := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker1, worker2})
// Dispatch multiple tasks
for i := 0; i < 10; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
pool.Close()
totalCounter := worker1.counter + worker2.counter
if totalCounter != 10 {
t.Errorf("Expected total counter to be 10, got %d", totalCounter)
}
}
// Test processing count and queue size
func TestProcessingCountAndQueueSize(t *testing.T) {
ctx := context.Background()
worker := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker})
// Dispatch multiple tasks
for i := 0; i < 5; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
queueSize := pool.QueueSize()
if queueSize != 5 {
t.Errorf("Expected queue size to be 5, got %d", queueSize)
}
processingCount := pool.ProcessingCount()
if processingCount != 0 {
t.Errorf("Expected processing count to be 0, got %d", processingCount)
}
pool.Close()
if worker.counter != 5 {
t.Errorf("Expected counter to be 5, got %d", worker.counter)
}
}
// Test ForceClose
func TestForceClose(t *testing.T) {
ctx := context.Background()
worker := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker})
// Dispatch multiple tasks
for i := 0; i < 10; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
pool.ForceClose()
queueSize := pool.QueueSize()
if queueSize != 0 {
t.Errorf("Expected queue size to be 0 after ForceClose, got %d", queueSize)
}
processingCount := pool.ProcessingCount()
if processingCount != 0 {
t.Errorf("Expected processing count to be 0 after ForceClose, got %d", processingCount)
}
}
// Test WaitWithCallback
func TestWaitWithCallback(t *testing.T) {
ctx := context.Background()
worker := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker})
// Dispatch multiple tasks
for i := 0; i < 5; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
waitCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err := pool.WaitWithCallback(waitCtx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 100*time.Millisecond)
if err != nil {
t.Fatalf("WaitWithCallback failed: %v", err)
}
if worker.counter != 5 {
t.Errorf("Expected counter to be 5, got %d", worker.counter)
}
}
// TestMaxDelay ensures that the delay doesn't exceed the maximum specified delay
func TestMaxDelay(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
worker := &FlakyWorker{failuresLeft: 10}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](5), // Limit attempts to ensure the task fails
WithDelay[int](100*time.Millisecond),
WithMaxDelay[int](300*time.Millisecond),
WithDelayType[int](BackOffDelay[int]),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Close()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Fatalf("Expected 1 dead task, got %d", len(deadTasks))
}
deadTask := deadTasks[0]
if deadTask.TotalDuration > 5*(300*time.Millisecond+100*time.Millisecond) {
t.Errorf("Total duration exceeded expected maximum: %v", deadTask.TotalDuration)
}
}
// Test MaxJitter with RandomDelay
func TestMaxJitterWithRandomDelay(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 1}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithMaxJitter[int](100*time.Millisecond),
WithDelayType[int](RandomDelay[int]),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
startTime := time.Now()
pool.Close()
elapsedTime := time.Since(startTime)
// Expected maximum time is processing time + max jitter + processing time
expectedMaxTime := 100*time.Millisecond + // Initial processing time
100*time.Millisecond + // Max jitter delay
100*time.Millisecond // Second processing time
if elapsedTime > expectedMaxTime+50*time.Millisecond { // Adding buffer for overhead
t.Errorf("Expected total retry time to be less than %v, got %v", expectedMaxTime+50*time.Millisecond, elapsedTime)
}
}
// TestContextCancellation ensures that the pool stops processing when the context is canceled
func TestContextCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
worker := &FlakyWorker{failuresLeft: 10}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](UnlimitedAttempts),
WithDelay[int](100*time.Millisecond),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Cancel the context after a short delay
time.AfterFunc(300*time.Millisecond, cancel)
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != context.Canceled {
t.Fatalf("Expected context.Canceled error, got: %v", err)
}
pool.Close()
if worker.failuresLeft >= 10 {
t.Errorf("Expected some attempts to be made before cancellation")
}
}
// TestTimeLimitWithUnlimitedRetries tests a task with time limit and unlimited retries
func TestTimeLimitWithUnlimitedRetries(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 10}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](UnlimitedAttempts),
WithDelay[int](50*time.Millisecond),
WithDelayType[int](FixedDelay[int]),
)
err := pool.Dispatch(1, WithTimeLimit[int](300*time.Millisecond))
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.Close()
// The exact number of failures may vary due to timing, so we check for a range
if worker.failuresLeft > 7 || worker.failuresLeft < 5 {
t.Errorf("Expected failuresLeft to be between 5 and 7 due to time limit, got %d", worker.failuresLeft)
}
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
}
// Test multiple tasks processed by multiple workers
func TestMultipleTasksMultipleWorkers(t *testing.T) {
ctx := context.Background()
worker1 := &IncrementWorker{}
worker2 := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker1, worker2})
// Dispatch multiple tasks
for i := 0; i < 20; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
pool.Close()
totalCounter := worker1.counter + worker2.counter
if totalCounter != 20 {
t.Errorf("Expected total counter to be 20, got %d", totalCounter)
}
}
// TestMaxAttempts tests that the pool stops retrying after max attempts
func TestMaxAttempts(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 10}
maxAttempts := 3
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](maxAttempts),
WithDelay[int](50*time.Millisecond),
WithDelayType[int](FixedDelay[int]),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.Close()
expectedFailuresLeft := 10 - maxAttempts
if worker.failuresLeft != expectedFailuresLeft {
t.Errorf("Expected failuresLeft to be %d after max attempts, got %d", expectedFailuresLeft, worker.failuresLeft)
}
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
}
// Test that unrecoverable errors are not retried even if RetryIf allows it
func TestUnrecoverableErrorWithCustomRetryIf(t *testing.T) {
ctx := context.Background()
worker := &UnrecoverableWorker{}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithRetryIf[int](func(err error) bool {
return true // Retry on all errors
}),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.Close()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
if len(deadTasks[0].Errors) != 1 {
t.Errorf("Expected 1 error, got %d", len(deadTasks[0].Errors))
}
if deadTasks[0].Errors[0].Error() != "unrecoverable error" {
t.Errorf("Expected unrecoverable error, got %v", deadTasks[0].Errors[0])
}
}
// CustomTimer implements the Timer interface for testing purposes
type CustomTimer struct {
durations []time.Duration
mu sync.Mutex
called bool // Add this field to track if After was called
}
func (t *CustomTimer) After(d time.Duration) <-chan time.Time {
t.mu.Lock()
defer t.mu.Unlock()
t.durations = append(t.durations, d)
t.called = true // Set this to true when After is called
return time.After(d)
}
// TestCustomTimer tests the custom timer implementation
func TestCustomTimer(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 2}
customTimer := &CustomTimer{}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](3),
WithDelay[int](100*time.Millisecond),
WithDelayType[int](FixedDelay[int]),
WithTimer[int](customTimer),
)
// Verify that the custom timer was set correctly
if pool.timer != customTimer {
t.Fatalf("Custom timer was not set correctly in the pool")
}
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for the task to be processed
time.Sleep(500 * time.Millisecond)
pool.Close()
// Add debug output
t.Logf("Timer called: %v", customTimer.called)
t.Logf("Number of durations: %d", len(customTimer.durations))
t.Logf("Durations: %v", customTimer.durations)
if !customTimer.called {
t.Error("Expected custom timer to be called, but it wasn't")
}
expectedCalls := 2 // We expect 2 calls because the task fails twice before succeeding
if len(customTimer.durations) != expectedCalls {
t.Errorf("Expected %d delay durations recorded, got %d", expectedCalls, len(customTimer.durations))
}
expectedDuration := 100 * time.Millisecond
allowedDeviation := 1 * time.Millisecond
for _, d := range customTimer.durations {
if d < expectedDuration-allowedDeviation || d > expectedDuration+allowedDeviation {
t.Errorf("Expected delay of %v (±%v), got %v", expectedDuration, allowedDeviation, d)
}
}
}
// TestDynamicWorkerManagement tests adding and removing workers dynamically
func TestDynamicWorkerManagement(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
worker1 := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker1})
// Dispatch initial tasks
for i := 0; i < 5; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
t.Log("first dispatch ", pool.QueueSize())
// Wait for initial tasks to be processed
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.RemoveWorker(0)
// Add a new worker dynamically
worker2 := &IncrementWorker{}
pool.AddWorker(worker2)
// Dispatch more tasks after adding worker2
for i := 0; i < 5; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
t.Log("second dispatch ", pool.QueueSize())
// Wait for all tasks to be processed
pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
pool.Close()
totalCounter := worker1.counter + worker2.counter
if totalCounter != 10 {
t.Errorf("Expected total counter to be 10, got %d", totalCounter)
}
if worker1.counter == 0 || worker2.counter == 0 {
t.Errorf("Expected both workers to process tasks, got worker1: %d, worker2: %d", worker1.counter, worker2.counter)
}
t.Logf("Worker1 counter: %d, Worker2 counter: %d", worker1.counter, worker2.counter)
}
// TestRemoveWorker tests removing a worker from the pool
func TestRemoveWorker(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
worker1 := &IncrementWorker{}
worker2 := &IncrementWorker{}
pool := New(ctx, []Worker[int]{worker1, worker2})
// Dispatch multiple tasks
for i := 0; i < 20; i++ {
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
// Wait for some tasks to be processed
time.Sleep(100 * time.Millisecond)
// Remove worker1 (assuming workerID is 0)
err := pool.RemoveWorker(0)
if err != nil {
t.Fatalf("Failed to remove worker: %v", err)
}
// Wait for all tasks to be processed
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Close()
totalCounter := worker1.counter + worker2.counter
if totalCounter != 20 {
t.Errorf("Expected total counter to be 20, got %d", totalCounter)
}
// Check that worker2 processed tasks after worker1 was removed
if worker2.counter == 0 {
t.Errorf("Expected worker2 to process tasks after worker1 removal")
}
t.Logf("Worker1 counter: %d, Worker2 counter: %d", worker1.counter, worker2.counter)
}
// Define a SlowWorker for testing InterruptWorker
type SlowWorker struct {
processing bool
mu sync.Mutex
started chan struct{}
}
func (w *SlowWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
w.processing = true
if w.started != nil {
close(w.started) // Signal that processing has started
}
w.mu.Unlock()
defer func() {
w.mu.Lock()
w.processing = false
w.mu.Unlock()
}()
select {
case <-time.After(500 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// TestInterruptWorker tests interrupting a worker
func TestInterruptWorker(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
worker := &SlowWorker{
started: make(chan struct{}),
}
pool := New(ctx, []Worker[int]{worker},
WithRetryIf[int](func(err error) bool {
return err.Error() == "worker interrupted"
}),
)
// Dispatch a task
for i := 0; i < 10; i++ {
err := pool.Dispatch(i)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
// Wait for the worker to start processing
select {
case <-worker.started:
case <-ctx.Done():
t.Fatal("Timed out waiting for worker to start")
}
// Interrupt the worker (assuming workerID is 0)
err := pool.RemoveWorker(0)
if err != nil {
t.Fatalf("Failed to interrupt worker: %v", err)
}
// Wait for a bit to allow requeueing
time.Sleep(100 * time.Millisecond)
// Check that the task is either requeued or being processed
queueSize := pool.QueueSize()
processingCount := pool.ProcessingCount()
if queueSize == 0 && processingCount == 0 {
t.Errorf("Expected task to be requeued or processing, got queue size: %d, processing count: %d", queueSize, processingCount)
}
// Wait for the task to be processed
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Close()
t.Logf("Final queue size: %d, processing count: %d", pool.QueueSize(), pool.ProcessingCount())
}
// TestOnTaskSuccessAndFailureCallbacks tests the OnTaskSuccess and OnTaskFailure callbacks
func TestOnTaskSuccessAndFailureCallbacks(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 1}
var successCalled, failureCalled bool
var mu sync.Mutex
var counter int
pool := New(ctx, []Worker[int]{worker},
WithOnTaskSuccess[int](func(controller WorkerController[int], workerID int, worker Worker[int], task *TaskWrapper[int]) {
mu.Lock()
successCalled = true
mu.Unlock()
}),
WithOnTaskFailure[int](func(controller WorkerController[int], workerID int, worker Worker[int], task *TaskWrapper[int], err error) DeadTaskAction {
mu.Lock()
failureCalled = true
if f, ok := worker.(*FlakyWorker); ok {
counter = f.Inc()
}
mu.Unlock()
return DeadTaskActionRetry
}),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != nil {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Close()
if counter != 1 {
t.Errorf("Expected counter to be 1, got %d", counter)
}
mu.Lock()
defer mu.Unlock()
if !successCalled {
t.Errorf("Expected OnTaskSuccess callback to be called")
}
if !failureCalled {
t.Errorf("Expected OnTaskFailure callback to be called")
}
}
// Define FailingWorker that implements Worker[int]
type FailingWorker struct {
id int
processed []int
mu sync.Mutex
}
func (worker *FailingWorker) Run(ctx context.Context, data int) error {
worker.mu.Lock()
worker.processed = append(worker.processed, data)
worker.mu.Unlock()
return errors.New("intentional error")
}
// TestTriedWorkersHandling tests that tasks are not retried by the same worker unless all workers have tried
func TestTriedWorkersHandling(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
numWorkers := 3
workers := make([]Worker[int], numWorkers)
failingWorkers := make([]*FailingWorker, numWorkers)
for i := 0; i < numWorkers; i++ {
worker := &FailingWorker{id: i}
failingWorkers[i] = worker
workers[i] = worker
}
pool := New(ctx, workers,
WithAttempts[int](numWorkers),
WithRetryIf[int](func(err error) bool {
return true
}),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != nil {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Close()
// Now, check that each worker has processed the task once
for i, worker := range failingWorkers {
if len(worker.processed) != 1 {
t.Errorf("Expected worker %d to process the task once, got %d", i, len(worker.processed))
}
}
}
// TestDeadTaskErrorsAndDurations tests that DeadTask contains correct total duration
func TestDeadTaskErrorsAndDurations(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 3}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithDelay[int](200*time.Millisecond),
WithDelayType[int](FixedDelay[int]),
)
err := pool.Dispatch(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
err = pool.WaitWithCallback(ctx, func(queueSize, processingCount, deadTaskCount int) bool {
return queueSize > 0 || processingCount > 0
}, 10*time.Millisecond)
if err != nil {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Close()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
deadTask := deadTasks[0]
// Check totalDuration
expectedMinDuration := 100 * time.Millisecond // At least one processing time
if deadTask.TotalDuration < expectedMinDuration {
t.Errorf("Expected total duration at least %v, got %v", expectedMinDuration, deadTask.TotalDuration)
}
// Check number of errors
if len(deadTask.Errors) != 2 {
t.Errorf("Expected 2 error, got %d", len(deadTask.Errors))
}
// Check error messages
if deadTask.Errors[0].Error() != "temporary error" {
t.Errorf("Expected 'temporary error', got '%v'", deadTask.Errors[0])
}
t.Logf("Dead task details: Retries: %d, TotalDuration: %v, Errors: %v", deadTask.Retries, deadTask.TotalDuration, deadTask.Errors)
}
// TestCombineDelayAndMaxBackOffN tests CombineDelay and maxBackOffN logic
func TestCombineDelayAndMaxBackOffN(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 5}
delays := make([]time.Duration, 0)
var mu sync.Mutex
// Custom DelayTypeFunc that records the delays
recordingDelay := func(n int, err error, config *Config[int]) time.Duration {
delay := config.delay << n
mu.Lock()
delays = append(delays, delay)
mu.Unlock()
return delay