-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworkerpoolxt_test.go
747 lines (663 loc) · 17.9 KB
/
workerpoolxt_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
package workerpoolxt
import (
"context"
"errors"
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
)
/**
*
* Any test ending in `_Special` will have the following command ran against it:
*
* > go test -race -run ^Test.*Special$ -count=2000
*
*/
var (
defaultTimeout = time.Duration(time.Second * 10)
freshCtx = func() context.Context { return context.Background() }
defaultWorkers = 10
)
func randNum(min, max int) int {
rand.Seed(time.Now().UnixNano())
return (rand.Intn(max-min+1) + min)
}
func makeDefaultWp() *WorkerPoolXT {
return New(freshCtx(), defaultWorkers)
}
func newWithNJobs(nJobs, numWorkers int) *WorkerPoolXT {
w := New(freshCtx(), numWorkers)
for i := 0; i < nJobs; i++ {
name := fmt.Sprintf("%d", i)
sleepfor := time.Millisecond * time.Duration(time.Duration(randNum(5, 10)))
w.SubmitXT(Job{
Name: name,
Task: func(o Options) Result {
time.Sleep(sleepfor)
return Result{Data: "from " + name}
},
})
}
return w
}
func TestBasics(t *testing.T) {
wp := New(freshCtx(), defaultWorkers)
wp.SubmitXT(Job{
Name: "a",
Task: func(o Options) Result {
return Result{Data: true}
},
})
wp.SubmitXT(Job{
Name: "b",
Task: func(o Options) Result {
return Result{Data: true}
},
})
wp.SubmitXT(Job{
Name: "c",
Task: func(o Options) Result {
return Result{Error: errors.New("err")}
},
})
results := wp.StopWaitXT()
if len(results) != 3 {
t.Fatalf("Expected 3 results got : %d", len(results))
}
}
func TestJobIsCancelledImmediately(t *testing.T) {
expectedResultsCount := 1
expectedError := context.Canceled
expectedDurationLessThan := time.Millisecond * 5
errorAfterDuration := time.Millisecond * 100
start := time.Now()
wp := New(freshCtx(), defaultWorkers)
ctx, done := context.WithCancel(context.Background())
wp.SubmitXT(Job{
Name: "a",
Context: ctx,
Task: func(o Options) Result {
time.Sleep(errorAfterDuration)
return Result{Data: "from a"}
},
})
time.Sleep(time.Millisecond * 2)
done()
results := wp.StopWaitXT()
took := time.Since(start)
resultsLen := len(results)
if took > expectedDurationLessThan {
t.Fatalf("Expected runtime of %s : got %s", expectedDurationLessThan, took)
}
if expectedResultsCount != resultsLen {
t.Fatalf("Expected %d results : got %d", expectedResultsCount, resultsLen)
}
if results[0].Error != expectedError {
t.Fatalf("Expected error %s : got %s", expectedError, results[0].Error)
}
}
func TestJobContextOverridesDefaultContext(t *testing.T) {
defaultContext := freshCtx()
jobContextWeWantToOverrideWith, done := context.WithTimeout(freshCtx(), time.Duration(time.Millisecond))
defer done()
wp := New(defaultContext, 10)
wp.SubmitXT(Job{
Name: "Using default ctx",
Task: func(o Options) Result {
time.Sleep(time.Second)
return Result{Data: "OK"}
},
})
wp.SubmitXT(Job{
Name: "Using custom per job ctx",
Context: jobContextWeWantToOverrideWith,
Task: func(o Options) Result {
time.Sleep(time.Second)
return Result{Data: "OK"}
},
})
results := wp.StopWaitXT()
errs, succs, expectedSuccs, expectedErrs := 0, 0, 1, 1
for _, r := range results {
if r.Error != nil {
errs++
} else {
succs++
}
}
if errs != expectedErrs || succs != expectedSuccs {
t.Fatalf("Expected errors=%d:success=%d : got errors=%d:success=%d", expectedErrs, expectedSuccs, errs, succs)
}
}
func TestTimeouts(t *testing.T) {
defaultCtx := context.Background()
numWorkers := 10
wp := New(defaultCtx, numWorkers)
timeout := time.Duration(time.Millisecond)
// don't have to use cancelFunc if you dont want, we call it for you on success
oneMsTimeoutContext, myCncl := context.WithTimeout(context.Background(), timeout)
defer myCncl()
wp.SubmitXT(Job{
Name: "my ctx job",
Context: oneMsTimeoutContext,
Task: func(o Options) Result {
// Simulate long running task
time.Sleep(time.Second * 10)
return Result{Data: "I could be anything"}
},
})
results := wp.StopWaitXT()
if len(results) != 1 {
t.Fatalf("Expected 1 result : got %d", len(results))
}
first := results[0]
if first.Error != context.DeadlineExceeded {
t.Fatalf("Expected err %s : got err %s", context.DeadlineExceeded, first.Error)
}
}
func TestCancellingContext(t *testing.T) {
defaultContext := freshCtx()
wp := New(defaultContext, 10)
ctx, cncl := context.WithCancel(freshCtx())
wp.SubmitXT(Job{
Name: "j1",
Context: ctx,
Task: func(o Options) Result {
time.Sleep(time.Millisecond * 10) // Sleep 10 sec
return Result{Data: "I will fail with context.Canceled"}
},
})
wp.SubmitXT(Job{
Name: "j2",
Task: func(o Options) Result {
return Result{Data: "I will not fail"}
},
})
// need to cancel ctx for some reason after doing "something"
time.Sleep(time.Millisecond * 2)
cncl()
results := wp.StopWaitXT()
errs, succs, expectedSuccs, expectedErrs := []Result{}, []Result{}, 1, 1
for _, r := range results {
if r.Error != nil {
errs = append(errs, r)
} else {
succs = append(succs, r)
}
}
if len(errs) != expectedErrs || len(succs) != expectedSuccs {
t.Fatalf("Expected errors=%d:success=%d : got errors=%d:success=%d", expectedErrs, expectedSuccs, len(errs), len(succs))
}
if errs[0].Error != context.Canceled {
t.Fatalf("Expected error '%s' : got '%s'", context.Canceled, errs[0].Error)
}
}
func TestSubmitWithSubmitXT_UsingStopWaitXT_Special(t *testing.T) {
var totalResults uint64
wp := New(freshCtx(), defaultWorkers)
expectedTotalResults := 2
wp.Submit(func() {
time.Sleep(time.Millisecond * 2)
atomic.AddUint64(&totalResults, 1)
})
wp.SubmitXT(Job{
Name: "From SubmitXT()",
Task: func(o Options) Result {
time.Sleep(time.Millisecond * 1)
atomic.AddUint64(&totalResults, 1)
return Result{Data: "SubmitXT() after sleep"}
},
})
_ = wp.StopWaitXT()
if int(atomic.LoadUint64(&totalResults)) != expectedTotalResults {
t.Fatalf("expect %d results : got %d results", expectedTotalResults, totalResults)
}
}
func TestSubmitWithSubmitXT_UsingStopWait_Special(t *testing.T) {
var totalResults uint64
wp := New(freshCtx(), defaultWorkers)
expectedTotalResults := 2
wp.Submit(func() {
time.Sleep(time.Millisecond * 2)
atomic.AddUint64(&totalResults, 1)
})
wp.SubmitXT(Job{
Name: "From SubmitXT()",
Task: func(o Options) Result {
time.Sleep(time.Millisecond * 1)
atomic.AddUint64(&totalResults, 1)
return Result{Data: "SubmitXT() after sleep"}
},
})
wp.StopWait()
if int(atomic.LoadUint64(&totalResults)) != expectedTotalResults {
t.Fatalf("expect %d results : got %d results", expectedTotalResults, totalResults)
}
}
func TestOverflow_Special(t *testing.T) {
thisTestHasToHaveTwoWorkers := 2
wp := New(freshCtx(), thisTestHasToHaveTwoWorkers)
releaseChan := make(chan struct{})
// Start workers, and have them all wait on a channel before completing.
for i := 0; i < 64; i++ {
wp.SubmitXT(Job{
Name: "test1",
Task: func(o Options) Result {
<-releaseChan
return Result{}
},
})
}
// Start a goroutine to free the workers after calling stop. This way
// the dispatcher can exit, then when this goroutine runs, the workerpool
// can exit.
go func() {
<-time.After(time.Millisecond)
close(releaseChan)
}()
wp.Stop()
// Now that the worker pool has exited, it is safe to inspect its waiting
// queue without causing a race.
qlen := wp.WorkerPool.WaitingQueueSize()
if qlen != 62 {
t.Fatal("Expected 62 tasks in waiting queue, have", qlen)
}
}
func TestStopRace(t *testing.T) {
max := 20
wp := New(freshCtx(), max)
workRelChan := make(chan struct{})
var started sync.WaitGroup
started.Add(max)
// Start workers, and have them all wait on a channel before completing.
for i := 0; i < max; i++ {
wp.Submit(func() {
started.Done()
<-workRelChan
})
}
started.Wait()
const doneCallers = 5
stopDone := make(chan struct{}, doneCallers)
for i := 0; i < doneCallers; i++ {
go func() {
wp.Stop()
stopDone <- struct{}{}
}()
}
select {
case <-stopDone:
t.Fatal("Stop should not return in any goroutine")
default:
}
close(workRelChan)
timeout := time.After(time.Second)
for i := 0; i < doneCallers; i++ {
select {
case <-stopDone:
case <-timeout:
t.Fatal("timedout waiting for Stop to return")
}
}
}
// Run this test with race detector to test that using WaitingQueueSize has no
// race condition
func TestWaitingQueueSizeRace(t *testing.T) {
const (
goroutines = 10
tasks = 20
workers = 5
)
wp := New(freshCtx(), workers)
maxChan := make(chan int)
for g := 0; g < goroutines; g++ {
go func() {
max := 0
// Submit 100 tasks, checking waiting queue size each time. Report
// the maximum queue size seen.
for i := 0; i < tasks; i++ {
wp.Submit(func() {
time.Sleep(time.Microsecond)
})
waiting := wp.WaitingQueueSize()
if waiting > max {
max = waiting
}
}
maxChan <- max
}()
}
// Find maximum queuesize seen by any goroutine.
maxMax := 0
for g := 0; g < goroutines; g++ {
max := <-maxChan
if max > maxMax {
maxMax = max
}
}
if maxMax == 0 {
t.Error("expected to see waiting queue size > 0")
}
if maxMax >= goroutines*tasks {
t.Error("should not have seen all tasks on waiting queue")
}
}
func TestSubmitXT_HowToHandleErrors(t *testing.T) {
wp := New(freshCtx(), defaultWorkers)
wp.SubmitXT(Job{ // Uses default timeout
Name: "Job 1 will pass",
Task: func(o Options) Result {
return Result{Data: "yay"}
}})
perJobContext, cncl := context.WithTimeout(freshCtx(), time.Duration(time.Millisecond*1))
defer cncl()
wp.SubmitXT(Job{ // Uses custom timeout
Name: "Job 2 will timeout",
Context: perJobContext,
Task: func(o Options) Result {
time.Sleep(time.Second * 20) // Simulate long running task
return Result{Data: "uhoh"}
}})
wp.SubmitXT(Job{ // Or if you encounter an error within the code in your job
Name: "Job 3 will encounter an error",
Task: func(o Options) Result {
err := fmt.Errorf("ErrorPretendException : something failed")
if err != nil {
return Result{Error: err}
}
return Result{Data: "uhoh"}
}})
results := wp.StopWaitXT()
failed, succeeded := 0, 0
for _, r := range results {
if r.Error != nil {
failed++
} else {
succeeded++
}
}
if succeeded != 1 || failed != 2 {
fmt.Println(results)
t.Fatalf("expected succeeded=1:failed=2 : got succeeded=%d:failed=%d", succeeded, failed)
}
}
func TestResultCountEqualsJobCount(t *testing.T) {
numJobs := 500
wp := New(freshCtx(), defaultWorkers)
for i := 0; i < numJobs; i++ {
ii := i
wp.SubmitXT(Job{
Name: fmt.Sprintf("Job %d", ii),
Task: func(o Options) Result { return Result{Data: fmt.Sprintf("Placeholder : %d", ii)} },
})
}
results := wp.StopWaitXT()
numResults := len(results)
if numResults != numJobs {
t.Fatalf("Expected %d results but got %d", numJobs, numResults)
}
}
func TestRuntimeDuration(t *testing.T) {
wp := New(freshCtx(), defaultWorkers)
wp.SubmitXT(Job{
Name: "test",
Task: func(o Options) Result {
time.Sleep(time.Second)
return Result{Data: "testing"}
},
})
res := wp.StopWaitXT()
first := res[0]
if first.Duration() == 0 {
t.Fatalf("Expected Duration() to not equal 0")
}
}
func TestName(t *testing.T) {
thename := "test99"
wp := New(freshCtx(), defaultWorkers)
wp.SubmitXT(Job{
Name: thename,
Task: func(o Options) Result {
return Result{Data: "testing"}
},
})
res := wp.StopWaitXT()
first := res[0]
if first.Name() != thename {
t.Fatalf("Expected Name() to be %s got %s", thename, first.Name())
}
}
func TestDefaultOptions(t *testing.T) {
varname, varvalue := "myvar", "myval"
opts := map[string]interface{}{varname: varvalue}
wp := NewWithOptions(freshCtx(), defaultWorkers, opts)
wp.SubmitXT(Job{
Name: "testing default options",
Task: func(o Options) Result {
// Set data to our opts myvar
return Result{Data: o[varname]}
},
})
res := wp.StopWaitXT()
first := res[0]
data := first.Data
if data != varvalue {
t.Fatalf("Expected option %s to be %s but got %s", varname, varvalue, data)
}
}
func TestPerJobOptions(t *testing.T) {
wp := New(freshCtx(), defaultWorkers)
wp.SubmitXT(Job{
Name: "job 1",
Task: func(o Options) Result {
// Set data to our opts myvar
return Result{Data: o["var"]}
},
Options: map[string]interface{}{"var": "job1value"},
})
wp.SubmitXT(Job{
Name: "job 2",
Task: func(o Options) Result {
// Set data to our opts myvar
return Result{Data: o["var"]}
},
Options: map[string]interface{}{"var": "job2value"},
})
res := wp.StopWaitXT()
for _, result := range res {
if result.Name() == "" {
t.Fatalf("Expected option %s to be %s but got %s", "var", "not ''", "''")
}
if result.Data == "" {
t.Fatalf("Expected data to not be null on : %s", result.Name())
}
if result.Name() == "job 1" {
if result.Data != "job1value" {
t.Fatalf("Expected %s option 'var' to be %s but got %s", result.Name(), "job1value", result.Data)
}
}
if result.Name() == "job 2" {
if result.Data != "job2value" {
t.Fatalf("Expected %s option 'var' to be %s but got %s", result.Name(), "job2value", result.Data)
}
}
}
}
func TestPerJobOptionsOverrideDefaultOptions(t *testing.T) {
opts := map[string]interface{}{"default": "value"}
wp := NewWithOptions(freshCtx(), defaultWorkers, opts)
// set default options so we can verify they were overwritten by per job options
wp.SubmitXT(Job{
Name: "job 1",
Task: func(o Options) Result {
// Set data to our opts myvar
return Result{Data: o["var"]}
},
Options: map[string]interface{}{"var": "job1value"},
})
wp.SubmitXT(Job{
Name: "job 2",
Task: func(o Options) Result {
// Set data to our opts myvar
return Result{Data: o["var"]}
},
Options: map[string]interface{}{"var": "job2value"},
})
res := wp.StopWaitXT()
for _, result := range res {
if result.Name() == "" {
t.Fatalf("Expected option %s to be %s but got %s", "var", "not ''", "''")
}
if result.Data == "" {
t.Fatalf("Expected data to not be null on : %s", result.Name())
}
if result.Name() == "job 1" {
if result.Data != "job1value" {
t.Fatalf("Expected %s option 'var' to be %s but got %s", result.Name(), "job1value", result.Data)
}
}
if result.Name() == "job 2" {
if result.Data != "job2value" {
t.Fatalf("Expected %s option 'var' to be %s but got %s", result.Name(), "job2value", result.Data)
}
}
}
}
/**
* This is a "cheap" test. More thorough tests need to be performed on wp.stop(true)
*/
func TestStopNow(t *testing.T) {
wp := New(freshCtx(), defaultWorkers)
wp.SubmitXT(Job{
Name: "job 1",
Task: func(o Options) Result {
// Set data to our opts myvar
return Result{Data: "placeholder"}
},
})
wp.stop(true)
}
func TestRetry(t *testing.T) {
wp := New(freshCtx(), defaultWorkers)
expectedError := errors.New("simulating error")
expectedName := "backoff_test"
expectedResultsLen := 2
wp.SubmitXT(Job{
Name: expectedName,
Task: func(o Options) Result {
return Result{Error: expectedError}
},
Retry: 3,
})
wp.SubmitXT(Job{
Name: "simulate_success",
Task: func(o Options) Result {
return Result{Data: "success"}
},
})
results := wp.StopWaitXT()
if len(results) != expectedResultsLen {
t.Fatalf("expected results len of %d, got results len of %d", expectedResultsLen, len(results))
}
for _, r := range results {
if r.Name() == expectedName && r.Error != expectedError {
t.Fatalf("Expected error %s : got error %s", expectedError, r.Error)
}
}
}
func TestCancelDefaultContext(t *testing.T) {
ctx, cncl := context.WithCancel(freshCtx())
wp := New(ctx, defaultWorkers)
totalJobs := 4
errs, succs, expectedErrors, expectedSuccs := 0, 0, totalJobs, 0
for i := 0; i < totalJobs; i++ {
wp.SubmitXT(Job{
Name: "a",
Task: func(o Options) Result {
time.Sleep(time.Second * 5)
return Result{Data: true}
},
})
}
time.Sleep(time.Second)
cncl()
results := wp.StopWaitXT()
for _, r := range results {
if r.Error != nil {
errs++
} else {
succs++
}
}
if errs != expectedErrors || succs != expectedSuccs {
t.Fatalf("Expected errs=%d:succs=%d : got errs=%d:succs=%d", expectedErrors, expectedSuccs, errs, succs)
}
}
func TestDeferDoesNotCancelJobImmediately(t *testing.T) {
wp := New(context.Background(), 10)
customContext, done := context.WithTimeout(
context.Background(),
time.Duration(time.Second*1),
)
defer done()
wp.SubmitXT(Job{
Name: "a",
Context: customContext,
Task: func(o Options) Result {
time.Sleep(time.Millisecond * 200)
return Result{Data: "Done"}
},
})
results := wp.StopWaitXT()
if len(results) != 1 {
t.Fatalf("Expected 1 got %d", len(results))
}
if results[0].Data != "Done" {
t.Fatalf("Expected 'Done' : got %s", results[0].Data)
}
}
func TestTimeoutHappensBeforeRetry(t *testing.T) {
// See issue #8 on GitHub
expectedResults := 1
timeout := time.Duration(time.Millisecond * 10)
wp := New(freshCtx(), 10)
ctx, done := context.WithTimeout(context.Background(), timeout)
defer done()
wp.SubmitXT(Job{
Name: "a",
Context: ctx,
// 10 retries with a job runtime of 5ms means this job should take 50ms
// but it is set to timeout in 10ms
// We only want the result from the timeout error, not from the last retry
Retry: 10,
Task: func(o Options) Result {
time.Sleep(time.Millisecond * 5)
errs := errors.New("test error")
if errs != nil {
return Result{Error: errs}
}
return Result{Data: "from a"}
},
})
results := wp.StopWaitXT()
if len(results) != expectedResults {
t.Fatalf("Expected %d results : got %d", expectedResults, len(results))
}
to := timeout + timeout
if results[0].Duration() > to {
t.Fatalf("Retries over rode timeout! When a job has a timeout of 1 second with Retry of 5, but each retry takes" +
" .5 seconds, we don't want a reply from the last retry, we want only a result from the timeout.")
}
}
func Test_100kJobs_1kWorkers_SleepBtwn5msAnd10msEach(t *testing.T) {
numjobs := 100000
numWorkers := 1000
wp := newWithNJobs(numjobs, numWorkers)
results := wp.StopWaitXT()
if len(results) != numjobs {
t.Fatalf("Expected %d : got %d", numjobs, len(results))
}
}