-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler_test.go
691 lines (617 loc) · 15.3 KB
/
scheduler_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
package smartpoll
import (
"context"
"errors"
"reflect"
"runtime"
"sync"
"testing"
"time"
)
// Tests that tasks are able to run independently, kicking them off using a
// RunHook. After an arbitrary number of times (different per task), with some
// very short arbitrary sleeps, no more runs are performed and
// sync.WaitGroup.Done is called. After all tasks have completed, the context
// is cancelled, and the main loop exits. The number of runs for each task is
// verified.
func TestScheduler_Run_runIndependentTasks(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
taskRuns := map[string]int{
"task1": 5,
"task2": 3,
"task3": 7,
}
runCounts := make(map[string]int)
var wg sync.WaitGroup
wg.Add(len(taskRuns))
options := []Option{
WithRunHook(func(ctx context.Context, internal *Internal) error {
for k := range taskRuns {
internal.Schedule(k, 0)
}
return nil
}),
}
for taskName, numRuns := range taskRuns {
taskName := taskName
numRuns := numRuns
options = append(options, WithTask(taskName, func(ctx context.Context) (TaskHook, error) {
time.Sleep(time.Millisecond * 3)
return func(ctx context.Context, internal *Internal) error {
runCounts[taskName]++
if runCounts[taskName] < numRuns {
internal.Schedule(taskName, time.Millisecond)
} else {
wg.Done()
}
return nil
}, nil
}))
}
// Create the scheduler with the tasks
scheduler, err := New(options...)
if err != nil {
t.Fatalf("Failed to create scheduler: %v", err)
}
// Run the scheduler in a separate goroutine
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
out := make(chan error)
go func() {
out <- scheduler.Run(ctx)
}()
wg.Wait()
cancel()
if err := <-out; err != context.Canceled {
t.Errorf("Scheduler returned an error: %v", err)
}
// Check that each task has run the expected number of times
for taskName, numRuns := range taskRuns {
if runCounts[taskName] != numRuns {
t.Errorf("Task %s ran %d times, expected %d", taskName, runCounts[taskName], numRuns)
}
}
}
// Based on TestScheduler_Run_runIndependentTasks, this test throws in a
// single hook, which kicks off the tasks. It also verifies the sanity of all
// the Scheduler.cases.
func TestScheduler_Run_runWithHook(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
taskRuns := map[string]int{
"task1": 5,
"task2": 3,
"task3": 7,
}
runCounts := make(map[string]*int32, len(taskRuns))
for k := range taskRuns {
runCounts[k] = new(int32)
}
var wg sync.WaitGroup
wg.Add(len(taskRuns))
startAllTasksCh := make(chan string)
var startedAndAllTasksRunning sync.WaitGroup
startedAndAllTasksRunning.Add(len(taskRuns) + 1)
startedAndAllTasksRunningCh := make(chan struct{})
go func() {
startedAndAllTasksRunning.Wait()
close(startedAndAllTasksRunningCh)
}()
const expectedStartAllTasksValue = "startAllTasks"
var scheduler *Scheduler
options := []Option{
WithHook(startAllTasksCh, func(ctx context.Context, internal *Internal, value string, ok bool) error {
if internal.scheduler != scheduler {
t.Error(`unexpected scheduler`)
}
for _, v := range scheduler.cases {
if v.Dir != reflect.SelectRecv {
t.Error(`unexpected case direction`, v.Dir)
}
if !v.Chan.IsValid() || v.Chan.Kind() != reflect.Chan {
t.Error(`unexpected case channel`, v.Chan)
}
}
if value != expectedStartAllTasksValue {
t.Errorf("Received unexpected value %v, expected %v", value, expectedStartAllTasksValue)
}
if !ok {
t.Errorf("Received unexpected closed channel")
}
for k := range taskRuns {
internal.Schedule(k, 0)
}
startedAndAllTasksRunning.Done()
return nil
}),
}
for taskName, numRuns := range taskRuns {
taskName := taskName
numRuns := numRuns
options = append(options, WithTask(taskName, func(ctx context.Context) (TaskHook, error) {
if *(runCounts[taskName]) == 0 {
startedAndAllTasksRunning.Done()
<-startedAndAllTasksRunningCh
}
time.Sleep(time.Millisecond * 3)
*(runCounts[taskName]) = (*(runCounts[taskName])) + 1
return func(ctx context.Context, internal *Internal) error {
if int(*(runCounts[taskName])) < numRuns {
internal.Schedule(taskName, time.Millisecond)
} else {
wg.Done()
}
return nil
}, nil
}))
}
// Create the scheduler with the tasks
scheduler, err := New(options...)
if err != nil {
t.Fatalf("Failed to create scheduler: %v", err)
}
// Run the scheduler in a separate goroutine
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
out := make(chan error)
go func() {
out <- scheduler.Run(ctx)
}()
// wait for a bit - it shouldn't do anything, for the moment
time.Sleep(time.Millisecond * 30)
select {
case <-out:
t.Fatal(`Scheduler exited early`)
default:
}
for taskName, runCount := range runCounts {
if *runCount != 0 {
t.Errorf("Task %s ran %d times, expected 0", taskName, *runCount)
}
}
// start the tasks
startAllTasksCh <- expectedStartAllTasksValue
wg.Wait()
cancel()
if err := <-out; err != context.Canceled {
t.Errorf("Scheduler returned an error: %v", err)
}
// Check that each task has run the expected number of times
for taskName, numRuns := range taskRuns {
if int(*(runCounts[taskName])) != numRuns {
t.Errorf("Task %s ran %d times, expected %d", taskName, int(*(runCounts[taskName])), numRuns)
}
}
}
func TestScheduler_Run_multipleRuns(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
// start a scheduler with a single task, which will block until we tell it otherwise
taskRunning := make(chan struct{})
unblockTask := make(chan struct{})
ee := errors.New(`some error`)
sch, err := New(
WithTask(nil, func(ctx context.Context) (TaskHook, error) {
if err := ctx.Err(); err != nil {
t.Error(err)
}
taskRunning <- struct{}{}
<-unblockTask
return nil, ee
}),
WithRunHook(func(ctx context.Context, internal *Internal) error {
internal.Schedule(nil, 0)
return nil
}),
)
if err != nil {
t.Fatal(err)
}
out := make(chan error)
run := func() context.CancelFunc {
ctx, cancel := context.WithCancel(context.Background())
go func() {
out <- sch.Run(ctx)
}()
return cancel
}
// starts immediately, exits with the task still running
firstRun := func() {
cancel := run()
<-taskRunning
cancel()
if err := <-out; err != context.Canceled {
t.Fatal(err)
}
}
// blocks until we unblock the task, then exits due to task error
secondRun := func() {
cancel := run()
defer cancel()
time.Sleep(time.Millisecond * 30)
select {
case <-taskRunning:
t.Fatal(`task should not be running`)
case <-out:
t.Fatal(`scheduler should not have exited`)
default:
}
unblockTask <- struct{}{}
<-taskRunning
unblockTask <- struct{}{}
if err := <-out; err != ee {
t.Fatal(err)
}
}
for i := 0; i < 3; i++ {
firstRun()
secondRun()
}
// finally, exit due to context cancellation, while blocking on the prior task
firstRun()
cancel := run()
defer cancel()
time.Sleep(time.Millisecond * 30)
select {
case <-taskRunning:
t.Fatal(`task should not be running`)
case <-out:
t.Fatal(`scheduler should not have exited`)
default:
}
cancel()
if err := <-out; err != context.Canceled {
t.Fatal(err)
}
secondRun()
}
func TestScheduler_Run_taskHookError(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
ee := errors.New(`some error`)
var ctx1, ctx2 context.Context
sch, err := New(
WithTask(nil, func(ctx context.Context) (TaskHook, error) {
ctx1 = ctx
if err := ctx.Err(); err != nil {
t.Error(err)
}
return func(ctx context.Context, internal *Internal) error {
ctx2 = ctx
if err := ctx.Err(); err != nil {
t.Error(err)
}
return ee
}, nil
}),
WithRunHook(func(ctx context.Context, internal *Internal) error {
internal.ScheduleSooner(nil, time.Millisecond*10)
return nil
}),
)
if err != nil {
t.Fatal(err)
}
if err := sch.Run(context.Background()); err != ee {
t.Error(err)
}
if err := ctx1.Err(); err != context.Canceled {
t.Error(err)
}
if err := ctx2.Err(); err != context.Canceled {
t.Error(err)
}
}
func TestScheduler_Run_runHookErrorAndClearingTimers(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
var task Task = func(ctx context.Context) (TaskHook, error) {
const msg = `should not have been called`
t.Error(msg)
panic(msg)
}
ee := errors.New(`some error`)
p1 := new(float64)
var sch *Scheduler
sch, err := New(
WithTask(nil, task),
WithTask(1, task),
WithTask(true, task),
WithTask(p1, task),
WithRunHook(func(ctx context.Context, internal *Internal) error {
now := time.Now()
t1 := now.Add(time.Hour)
t2 := now.Add(time.Hour * 2)
internal.Schedule(1, time.Hour*6)
internal.Schedule(1, time.Hour*5)
internal.ScheduleAtSooner(1, t1)
internal.ScheduleAt(p1, t2)
internal.Schedule(true, time.Hour*4)
if v := sch.tasks[nil]; v == nil || v.timer != nil || v.next != (time.Time{}) {
t.Error()
}
if v := sch.tasks[1]; v == nil || v.timer == nil || v.next != t1 {
t.Error()
}
if v := sch.tasks[p1]; v == nil || v.timer == nil || v.next != t2 {
t.Error()
}
if v := sch.tasks[true]; v == nil || v.timer == nil {
t.Error()
}
return ee
}),
)
if err != nil {
t.Fatal(err)
}
if err := sch.Run(context.Background()); err != ee {
t.Error(err)
}
if len(sch.tasks) != 4 {
t.Error(len(sch.tasks))
}
for k, v := range sch.tasks {
if v == nil || v.timer != nil || v.next != (time.Time{}) {
t.Error(k)
}
}
}
func TestScheduler_Run_multipleHooksHookError(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
aIn := make(chan int)
aOut := make(chan int)
bIn := make(chan error)
bOut := make(chan error)
cIn := make(chan *int)
cOut := make(chan *int)
dIn := make(chan []string)
dOut := make(chan []string)
ee := errors.New(`some error`)
sch, err := New(
WithHook(aIn, func(ctx context.Context, internal *Internal, value int, ok bool) error {
if !ok {
t.Error(`unexpected closed channel`)
}
aOut <- value
return nil
}),
WithHook(bIn, func(ctx context.Context, internal *Internal, value error, ok bool) error {
if !ok {
t.Error(`unexpected closed channel`)
}
bOut <- value
return nil
}),
WithHook(cIn, func(ctx context.Context, internal *Internal, value *int, ok bool) error {
if !ok {
return ee
}
cOut <- value
return nil
}),
WithHook(dIn, func(ctx context.Context, internal *Internal, value []string, ok bool) error {
if !ok {
t.Error(`unexpected closed channel`)
}
dOut <- value
return nil
}),
// dummy task to avoid error on New
WithTask(nil, func(ctx context.Context) (TaskHook, error) {
const msg = `should not have been called`
t.Error(msg)
panic(msg)
}),
)
if err != nil {
t.Fatal(err)
}
out := make(chan error)
go func() {
out <- sch.Run(context.Background())
}()
aIn <- 9123
if v := <-aOut; v != 9123 {
t.Error(v)
}
{
e := errors.New(`asdasads`)
bIn <- e
if v := <-bOut; v != e {
t.Error(v)
}
}
{
n := 123
cIn <- &n
if v := <-cOut; v != &n {
t.Error(v)
}
}
{
dIn <- []string{`a`, `b`, `c`}
if v := <-dOut; len(v) != 3 || v[0] != `a` || v[1] != `b` || v[2] != `c` {
t.Error(v)
}
}
bIn <- nil
if v := <-bOut; v != nil {
t.Error(v)
}
{
e := errors.New(`z`)
bIn <- e
if v := <-bOut; v != e {
t.Error(v)
}
}
close(cIn)
if err := <-out; err != ee {
t.Error(err)
}
}
func TestScheduler_Run_taskWithoutHook(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
in := make(chan struct{})
schedule := make(chan struct{})
sch, err := New(
WithTask(nil, func(ctx context.Context) (TaskHook, error) {
in <- struct{}{}
return nil, nil
}),
WithHook(schedule, func(ctx context.Context, internal *Internal, _ struct{}, ok bool) error {
if !ok {
return context.Canceled
}
internal.Schedule(nil, 0)
return nil
}),
)
if err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
defer close(done)
if err := sch.Run(context.Background()); err != context.Canceled {
t.Error(err)
}
}()
// deliberately run a bunch of times - regression on a deadlock bug
for i := 0; i < 50; i++ {
schedule <- struct{}{}
<-in
}
close(schedule)
<-done
}
func TestScheduler_Run_taskRuntimeGoexit(t *testing.T) {
defer checkNumGoroutines(time.Second * 3)(t)
schCh := make(chan func(internal *Internal))
taskIn := make(chan struct{})
taskOut := make(chan struct{})
taskHookIn := make(chan struct{})
taskHookOut := make(chan struct{})
sch, err := New(
WithHook(schCh, func(ctx context.Context, internal *Internal, f func(internal *Internal), _ bool) error {
f(internal)
return nil
}),
WithTask(`Task`, func(ctx context.Context) (TaskHook, error) {
taskIn <- struct{}{}
<-taskOut
runtime.Goexit()
t.Error(`should not reach here`)
panic(`should not reach here`)
}),
WithTask(`TaskHook`, func(ctx context.Context) (TaskHook, error) {
return func(ctx context.Context, internal *Internal) error {
taskHookIn <- struct{}{}
<-taskHookOut
runtime.Goexit()
t.Error(`should not reach here`)
panic(`should not reach here`)
}, nil
}),
)
if err != nil {
t.Fatal(err)
}
out := make(chan error)
run := func() {
out <- sch.Run(context.Background())
}
go run()
schCh <- func(internal *Internal) {
internal.Schedule(`Task`, 0)
}
<-taskIn
taskOut <- struct{}{}
if err := <-out; err != ErrPanicInTask {
t.Errorf(`unexpected error: %v`, err)
}
go run()
schCh <- func(internal *Internal) {
internal.Schedule(`TaskHook`, 0)
}
<-taskHookIn
taskHookOut <- struct{}{}
if err := <-out; err != ErrPanicInTask {
t.Errorf(`unexpected error: %v`, err)
}
// context cancel test for Task path
go run()
schCh <- func(internal *Internal) {
internal.Schedule(`Task`, 0)
internal.Schedule(`TaskHook`, 0)
}
<-taskIn
<-taskHookIn
taskOut <- struct{}{}
time.Sleep(time.Millisecond * 30)
taskHookOut <- struct{}{}
if err := <-out; err != ErrPanicInTask {
t.Errorf(`unexpected error: %v`, err)
}
}
func TestScheduler_Run_noTasks(t *testing.T) {
defer func() {
if r := recover(); r != `smartpoll: scheduler must be initialized with New` {
t.Error(r)
}
}()
_ = (&Scheduler{}).Run(context.Background())
}
func TestScheduler_Run_concurrentRun(t *testing.T) {
sch, err := New(
WithTask(nil, func(ctx context.Context) (TaskHook, error) {
return func(ctx context.Context, internal *Internal) error { return nil }, nil
}),
)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
out := make(chan struct{})
go func() {
defer close(out)
_ = sch.Run(ctx)
}()
for i := 0; ; i++ {
if i >= 5 {
t.Fatal(`expected to mark running`)
}
time.Sleep(time.Millisecond * 50)
if sch.running.Load() == 1 {
break
}
}
select {
case <-out:
t.Fatal(`expected to block`)
default:
}
if v := sch.running.Load(); v != 1 {
t.Fatal(v)
}
func() {
defer func() {
if v := recover(); v != `smartpoll: scheduler already running` {
t.Fatal(v)
}
}()
_ = sch.Run(context.Background())
}()
time.Sleep(time.Millisecond * 30)
if v := sch.running.Load(); v != 1 {
t.Fatal(v)
}
select {
case <-out:
t.Fatal(`expected to block`)
default:
}
cancel()
<-out
if v := sch.running.Load(); v != 0 {
t.Fatal(v)
}
}