-
Notifications
You must be signed in to change notification settings - Fork 0
/
pooler_test.go
1176 lines (957 loc) · 28.3 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"
"fmt"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/davidroman0O/retrypool/logs"
)
// Define an IncrementWorker that increments a counter
type IncrementWorker struct {
mu sync.Mutex
counter int
}
func (w *IncrementWorker) Run(ctx context.Context, data int) error {
fmt.Println("called", data)
w.mu.Lock()
w.counter += data
w.mu.Unlock()
return nil
}
// Define an SlowIncrementWorker that increments a counter
type SlowIncrementWorker struct {
mu sync.Mutex
counter int
}
func (w *SlowIncrementWorker) Run(ctx context.Context, data int) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(100 * time.Millisecond):
fmt.Println("called", data)
w.mu.Lock()
w.counter += data
w.mu.Unlock()
}
return nil
}
// Define a FlakyWorker that fails a certain number of times before succeeding
type FlakyWorker struct {
failuresLeft int
mu sync.Mutex
count int
}
func (w *FlakyWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.failuresLeft > 0 {
w.failuresLeft--
return errors.New("temporary error")
}
return nil
}
// Define a FailingWorker that always fails
type FailingWorker struct {
mu sync.Mutex
counter int
}
func (w *FailingWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
w.counter++
w.mu.Unlock()
return errors.New("task failed")
}
// Define a testPanicWorker that panics during execution
type testPanicWorker struct{}
func (w *testPanicWorker) Run(ctx context.Context, data int) error {
panic("worker panic")
}
// Define a SlowWorker that sleeps
type SlowWorker struct {
mu sync.Mutex
processing bool
started chan struct{}
}
func (w *SlowWorker) IsProcessing() bool {
w.mu.Lock()
defer w.mu.Unlock()
return w.processing
}
func (w *SlowWorker) Run(ctx context.Context, data int) error {
fmt.Println("called", data)
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()
}
}
// Define a worker that counts the number of times Run is called
type CountingWorker struct {
mu sync.Mutex
counter int
}
func (w *CountingWorker) Run(ctx context.Context, data int) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(100 * time.Millisecond):
fmt.Println("called", data)
w.mu.Lock()
w.counter++
w.mu.Unlock()
}
return nil
}
func (w *CountingWorker) GetCount() int {
w.mu.Lock()
defer w.mu.Unlock()
return w.counter
}
// Define a worker that sleeps longer than max duration per attempt
type VerySlowWorker struct {
mu sync.Mutex
counter int
}
func (w *VerySlowWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
w.counter++
w.mu.Unlock()
time.Sleep(300 * time.Millisecond)
return errors.New("task failed")
}
// Define a worker that panics on first task, succeeds on second
type PanicThenSuccessWorker struct {
mu sync.Mutex
panicCount int
}
func (w *PanicThenSuccessWorker) Run(ctx context.Context, data int) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.panicCount == 0 {
w.panicCount++
panic("worker panic")
}
return nil
}
// Define a worker that records the data it processes
type RecordingWorker struct {
mu sync.Mutex
tasks []int
}
func (w *RecordingWorker) Run(ctx context.Context, data int) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(100 * time.Millisecond):
w.mu.Lock()
w.tasks = append(w.tasks, data)
w.mu.Unlock()
}
return nil
}
// TestAddWorkerDynamically verifies that adding a worker during task processing
// results in the worker starting to process tasks immediately.
func TestAddWorkerDynamically(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Create initial worker
initialWorker := &RecordingWorker{}
var worker1Tasks, worker2Tasks []int
var taskMu sync.Mutex
// Create pool with initial worker
pool := New(ctx, []Worker[int]{initialWorker},
WithOnTaskSuccess[int](func(_ WorkerController[int], workerID int, _ Worker[int], task *TaskWrapper[int]) {
taskMu.Lock()
if workerID == 0 {
worker1Tasks = append(worker1Tasks, task.Data())
} else {
worker2Tasks = append(worker2Tasks, task.Data())
}
taskMu.Unlock()
}),
)
// Dispatch tasks
for i := 0; i < 10; i++ {
err := pool.Submit(i)
if err != nil {
t.Fatalf("Failed to dispatch task %d: %v", i, err)
}
}
// Wait a moment to let initialWorker start processing
time.Sleep(100 * time.Millisecond)
// Add new worker dynamically
newWorker := &RecordingWorker{}
newWorkerID := pool.AddWorker(newWorker)
if newWorkerID <= 0 {
t.Errorf("Expected new worker ID to be greater than 0, got %d", newWorkerID)
}
// Wait for 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)
}
if err := pool.Shutdown(); err != nil {
if err != context.Canceled {
t.Fatalf("Failed to close pool: %v", err)
}
}
// Check newWorker processed tasks
newWorker.mu.Lock()
newWorkerTaskCount := len(newWorker.tasks)
newWorker.mu.Unlock()
if newWorkerTaskCount == 0 {
t.Errorf("Expected new worker to process tasks")
}
t.Logf("Worker1 tasks: %v", worker1Tasks)
t.Logf("Worker2 tasks: %v", worker2Tasks)
if len(worker2Tasks) == 0 {
t.Error("Second worker didn't process any tasks")
}
}
// TestRemoveWorkerDuringProcessing verifies that removing a worker during processing
// results in its tasks being reassigned and processed by other workers.
func TestRemoveWorkerDuringProcessing(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}, WithLogLevel[int](logs.LevelDebug))
// Dispatch tasks
for i := 0; i < 10; i++ {
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task %d: %v", i, err)
}
}
// Wait a moment to let workers start processing
time.Sleep(100 * time.Millisecond)
// Remove worker1
err := pool.RemoveWorker(0)
if err != nil {
t.Fatalf("Failed to remove worker: %v", err)
}
// Wait for tasks to be processed
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
totalCounter := worker1.counter + worker2.counter
if totalCounter != 10 {
t.Errorf("Expected total counter to be 10, got %d", totalCounter)
}
if worker1.counter == 0 {
t.Errorf("Expected worker1 to have processed tasks before removal")
}
if worker2.counter == 0 {
t.Errorf("Expected worker2 to process tasks after removal")
}
}
// TestInterruptWorkerWithRemoveWorkerOption verifies that interrupting a worker
// with the WithRemoveWorker option removes the worker and reassigns its tasks.
func TestInterruptWorkerWithRemoveWorkerOption(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}, WithLogLevel[int](logs.LevelDebug))
// Dispatch tasks
for i := 0; i < 10; i++ {
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task %d: %v", i, err)
}
}
// Wait a moment
time.Sleep(100 * time.Millisecond)
// Interrupt worker1 with WithRemoveWorker
err := pool.InterruptWorker(0, WithRemoveWorker())
if err != nil {
t.Fatalf("Failed to interrupt and remove worker: %v", err)
}
// Wait for tasks to be processed
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
totalCounter := worker1.counter + worker2.counter
if totalCounter != 10 {
t.Errorf("Expected total counter to be 10, got %d", totalCounter)
}
if worker1.counter == 0 {
t.Errorf("Expected worker1 to have processed tasks before removal")
}
if worker2.counter == 0 {
t.Errorf("Expected worker2 to process tasks after removal")
}
}
// TestTaskRetriesUpToMaxAttempts verifies that tasks retry up to the maximum number of attempts.
func TestTaskRetriesUpToMaxAttempts(t *testing.T) {
ctx := context.Background()
worker := &FailingWorker{}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](3),
WithRetryIf[int](func(err error) bool { return true }),
)
// Dispatch task
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
if worker.counter != 3 {
t.Errorf("Expected 3 attempts, got %d", worker.counter)
}
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
}
// TestCustomDelayTypeFunction tests that a custom delay type function is used
// to calculate delays between retries.
func TestCustomDelayTypeFunction(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{failuresLeft: 3}
var delays []time.Duration
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](4),
WithRetryIf[int](func(err error) bool { return true }),
WithDelayType[int](func(n int, err error, c *Config[int]) time.Duration {
delay := time.Duration(n) * 100 * time.Millisecond
delays = append(delays, delay)
return delay
}),
)
// Dispatch task
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 50*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
expectedDelays := []time.Duration{
100 * time.Millisecond,
200 * time.Millisecond,
300 * time.Millisecond,
}
if len(delays) != len(expectedDelays) {
t.Fatalf("Expected %d delays, got %d", len(expectedDelays), len(delays))
}
for i, expectedDelay := range expectedDelays {
if delays[i] != expectedDelay {
t.Errorf("Expected delay %v, got %v", expectedDelay, delays[i])
}
}
}
// TestImmediateRetryOption verifies that tasks with WithImmediateRetry are retried immediately.
func TestImmediateRetryOption(t *testing.T) {
ctx := context.Background()
// Worker that fails once, then succeeds
worker := &FlakyWorker{failuresLeft: 1}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithRetryIf[int](func(err error) bool { return true }),
)
// Dispatch task with immediate retry
err := pool.Submit(1, WithImmediateRetry[int]())
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
if worker.failuresLeft != 0 {
t.Errorf("Expected worker to have no failures left, got %d", worker.failuresLeft)
}
}
// TestTaskRespectsTimeLimit verifies that tasks respect their total time limit.
func TestTaskRespectsTimeLimit(t *testing.T) {
ctx := context.Background()
worker := &VerySlowWorker{}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](10),
WithRetryIf[int](func(err error) bool { return true }),
)
// Dispatch task with time limit and max duration per attempt
err := pool.Submit(1,
WithTimeLimit[int](500*time.Millisecond),
WithMaxContextDuration[int](200*time.Millisecond),
)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 50*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
if worker.counter == 0 {
t.Errorf("Expected worker to have attempted task")
}
}
// TestTaskCancellationOnContextCancel verifies that tasks are canceled when context is canceled.
func TestTaskCancellationOnContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
worker := &SlowWorker{}
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](UnlimitedAttempts),
WithRetryIf[int](func(err error) bool { return true }),
)
for i := 0; i < 10; i++ {
// Dispatch task
err := pool.Submit(i)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
}
// Cancel context after delay
time.AfterFunc(2*time.Second, cancel)
// Wait for pool to finish
err := pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != context.Canceled {
t.Errorf("Expected context.Canceled error, got %v", err)
}
pool.Shutdown()
// Check task is in dead tasks
deadTasks := pool.DeadTasks()
if len(deadTasks) == 0 {
t.Errorf("Expected many dead tasks, got %d", len(deadTasks))
}
}
// TestCallbacksAreInvoked verifies that OnTaskSuccess, OnTaskFailure, and OnNewDeadTask callbacks are invoked.
func TestCallbacksAreInvoked(t *testing.T) {
ctx := context.Background()
worker := &FlakyWorker{
failuresLeft: 1,
}
var successCalled bool
var failureCalled bool
var newDeadTaskCalled bool
var mu sync.Mutex
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](2),
WithRetryIf[int](func(err error) bool { return true }),
WithOnTaskSuccess[int](func(c WorkerController[int], id int, w Worker[int], t *TaskWrapper[int]) {
mu.Lock()
successCalled = true
mu.Unlock()
}),
WithOnTaskFailure[int](func(c WorkerController[int], id int, w Worker[int], t *TaskWrapper[int], e error) DeadTaskAction {
mu.Lock()
failureCalled = true
mu.Unlock()
return DeadTaskActionRetry
}),
WithOnNewDeadTask[int](func(t *DeadTask[int]) {
mu.Lock()
newDeadTaskCalled = true
mu.Unlock()
}),
)
// Dispatch task
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
mu.Lock()
defer mu.Unlock()
if !successCalled {
t.Errorf("Expected OnTaskSuccess to be called")
}
if !failureCalled {
t.Errorf("Expected OnTaskFailure to be called")
}
if newDeadTaskCalled {
t.Errorf("Did not expect OnNewDeadTask to be called")
}
}
// TestPanicRecoveryInWorker tests that a panic in the worker's Run method is recovered and handled.
func TestPanicRecoveryInWorker(t *testing.T) {
ctx := context.Background()
worker := &testPanicWorker{}
var panicHandled bool
pool := New(ctx, []Worker[int]{worker},
WithPanicHandler[int](func(task int, v interface{}, stackTrace string) {
panicHandled = true
}),
)
// Dispatch task
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
if !panicHandled {
t.Errorf("Expected panic handler to be called")
}
}
// TestPoolContinuesAfterPanic verifies that the pool continues processing after a panic in a worker.
func TestPoolContinuesAfterPanic(t *testing.T) {
ctx := context.Background()
worker := &PanicThenSuccessWorker{}
var panicHandled bool
pool := New(ctx, []Worker[int]{worker},
WithPanicHandler[int](func(task int, v interface{}, stackTrace string) {
panicHandled = true
}),
)
// Dispatch tasks
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task 1: %v", err)
}
// Wait for a moment
time.Sleep(100 * time.Millisecond)
err = pool.Submit(2)
if err != nil {
t.Fatalf("Failed to dispatch task 2: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 50*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
if !panicHandled {
t.Errorf("Expected panic handler to be called")
}
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead tasks, got %d", len(deadTasks))
}
}
// TestOnTaskFailureDeadTaskAction tests that the OnTaskFailure callback returns the correct DeadTaskAction.
func TestOnTaskFailureDeadTaskAction(t *testing.T) {
ctx := context.Background()
worker := &FailingWorker{}
actionSequence := []DeadTaskAction{
DeadTaskActionRetry,
DeadTaskActionForceRetry,
DeadTaskActionAddToDeadTasks,
}
actionIndex := 0
pool := New(ctx, []Worker[int]{worker},
WithAttempts[int](5),
WithRetryIf[int](func(err error) bool { return true }),
WithOnTaskFailure[int](func(c WorkerController[int], id int, w Worker[int], t *TaskWrapper[int], e error) DeadTaskAction {
action := actionSequence[actionIndex]
actionIndex++
return action
}),
)
// Dispatch task
err := pool.Submit(1)
if err != nil {
t.Fatalf("Failed to dispatch task: %v", err)
}
// Wait for pool to finish
err = pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 50*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
deadTasks := pool.DeadTasks()
if len(deadTasks) != 1 {
t.Errorf("Expected 1 dead task, got %d", len(deadTasks))
}
}
// TestRangeTasksIteratesAllTasks tests that RangeTasks correctly iterates over all tasks with accurate statuses.
func TestRangeTasksIteratesAllTasks(t *testing.T) {
ctx := context.Background()
worker := &CountingWorker{}
pool := New(ctx, []Worker[int]{worker})
// Dispatch multiple tasks
for i := 0; i < 5; i++ {
err := pool.Submit(i)
if err != nil {
t.Fatalf("Failed to dispatch task %d: %v", i, err)
}
}
// Allow some tasks to be processed
time.Sleep(100 * time.Millisecond)
var queuedTasks, processingTasks int
pool.RangeTasks(func(data *TaskWrapper[int], workerID int, status TaskStatus) bool {
if status == TaskStatusQueued {
queuedTasks++
} else if status == TaskStatusProcessing {
processingTasks++
}
return true
})
if queuedTasks == 0 {
t.Errorf("Expected some tasks to be queued")
}
if processingTasks == 0 {
t.Errorf("Expected some tasks to be processing")
}
pool.Shutdown()
}
// Define at package level
type TestSlowIncrementWorker struct {
*IncrementWorker
}
func NewTestSlowIncrementWorker() *TestSlowIncrementWorker {
return &TestSlowIncrementWorker{
IncrementWorker: &IncrementWorker{},
}
}
func (w *TestSlowIncrementWorker) Run(ctx context.Context, data int) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(50 * time.Millisecond):
}
return w.IncrementWorker.Run(ctx, data)
}
// TestCombinedFeaturesWithDynamicWorkers tests a complex scenario involving dynamic workers and task retries.
func TestCombinedFeaturesWithDynamicWorkers(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
worker1 := NewTestSlowIncrementWorker()
worker2 := NewTestSlowIncrementWorker()
// Track task completion order and worker assignment
type taskResult struct {
workerID int
timestamp time.Time
}
var completedTasks sync.Map
var taskCount int32
pool := New(ctx, []Worker[int]{worker1},
WithLogLevel[int](logs.LevelDebug),
WithAttempts[int](1), // No retries to keep things simple
WithOnTaskSuccess[int](func(_ WorkerController[int], workerID int, _ Worker[int], task *TaskWrapper[int]) {
completedTasks.Store(task.Data(), taskResult{
workerID: workerID,
timestamp: time.Now(),
})
atomic.AddInt32(&taskCount, 1)
}),
)
// Submit first batch
for i := 0; i < 5; i++ {
if err := pool.Submit(i); err != nil {
t.Fatalf("Failed to dispatch task %d: %v", i, err)
}
}
// Let some first batch tasks complete
time.Sleep(150 * time.Millisecond)
// Add second worker
worker2ID := pool.AddWorker(worker2)
if worker2ID != 1 {
t.Errorf("Expected worker2 ID to be 1, got %d", worker2ID)
}
// Submit second batch
for i := 5; i < 10; i++ {
if err := pool.Submit(i); err != nil {
t.Fatalf("Failed to dispatch task %d: %v", i, err)
}
}
// Wait for at least one second batch task to start
time.Sleep(100 * time.Millisecond)
// Interrupt first worker
err := pool.InterruptWorker(0, WithReassignTask())
if err != nil {
t.Fatalf("Failed to interrupt worker: %v", err)
}
// Wait for completion with timeout
timeout := time.NewTimer(3 * time.Second)
defer timeout.Stop()
completed := make(map[int]taskResult)
for len(completed) < 10 {
select {
case <-timeout.C:
t.Fatalf("Timeout waiting for tasks. Completed %d/10: %v", len(completed), completed)
case <-time.After(50 * time.Millisecond):
completedTasks.Range(func(k, v interface{}) bool {
completed[k.(int)] = v.(taskResult)
return true
})
}
}
// Let any final operations complete
time.Sleep(100 * time.Millisecond)
pool.Shutdown()
// Analyze results
byWorker := make(map[int][]int)
for taskID, result := range completed {
byWorker[result.workerID] = append(byWorker[result.workerID], taskID)
}
// Sort tasks for consistent output
for _, tasks := range byWorker {
sort.Ints(tasks)
}
t.Logf("Tasks by worker0: %v", byWorker[0])
t.Logf("Tasks by worker1: %v", byWorker[1])
// Verify distribution
if len(byWorker[0]) == 0 || len(byWorker[1]) == 0 {
t.Error("Expected both workers to process tasks")
}
if len(byWorker[1]) < 3 {
t.Errorf("Expected worker1 to process at least 3 tasks, got %d", len(byWorker[1]))
}
// Check for dead tasks
deadTasks := pool.DeadTasks()
if len(deadTasks) > 0 {
t.Errorf("Got unexpected dead tasks: %+v", deadTasks)
}
}
// TestTaskQueueDistribution verifies that tasks are distributed evenly across workers
func TestTaskQueueDistribution(t *testing.T) {
ctx := context.Background()
numWorkers := 3
numTasks := 30
// Create workers that track how many tasks they process
workers := make([]Worker[int], numWorkers)
counters := make([]*CountingWorker, numWorkers)
for i := 0; i < numWorkers; i++ {
worker := &CountingWorker{}
workers[i] = worker
counters[i] = worker
}
pool := New(ctx, workers)
// Submit tasks
for i := 0; i < numTasks; i++ {
err := pool.Submit(i)
if err != nil {
t.Fatalf("Failed to submit task %d: %v", i, err)
}
}
// Wait for tasks to complete
err := pool.WaitWithCallback(ctx, func(q, p, d int) bool {
return q > 0 || p > 0
}, 10*time.Millisecond)
if err != nil && err != context.DeadlineExceeded {
t.Fatalf("WaitWithCallback failed: %v", err)
}
pool.Shutdown()
// Calculate distribution metrics
total := 0
minCount := numTasks
maxCount := 0
for _, counter := range counters {
count := counter.GetCount()
total += count
if count < minCount {
minCount = count
}
if count > maxCount {
maxCount = count
}
}
// Check that all tasks were processed
if total != numTasks {
t.Errorf("Expected %d total tasks processed, got %d", numTasks, total)
}
// Check distribution (allow for some variance)
expectedPerWorker := numTasks / numWorkers
maxVariance := expectedPerWorker / 2