-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool_test.go
1550 lines (1284 loc) · 42 KB
/
pool_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 pool
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/go-pkgz/pool/metrics"
)
func TestPool_Basic(t *testing.T) {
var processed []string
var mu sync.Mutex
worker := WorkerFunc[string](func(_ context.Context, v string) error {
mu.Lock()
processed = append(processed, v)
mu.Unlock()
return nil
})
p := New[string](2, worker)
require.NoError(t, p.Go(context.Background()))
inputs := []string{"1", "2", "3", "4", "5"}
for _, v := range inputs {
p.Submit(v)
}
require.NoError(t, p.Close(context.Background()))
sort.Strings(processed)
assert.Equal(t, inputs, processed)
}
func TestPool_ChunkDistribution(t *testing.T) {
var workerCounts [2]int32
worker := WorkerFunc[string](func(ctx context.Context, _ string) error {
id := metrics.WorkerID(ctx)
atomic.AddInt32(&workerCounts[id], 1)
return nil
})
p := New[string](2, worker).WithChunkFn(func(v string) string { return v })
require.NoError(t, p.Go(context.Background()))
// submit same value multiple times, should always go to same worker
for i := 0; i < 10; i++ {
p.Submit("test1")
}
require.NoError(t, p.Close(context.Background()))
// verify all items went to the same worker
assert.True(t, workerCounts[0] == 0 || workerCounts[1] == 0)
assert.Equal(t, int32(10), workerCounts[0]+workerCounts[1])
}
func TestPool_ErrorHandling_StopOnError(t *testing.T) {
errTest := errors.New("test error")
var processedCount atomic.Int32
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if v == "error" {
return errTest
}
processedCount.Add(1)
return nil
})
p := New[string](1, worker)
require.NoError(t, p.Go(context.Background()))
p.Submit("ok1")
p.Submit("error")
p.Submit("ok2") // should not be processed
err := p.Close(context.Background())
require.ErrorIs(t, err, errTest)
assert.Equal(t, int32(1), processedCount.Load())
}
func TestPool_ErrorHandling_ContinueOnError(t *testing.T) {
errTest := errors.New("test error")
var processedCount atomic.Int32
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if v == "error" {
return errTest
}
processedCount.Add(1)
return nil
})
p := New[string](1, worker).WithContinueOnError()
require.NoError(t, p.Go(context.Background()))
p.Submit("ok1")
p.Submit("error")
p.Submit("ok2")
err := p.Close(context.Background())
require.ErrorIs(t, err, errTest)
assert.Equal(t, int32(2), processedCount.Load())
}
func TestPool_ContextCancellation(t *testing.T) {
worker := WorkerFunc[string](func(ctx context.Context, _ string) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
return nil
}
})
p := New[string](1, worker)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
require.NoError(t, p.Go(ctx))
p.Submit("test")
err := p.Close(context.Background())
assert.ErrorIs(t, err, context.DeadlineExceeded)
}
func TestPool_StatefulWorker(t *testing.T) {
type statefulWorker struct {
count int
}
workerMaker := func() Worker[string] {
w := &statefulWorker{}
return WorkerFunc[string](func(_ context.Context, _ string) error {
w.count++
time.Sleep(time.Millisecond) // even with sleep it's safe
return nil
})
}
p := NewStateful[string](2, workerMaker).WithWorkerChanSize(5)
require.NoError(t, p.Go(context.Background()))
// submit more items to increase chance of concurrent processing
for i := 0; i < 100; i++ {
p.Submit("test")
}
assert.NoError(t, p.Close(context.Background()))
}
func TestPool_Wait(t *testing.T) {
processed := make(map[string]bool)
var mu sync.Mutex
worker := WorkerFunc[string](func(_ context.Context, v string) error {
time.Sleep(10 * time.Millisecond) // simulate work
mu.Lock()
processed[v] = true
mu.Unlock()
return nil
})
p := New[string](2, worker)
require.NoError(t, p.Go(context.Background()))
// submit in a separate goroutine since we'll use Wait
go func() {
inputs := []string{"1", "2", "3"}
for _, v := range inputs {
p.Submit(v)
}
err := p.Close(context.Background())
assert.NoError(t, err)
}()
// wait for completion
require.NoError(t, p.Wait(context.Background()))
// verify all items were processed
mu.Lock()
require.Len(t, processed, 3)
for _, v := range []string{"1", "2", "3"} {
require.True(t, processed[v], "item %s was not processed", v)
}
mu.Unlock()
}
func TestPool_Wait_WithError(t *testing.T) {
errTest := errors.New("test error")
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if v == "error" {
return errTest
}
return nil
})
p := New[string](1, worker)
require.NoError(t, p.Go(context.Background()))
go func() {
p.Submit("ok")
p.Submit("error")
err := p.Close(context.Background())
assert.Error(t, err)
}()
err := p.Wait(context.Background())
require.Error(t, err)
require.ErrorIs(t, err, errTest)
}
func TestPool_Distribution(t *testing.T) {
t.Run("shared channel distribution", func(t *testing.T) {
var counts [2]int32
worker := WorkerFunc[int](func(ctx context.Context, _ int) error {
atomic.AddInt32(&counts[metrics.WorkerID(ctx)], 1)
return nil
})
p := New[int](2, worker)
require.NoError(t, p.Go(context.Background()))
const n = 10000
for i := 0; i < n; i++ {
p.Submit(i)
}
require.NoError(t, p.Close(context.Background()))
// check both workers got some work
assert.Positive(t, counts[0], "worker 0 should process some items")
assert.Positive(t, counts[1], "worker 1 should process some items")
// check rough distribution, allow more variance as it's scheduler-dependent
diff := math.Abs(float64(counts[0]-counts[1])) / float64(n)
require.Less(t, diff, 0.3, "distribution difference %v should be less than 30%%", diff)
t.Logf("workers distribution: %v, difference: %.2f%%", counts, diff*100)
})
t.Run("chunked distribution", func(t *testing.T) {
var counts [2]int32
worker := WorkerFunc[int](func(ctx context.Context, _ int) error {
atomic.AddInt32(&counts[metrics.WorkerID(ctx)], 1)
return nil
})
p := New[int](2, worker).WithChunkFn(func(v int) string {
return fmt.Sprintf("key-%d", v%10) // 10 different keys
})
require.NoError(t, p.Go(context.Background()))
const n = 10000
for i := 0; i < n; i++ {
p.Submit(i)
}
require.NoError(t, p.Close(context.Background()))
// chunked distribution should still be roughly equal
diff := math.Abs(float64(counts[0]-counts[1])) / float64(n)
require.Less(t, diff, 0.1, "chunked distribution difference %v should be less than 10%%", diff)
t.Logf("workers distribution: %v, difference: %.2f%%", counts, diff*100)
})
}
func TestPool_Metrics(t *testing.T) {
t.Run("basic metrics", func(t *testing.T) {
var processed int32
worker := WorkerFunc[int](func(ctx context.Context, _ int) error {
time.Sleep(time.Millisecond) // simulate work
atomic.AddInt32(&processed, 1)
return nil
})
p := New[int](2, worker)
require.NoError(t, p.Go(context.Background()))
for i := 0; i < 10; i++ {
p.Submit(i)
}
require.NoError(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
assert.Equal(t, int(atomic.LoadInt32(&processed)), stats.Processed)
assert.Equal(t, 0, stats.Errors)
assert.Equal(t, 0, stats.Dropped)
assert.Greater(t, stats.ProcessingTime, time.Duration(0))
})
t.Run("metrics with errors", func(t *testing.T) {
var errs, processed int32
worker := WorkerFunc[int](func(ctx context.Context, v int) error {
if v%2 == 0 {
atomic.AddInt32(&errs, 1)
return errors.New("even number")
}
atomic.AddInt32(&processed, 1)
return nil
})
p := New[int](2, worker).WithContinueOnError()
require.NoError(t, p.Go(context.Background()))
for i := 0; i < 10; i++ {
p.Submit(i)
}
require.Error(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
assert.Equal(t, int(atomic.LoadInt32(&processed)), stats.Processed)
assert.Equal(t, int(atomic.LoadInt32(&errs)), stats.Errors)
assert.Equal(t, 0, stats.Dropped)
})
t.Run("metrics timing", func(t *testing.T) {
processed := make(chan struct{}, 2)
worker := WorkerFunc[int](func(_ context.Context, _ int) error {
// signal when processing starts
start := time.Now()
time.Sleep(10 * time.Millisecond)
processed <- struct{}{}
t.Logf("processed item in %v", time.Since(start))
return nil
})
p := New[int](2, worker).WithBatchSize(0) // disable batching
require.NoError(t, p.Go(context.Background()))
p.Submit(1)
p.Submit(2)
// wait for both items to be processed
for i := 0; i < 2; i++ {
select {
case <-processed:
case <-time.After(time.Second):
t.Fatal("timeout waiting for processing")
}
}
require.NoError(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
assert.Equal(t, 2, stats.Processed)
// verify timing is reasonable but don't be too strict
assert.Greater(t, stats.ProcessingTime, time.Millisecond,
"processing time should be measurable")
assert.Greater(t, stats.TotalTime, time.Millisecond,
"total time should be measurable")
assert.Less(t, stats.ProcessingTime, time.Second,
"processing time should be reasonable")
})
t.Run("per worker stats", func(t *testing.T) {
var processed, errs int32
worker := WorkerFunc[int](func(ctx context.Context, v int) error {
time.Sleep(time.Millisecond)
if v%2 == 0 {
atomic.AddInt32(&errs, 1)
return errors.New("even error")
}
atomic.AddInt32(&processed, 1)
return nil
})
p := New[int](2, worker).WithContinueOnError()
require.NoError(t, p.Go(context.Background()))
// submit enough items to ensure both workers get some
n := 100
for i := 0; i < n; i++ {
p.Submit(i)
}
require.Error(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
assert.Equal(t, int(atomic.LoadInt32(&processed)), stats.Processed)
assert.Equal(t, int(atomic.LoadInt32(&errs)), stats.Errors)
assert.Greater(t, stats.ProcessingTime, 40*time.Millisecond,
"processing time should be significant with 100 tasks")
assert.Less(t, stats.ProcessingTime, time.Second,
"processing time should be reasonable")
})
}
func TestPool_MetricsString(t *testing.T) {
worker := WorkerFunc[int](func(_ context.Context, _ int) error {
time.Sleep(time.Millisecond)
return nil
})
p := New[int](2, worker)
require.NoError(t, p.Go(context.Background()))
p.Submit(1)
p.Submit(2)
require.NoError(t, p.Close(context.Background()))
// check stats string format
stats := p.Metrics().GetStats()
str := stats.String()
assert.Contains(t, str, "processed:2")
assert.Contains(t, str, "proc:")
assert.Contains(t, str, "total:")
// check user metrics string format
p.Metrics().Add("custom", 5)
str = p.Metrics().String()
assert.Contains(t, str, "custom:5")
}
func TestPool_WorkerCompletion(t *testing.T) {
t.Run("batch processing with errors", func(t *testing.T) {
var processed []string
var mu sync.Mutex
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if v == "error" {
return fmt.Errorf("test error")
}
mu.Lock()
processed = append(processed, v)
mu.Unlock()
return nil
})
p := New[string](1, worker)
require.NoError(t, p.Go(context.Background()))
// submit items including error
p.Submit("ok1")
p.Submit("error")
p.Submit("ok2")
// should process until error
err := p.Close(context.Background())
require.Error(t, err)
require.Contains(t, err.Error(), "test error")
assert.Equal(t, []string{"ok1"}, processed)
})
t.Run("batch processing continues on error", func(t *testing.T) {
var processed []string
var mu sync.Mutex
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if v == "error" {
return fmt.Errorf("test error")
}
mu.Lock()
processed = append(processed, v)
mu.Unlock()
return nil
})
p := New[string](1, worker).WithContinueOnError()
require.NoError(t, p.Go(context.Background()))
// submit items including error
p.Submit("ok1")
p.Submit("error")
p.Submit("ok2")
// should process all items despite error
err := p.Close(context.Background())
require.Error(t, err)
assert.Equal(t, []string{"ok1", "ok2"}, processed)
})
t.Run("workerCompleteFn error", func(t *testing.T) {
worker := WorkerFunc[string](func(_ context.Context, v string) error {
return nil
})
completeFnError := fmt.Errorf("complete error")
p := New[string](1, worker).WithWorkerCompleteFn(func(context.Context, int, Worker[string]) error {
return completeFnError
})
require.NoError(t, p.Go(context.Background()))
p.Submit("task")
err := p.Close(context.Background())
require.Error(t, err)
require.ErrorIs(t, err, completeFnError)
})
t.Run("batch error prevents workerCompleteFn", func(t *testing.T) {
var completeFnCalled bool
worker := WorkerFunc[string](func(_ context.Context, v string) error {
return fmt.Errorf("batch error")
})
p := New[string](1, worker).WithWorkerCompleteFn(func(context.Context, int, Worker[string]) error {
completeFnCalled = true
return nil
})
require.NoError(t, p.Go(context.Background()))
p.Submit("task")
err := p.Close(context.Background())
require.Error(t, err)
require.Contains(t, err.Error(), "batch error")
assert.False(t, completeFnCalled, "workerCompleteFn should not be called after batch error")
})
t.Run("context cancellation", func(t *testing.T) {
processed := make(chan string, 1)
worker := WorkerFunc[string](func(ctx context.Context, v string) error {
// make sure we wait for context cancellation
select {
case <-ctx.Done():
return ctx.Err()
case processed <- v:
time.Sleep(50 * time.Millisecond) // ensure we're still processing when cancelled
return ctx.Err()
}
})
ctx, cancel := context.WithCancel(context.Background())
p := New[string](1, worker).WithBatchSize(0) // disable batching for this test
require.NoError(t, p.Go(ctx))
p.Submit("task")
// wait for task to start processing
select {
case <-processed:
case <-time.After(time.Second):
t.Fatal("timeout waiting for processing to start")
}
// ensure the task is being processed
time.Sleep(10 * time.Millisecond)
cancel()
err := p.Close(context.Background())
require.Error(t, err)
require.ErrorIs(t, err, context.Canceled)
})
}
func TestPool_WaitTimeAccuracy(t *testing.T) {
t.Run("measures idle time between tasks", func(t *testing.T) {
worker := WorkerFunc[int](func(ctx context.Context, v int) error {
time.Sleep(10 * time.Millisecond) // fixed processing time
return nil
})
p := New[int](1, worker)
require.NoError(t, p.Go(context.Background()))
// submit first task
p.Submit(1)
waitPeriod := 50 * time.Millisecond
time.Sleep(waitPeriod) // deliberate wait
p.Submit(2)
require.NoError(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
// allow for some variance in timing
minExpectedWait := 35 * time.Millisecond // 70% of wait period
assert.Greater(t, stats.WaitTime, minExpectedWait,
"wait time (%v) should be greater than %v", stats.WaitTime, minExpectedWait)
})
}
func TestPool_InitializationTime(t *testing.T) {
t.Run("captures initialization in maker function", func(t *testing.T) {
initDuration := 25 * time.Millisecond
p := NewStateful[int](1, func() Worker[int] {
time.Sleep(initDuration) // simulate expensive initialization
return WorkerFunc[int](func(ctx context.Context, v int) error {
return nil
})
})
require.NoError(t, p.Go(context.Background()))
p.Submit(1)
require.NoError(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
minExpectedInit := 20 * time.Millisecond // 80% of init duration
assert.Greater(t, stats.InitTime, minExpectedInit,
"init time (%v) should capture worker maker execution time (expected > %v)",
stats.InitTime, minExpectedInit)
})
t.Run("minimal init time for stateless worker", func(t *testing.T) {
worker := WorkerFunc[int](func(ctx context.Context, v int) error {
return nil
})
p := New[int](1, worker)
require.NoError(t, p.Go(context.Background()))
p.Submit(1)
require.NoError(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
assert.Less(t, stats.InitTime, 5*time.Millisecond,
"stateless worker should have minimal init time")
})
}
func TestPool_TimingUnderLoad(t *testing.T) {
const (
workers = 3
tasks = 9
processingTime = 10 * time.Millisecond
)
// create channel to track completion
done := make(chan struct{}, tasks)
worker := WorkerFunc[int](func(ctx context.Context, v int) error {
start := time.Now()
time.Sleep(processingTime)
t.Logf("task %d processed in %v", v, time.Since(start))
done <- struct{}{}
return nil
})
p := New[int](workers, worker).WithBatchSize(0)
require.NoError(t, p.Go(context.Background()))
// submit all tasks
for i := 0; i < tasks; i++ {
p.Submit(i)
}
// wait for all tasks to complete
for i := 0; i < tasks; i++ {
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("timeout waiting for tasks to complete")
}
}
require.NoError(t, p.Close(context.Background()))
stats := p.Metrics().GetStats()
// verify the basic metrics are reasonable
assert.Equal(t, tasks, stats.Processed, "all tasks should be processed")
assert.Greater(t, stats.ProcessingTime, processingTime/2,
"processing time should be measurable")
assert.Less(t, stats.ProcessingTime, 5*time.Second,
"processing time should be reasonable")
t.Logf("Processed %d tasks with %d workers in %v (processing time %v)",
stats.Processed, workers, stats.TotalTime, stats.ProcessingTime)
}
func TestMiddleware_Basic(t *testing.T) {
t.Run("stateless worker middleware", func(t *testing.T) {
var processed atomic.Int32
// create base worker
worker := WorkerFunc[string](func(_ context.Context, v string) error {
processed.Add(1)
return nil
})
// middleware to count calls
var middlewareCalls atomic.Int32
countMiddleware := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
middlewareCalls.Add(1)
return next.Do(ctx, v)
})
}
p := New[string](1, worker).Use(countMiddleware)
require.NoError(t, p.Go(context.Background()))
p.Submit("test1")
p.Submit("test2")
require.NoError(t, p.Close(context.Background()))
assert.Equal(t, int32(2), processed.Load(), "base worker should process all items")
assert.Equal(t, int32(2), middlewareCalls.Load(), "middleware should be called for all items")
})
t.Run("stateful worker middleware", func(t *testing.T) {
type statefulWorker struct {
count int
}
var order []string
var mu sync.Mutex
// create stateful worker
maker := func() Worker[string] {
w := &statefulWorker{}
return WorkerFunc[string](func(_ context.Context, v string) error {
w.count++
mu.Lock()
order = append(order, fmt.Sprintf("worker_%d", w.count))
mu.Unlock()
return nil
})
}
// create simple logging middleware
logMiddleware := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
mu.Lock()
order = append(order, "middleware_before")
mu.Unlock()
err := next.Do(ctx, v)
mu.Lock()
order = append(order, "middleware_after")
mu.Unlock()
return err
})
}
p := NewStateful[string](1, maker).Use(logMiddleware)
require.NoError(t, p.Go(context.Background()))
p.Submit("test1")
p.Submit("test2")
require.NoError(t, p.Close(context.Background()))
assert.Equal(t, []string{
"middleware_before",
"worker_1",
"middleware_after",
"middleware_before",
"worker_2",
"middleware_after",
}, order, "middleware should wrap each worker call")
})
}
func TestMiddleware_ExecutionOrder(t *testing.T) {
var order strings.Builder
var mu sync.Mutex
addToOrder := func(s string) {
mu.Lock()
order.WriteString(s)
mu.Unlock()
}
// base worker
worker := WorkerFunc[string](func(_ context.Context, v string) error {
addToOrder("worker->")
return nil
})
// create middlewares that log their execution order
middleware1 := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
addToOrder("m1_before->")
err := next.Do(ctx, v)
addToOrder("m1_after->")
return err
})
}
middleware2 := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
addToOrder("m2_before->")
err := next.Do(ctx, v)
addToOrder("m2_after->")
return err
})
}
middleware3 := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
addToOrder("m3_before->")
err := next.Do(ctx, v)
addToOrder("m3_after->")
return err
})
}
// apply middlewares: middleware1, middleware2, middleware3
p := New[string](1, worker).Use(middleware1, middleware2, middleware3)
require.NoError(t, p.Go(context.Background()))
p.Submit("test")
require.NoError(t, p.Close(context.Background()))
// expect order similar to http middleware: last added = outermost wrapper
// first added (m1) is closest to worker, last added (m3) is outermost
expected := "m1_before->m2_before->m3_before->worker->m3_after->m2_after->m1_after->"
assert.Equal(t, expected, order.String(), "middleware execution order should match HTTP middleware pattern")
}
func TestMiddleware_ErrorHandling(t *testing.T) {
errTest := errors.New("test error")
var processed atomic.Int32
// worker that fails
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if v == "error" {
return errTest
}
processed.Add(1)
return nil
})
// middleware that logs errors
var errCount atomic.Int32
errorMiddleware := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
err := next.Do(ctx, v)
if err != nil {
errCount.Add(1)
}
return err
})
}
p := New[string](1, worker).Use(errorMiddleware)
require.NoError(t, p.Go(context.Background()))
p.Submit("ok")
p.Submit("error")
err := p.Close(context.Background())
require.Error(t, err)
require.ErrorIs(t, err, errTest)
assert.Equal(t, int32(1), processed.Load(), "should process non-error item")
assert.Equal(t, int32(1), errCount.Load(), "should count one error")
}
func TestMiddleware_Practical(t *testing.T) {
t.Run("retry middleware", func(t *testing.T) {
var attempts atomic.Int32
// worker that fails first time
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if attempts.Add(1) == 1 {
return errors.New("temporary error")
}
return nil
})
// retry middleware
retryMiddleware := func(maxAttempts int) Middleware[string] {
return func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
var lastErr error
for i := 0; i < maxAttempts; i++ {
var err error
if err = next.Do(ctx, v); err == nil {
return nil
}
lastErr = err
// wait before retry
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Millisecond):
}
}
return lastErr
})
}
}
p := New[string](1, worker).Use(retryMiddleware(3))
require.NoError(t, p.Go(context.Background()))
p.Submit("test")
require.NoError(t, p.Close(context.Background()))
assert.Equal(t, int32(2), attempts.Load(), "should succeed on second attempt")
})
t.Run("timing middleware", func(t *testing.T) {
worker := WorkerFunc[string](func(_ context.Context, v string) error {
time.Sleep(time.Millisecond)
return nil
})
var totalTime int64
timingMiddleware := func(next Worker[string]) Worker[string] {
return WorkerFunc[string](func(ctx context.Context, v string) error {
start := time.Now()
err := next.Do(ctx, v)
atomic.AddInt64(&totalTime, time.Since(start).Microseconds())
return err
})
}
p := New[string](1, worker).Use(timingMiddleware)
require.NoError(t, p.Go(context.Background()))
p.Submit("test")
require.NoError(t, p.Close(context.Background()))
assert.Greater(t, atomic.LoadInt64(&totalTime), int64(1000),
"should measure time greater than 1ms")
})
}
func TestPool_Batch(t *testing.T) {
t.Run("basic batching", func(t *testing.T) {
var batches [][]string
var mu sync.Mutex
worker := WorkerFunc[string](func(_ context.Context, v string) error {
mu.Lock()
defer mu.Unlock()
// start new batch if no batches or current batch is full
if len(batches) == 0 || len(batches[len(batches)-1]) >= 3 {
batches = append(batches, []string{v})
return nil
}
// add to current batch
batches[len(batches)-1] = append(batches[len(batches)-1], v)
return nil
})
p := New[string](2, worker).WithBatchSize(3)
require.NoError(t, p.Go(context.Background()))
// submit 8 items - should make 2 full batches and 1 partial
for i := 0; i < 8; i++ {
p.Submit(fmt.Sprintf("v%d", i))
}
require.NoError(t, p.Close(context.Background()))
mu.Lock()
defer mu.Unlock()
require.Len(t, batches, 3, "should have 3 batches")
assert.Len(t, batches[0], 3, "first batch should be full")
assert.Len(t, batches[1], 3, "second batch should be full")
assert.Len(t, batches[2], 2, "last batch should have remaining items")
})
t.Run("batching with chunk function", func(t *testing.T) {
var processed sync.Map
worker := WorkerFunc[string](func(_ context.Context, v string) error {
key := v[:1] // first letter is the chunk key
val, _ := processed.LoadOrStore(key, []string{})
items := val.([]string)
items = append(items, v)
processed.Store(key, items)
return nil
})
p := New[string](2, worker).
WithBatchSize(2).
WithChunkFn(func(v string) string { return v[:1] }) // chunk by first letter
require.NoError(t, p.Go(context.Background()))
// submit items that should go to different workers
items := []string{"a1", "a2", "a3", "b1", "b2", "b3"}
for _, item := range items {
p.Submit(item)
}
require.NoError(t, p.Close(context.Background()))
// verify items are grouped by first letter
aItems, _ := processed.Load("a")
bItems, _ := processed.Load("b")
assert.Len(t, aItems.([]string), 3, "should have 3 'a' items")
assert.Len(t, bItems.([]string), 3, "should have 3 'b' items")
})
t.Run("error handling in batch", func(t *testing.T) {
var processed []string
var mu sync.Mutex
worker := WorkerFunc[string](func(_ context.Context, v string) error {
if strings.HasPrefix(v, "err") {
return fmt.Errorf("error processing %s", v)
}
mu.Lock()
processed = append(processed, v)
mu.Unlock()
return nil
})
// test without continue on error
p1 := New[string](1, worker).WithBatchSize(2)
require.NoError(t, p1.Go(context.Background()))