-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpool_test.go
1337 lines (1109 loc) · 43.9 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
// ** goworkerpool.com **********************************************************************************************
// ** github.com/enriquebris/goworkerpool **
// ** v0.10.0 *******************************************************************************************************
package goworkerpool
import (
"sync"
"testing"
"time"
"github.com/enriquebris/goconcurrentqueue"
"github.com/stretchr/testify/suite"
)
type PoolTestSuite struct {
suite.Suite
pool *Pool
}
const (
initialWorkers = 5
maxOperationsInQueue = 100
)
func (suite *PoolTestSuite) SetupTest() {
var err error
// build a *Pool and wait until all initial workers are up and running
suite.pool, err = NewPoolWithOptions(PoolOptions{
TotalInitialWorkers: initialWorkers,
MaxWorkers: 10,
MaxOperationsInQueue: maxOperationsInQueue,
WaitUntilInitialWorkersAreUp: true,
})
suite.NoError(err)
}
// ***************************************************************************************
// ** NewPool
// ***************************************************************************************
func (suite *PoolTestSuite) TestNewPoolWrongData() {
pool := NewPool(-1, maxOperationsInQueue, false)
suite.Nil(pool)
pool = NewPool(initialWorkers, -1, false)
suite.Nil(pool)
}
func (suite *PoolTestSuite) TestNewPool() {
pool := NewPool(initialWorkers, maxOperationsInQueue, false)
suite.NotNil(pool)
}
// ***************************************************************************************
// ** NewPoolWithOptions
// ***************************************************************************************
// new pool with MaxOperationsInQueue == 0 ==> error
func (suite *PoolTestSuite) TestNewPoolWithOptionsZeroMaxOperationsInQueue() {
pool, err := NewPoolWithOptions(PoolOptions{
TotalInitialWorkers: 5,
MaxWorkers: 1,
MaxOperationsInQueue: 0,
NewWorkerChan: nil,
})
suite.Nil(pool)
suite.Error(err, "error expected if MaxOperationsInQueue == 0")
// error's type
pErr, ok := err.(*PoolError)
suite.True(ok, "expected error's type: *PoolError")
suite.Equalf(ErrorData, pErr.Code(), "expected error's type: %v", ErrorData)
}
// new pool MaxWorkers == 0 ==> error
func (suite *PoolTestSuite) TestNewPoolWithOptionsZeroMaxWorkers() {
pool, err := NewPoolWithOptions(PoolOptions{
TotalInitialWorkers: 5,
MaxWorkers: 0,
MaxOperationsInQueue: 10,
NewWorkerChan: nil,
})
suite.Nil(pool)
suite.Error(err, "error expected if MaxWorkers == 0")
// error's type
pErr, ok := err.(*PoolError)
suite.True(ok, "expected error's type: *PoolError")
suite.Equalf(ErrorData, pErr.Code(), "expected error's type: %v", ErrorData)
}
// new pool with valid options (configuration parameters)
func (suite *PoolTestSuite) TestNewPoolWithOptions() {
newWorkerChan := make(chan int, initialWorkers+1)
pool, err := NewPoolWithOptions(PoolOptions{
TotalInitialWorkers: initialWorkers,
MaxWorkers: 10,
MaxOperationsInQueue: maxOperationsInQueue,
NewWorkerChan: newWorkerChan,
})
suite.NoError(err)
// wait until initial workers are up
totalWorkers := 0
for totalWorkers < initialWorkers {
select {
case newWorker := <-newWorkerChan:
totalWorkers = totalWorkers + newWorker
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for a worker initialization")
}
}
// check values defined at initialization
suite.checkInitializationValues(pool)
}
// new pool && wait until all initial workers are up and running
func (suite *PoolTestSuite) TestNewPoolWithOptionsWaitUntilInitialWorkersAreUp() {
var (
pool *Pool
err error
poolIsUp = make(chan struct{})
)
go func() {
pool, err = NewPoolWithOptions(PoolOptions{
TotalInitialWorkers: initialWorkers,
MaxWorkers: 10,
MaxOperationsInQueue: maxOperationsInQueue,
NewWorkerChan: nil,
WaitUntilInitialWorkersAreUp: true,
})
suite.NoError(err)
poolIsUp <- struct{}{}
}()
select {
case <-poolIsUp:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for workers initialization")
}
// combined with this WaitUntilInitialWorkersAreUp should be the deprecated function StartWorkersAndWait, the
// whole following section could be removed once StartWorkersAndWait gets removed
startWorkersAndWaitIsDone := make(chan struct{})
go func() {
err = pool.StartWorkersAndWait()
suite.NoError(err)
startWorkersAndWaitIsDone <- struct{}{}
}()
select {
case <-startWorkersAndWaitIsDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for workers StartWorkersAndWait")
}
// check values defined at initialization
suite.checkInitializationValues(pool)
}
// ***************************************************************************************
// ** initialization
// ***************************************************************************************
// checkInitializationValues checks values defined in initialization()
func (suite *PoolTestSuite) checkInitializationValues(pool *Pool) {
// max operations in queue
suite.Equal(maxOperationsInQueue, cap(pool.activityChan))
// workers
// verify that suite.pool.totalWorkers == initialWorkers
suite.Equal(initialWorkers, pool.totalWorkers.GetValue())
// verify that all workers are available
suite.Equal(initialWorkers, pool.availableWorkers.GetLen())
// no workers in progress
suite.Equal(0, pool.totalWorkersInProgress.GetValue(), "unexpected workers in progress just after initialization")
// no actions / tasks
suite.Zero(pool.actions.GetLen(), "unexpected enqueued actions just after initialization")
suite.Zero(pool.tasks.GetLen(), "unexpected enqueued tasks just after initialization")
// metrics
suite.Zero(pool.taskSuccesses.GetValue())
// no actions in progress
suite.False(pool.getStatus(waitInProgress), "unexpected Wait action in progress")
suite.False(pool.getStatus(killAllWorkersInProgress), "unexpected KillAllWorkers in progress")
// trigger on totalWorkers.0.triggerZeroTotalWorkers
suite.NotNil(pool.totalWorkers.GetTriggerOnValue(0, triggerZeroTotalWorkers), "trigger function expected for totalWorkers.0.triggerZeroTotalWorkers")
// verify that all workers have different IDs
suite.checkWorkersID(pool)
}
// initialize() with AddWorker() failing because KillAllWorkers is in progress
func (suite *PoolTestSuite) TestInitializationFailAddWorker() {
// mimic KillAllWorkers in progress to avoid create new workers
suite.pool.setStatus(killAllWorkersInProgress, true)
// set log channel
logChan := make(chan PoolLog, initialWorkers)
suite.pool.SetLogChan(logChan)
doneChan := make(chan []PoolLog)
// listen to log channel
go func(logChan chan PoolLog, max int, doneChan chan []PoolLog) {
total := 0
poolLogList := make([]PoolLog, 0)
for total < max-1 {
poolLog := <-logChan
poolLogList = append(poolLogList, poolLog)
total++
}
doneChan <- poolLogList
}(logChan, initialWorkers, doneChan)
// initialize the pool
suite.pool.initialize(PoolOptions{
TotalInitialWorkers: initialWorkers,
MaxWorkers: 10,
MaxOperationsInQueue: maxOperationsInQueue,
WaitUntilInitialWorkersAreUp: true,
})
// get total workers && availableWorkers
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
select {
case logs := <-doneChan:
// check the error logs
for i := 0; i < len(logs); i++ {
// log's code: error
suite.Equal(logError, logs[i].Code)
// error's type
pErr, ok := logs[i].Error.(*PoolError)
suite.True(ok)
suite.Equal(ErrorKillAllWorkersInProgress, pErr.Code())
}
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
// check that no workers were added to workers / availableWorkers
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
suite.Equal(totalAvailableWorkers, suite.pool.availableWorkers.GetLen())
}
// point pool.totalWorkers to zero to trigger the totalWorkers.zero trigger's function
func (suite *PoolTestSuite) TestInitializationTriggerTotalWorkersZero() {
suite.Equal(initialWorkers, suite.pool.totalWorkers.GetValue())
// mimic KillAllWorkers in progress
suite.pool.setStatus(killAllWorkersInProgress, true)
// mimic Wait in progress
suite.pool.setStatus(waitInProgress, true)
// set noWorkersChan (part of Wait "in progress")
noWorkersChan := make(chan struct{}, 2)
suite.pool.noWorkersChan = noWorkersChan
// update totalWorkers to zero
for suite.pool.totalWorkers.GetValue() >= 0 {
suite.pool.totalWorkers.Update(-1)
}
select {
case <-suite.pool.getNoWorkersChan():
// "no workers" signal received
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for noWorkers channel")
}
// killAllWorkersInProgress should be updated to false
suite.False(suite.pool.getStatus(killAllWorkersInProgress))
}
// ***************************************************************************************
// ** dispatcher - action
// ***************************************************************************************
// send a signal over activityChan while no action/task was enqueued
func (suite *PoolTestSuite) TestDispatcherNoActionNoTask() {
suite.True(suite.pool.getStatus(dispatcherInProgress))
defer suite.True(suite.pool.getStatus(dispatcherInProgress))
// set log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// mimic "send action/task"
select {
case suite.pool.activityChan <- struct{}{}:
default:
suite.FailNow("can't send message over activityChannel")
}
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
pErr, ok := pLog.Error.(*PoolError)
suite.True(ok, "expected error's type: *PoolError")
suite.Equal(ErrorDispatcherNoActionNoTask, pErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
}
// dispatcher stops after activityChann is closed
func (suite *PoolTestSuite) TestDispatcherClosedActivityChan() {
close(suite.pool.activityChan)
// give the dispatcher 1second to update dispatcherAlive status
time.Sleep(time.Second)
suite.False(suite.pool.getStatus(dispatcherInProgress))
}
// dispatcher receives an "activity" signal but actions.Dequeue() fails
func (suite *PoolTestSuite) TestDispatcherActionQueueError() {
// replace action's queue
suite.pool.actions = goconcurrentqueue.NewFixedFIFO(0)
// lock the action's queue, any future queue's operation will fail
suite.pool.actions.Lock()
// set log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// mimic "send action/task"
select {
case suite.pool.activityChan <- struct{}{}:
default:
suite.FailNow("can't send message over activityChannel")
}
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
qErr, ok := pLog.Error.(*goconcurrentqueue.QueueError)
suite.True(ok, "expected error's type: *goconcurrentqueue.QueueError")
suite.Equal(goconcurrentqueue.QueueErrorCodeLockedQueue, qErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
suite.True(suite.pool.getStatus(dispatcherInProgress))
}
// dispatcher receives an action to be executed only by itself, not by the worker
func (suite *PoolTestSuite) TestDispatcherActionDoNotSentToWorker() {
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
// to let know that the preFunc() was executed
preFuncDone := make(chan struct{}, 2)
// enqueue the action
err := suite.pool.addAction("dummyAction", false, func() {
preFuncDone <- struct{}{}
})
suite.NoError(err)
// wait until action's preFunc execution is done
select {
case <-preFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for action's preFunc execution")
}
notSupposedToHappenChan := make(chan struct{}, 2)
// add a trigger to totalWorkers - 1 ==> fail and wait some short time !!!
suite.pool.totalWorkers.SetTriggerOnValue(totalWorkers-1, "error", func(currentValue int, previousValue int) {
notSupposedToHappenChan <- struct{}{}
})
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
suite.Equal(totalAvailableWorkers, suite.pool.availableWorkers.GetLen())
select {
case <-notSupposedToHappenChan:
suite.FailNow("available workers' amount should not change after dispatcher executes an action with sendToWorker == false")
case <-time.After(3 * time.Second):
// available workers' amount keep the same after 3 seconds ==> it's ok, it's the expected, no any worker
// processed the enqueued action
}
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
suite.Equal(totalAvailableWorkers, suite.pool.availableWorkers.GetLen())
}
// dispatcher receives an action to be executed by a worker, but can't dequeue a worker and later can't re-enqueue the
// failed action
func (suite *PoolTestSuite) TestDispatcherActionByWorkerCantDequeueWorker() {
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalActions := suite.pool.actions.GetLen()
totalTasks := suite.pool.tasks.GetLen()
// to let know that the preFunc() was executed
preFuncDone := make(chan struct{}, 2)
// to receive pool's logs
logChan := make(chan PoolLog, 2)
// set log channel
suite.pool.SetLogChan(logChan)
// replace availableWorkers internal queue
suite.pool.availableWorkers = goconcurrentqueue.NewFixedFIFO(1)
// lock the queue, so Dequeue operation will fail
suite.pool.availableWorkers.Lock()
// enqueue the action
err := suite.pool.addAction("dummyAction", true, func() {
// lock internal's pool actions queue, all future operations over it will fail
suite.pool.actions.Lock()
preFuncDone <- struct{}{}
})
suite.NoError(err)
// wait until action's preFunc execution is done
select {
case <-preFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for action's preFunc execution")
}
// wait for the first && second error:
// 1 - no worker couldn't be dequeued from availableWorkers queue
// 2 - failed action couldn't be enqueued into actions queue
for i := 0; i < 2; i++ {
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
qErr, ok := pLog.Error.(*goconcurrentqueue.QueueError)
suite.True(ok, "expected error's type: *goconcurrentqueue.QueueError")
suite.Equal(goconcurrentqueue.QueueErrorCodeLockedQueue, qErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
}
// same amount of workers expected
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
// same amount of actions as before the action was enqueued
suite.Equal(totalActions, suite.pool.actions.GetLen())
// same amount of tasks as before the action was enqueued
suite.Equal(totalTasks, suite.pool.tasks.GetLen())
}
// dispatcher receives an action to be executed by a worker, but can't dequeue a worker and later action will be
// re-enqueued
func (suite *PoolTestSuite) TestDispatcherActionByWorkerCantDequeueWorkerReEnqueueAction() {
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalActions := suite.pool.actions.GetLen()
totalTasks := suite.pool.tasks.GetLen()
// to let know that the preFunc() was executed
preFuncDone := make(chan struct{}, 2)
// to receive pool's logs
logChan := make(chan PoolLog, 2)
// set log channel
suite.pool.SetLogChan(logChan)
// replace availableWorkers internal queue
suite.pool.availableWorkers = goconcurrentqueue.NewFixedFIFO(1)
// lock the queue, so Dequeue operation will fail
suite.pool.availableWorkers.Lock()
// enqueue the action
err := suite.pool.addAction("dummyAction", true, func() {
preFuncDone <- struct{}{}
})
suite.NoError(err)
// wait until action's preFunc execution is done
select {
case <-preFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for action's preFunc execution")
}
// wait for the logChannel: [error] no worker couldn't be dequeued from availableWorkers queue
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
qErr, ok := pLog.Error.(*goconcurrentqueue.QueueError)
suite.True(ok, "expected error's type: *goconcurrentqueue.QueueError")
suite.Equal(goconcurrentqueue.QueueErrorCodeLockedQueue, qErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
// dispatcher failed to dequeue a worker to process the action, so it re-enqueued the action
// wait until action's preFunc execution is done
select {
case <-preFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for action's preFunc execution")
}
// same amount of workers
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
// same amount of actions as before the action was enqueued
suite.Equal(totalActions, suite.pool.actions.GetLen())
// same amount of tasks as before the action was enqueued
suite.Equal(totalTasks, suite.pool.tasks.GetLen())
}
// dispatcher receives an action to be executed by a worker
func (suite *PoolTestSuite) TestDispatcherActionByWorker() {
// build a *Pool (only 1 worker) and wait until all initial workers are up and running
var err error
suite.pool, err = NewPoolWithOptions(PoolOptions{
TotalInitialWorkers: 1,
MaxWorkers: 10,
MaxOperationsInQueue: maxOperationsInQueue,
WaitUntilInitialWorkersAreUp: true,
})
suite.NoError(err)
// metrics
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
totalActions := suite.pool.actions.GetLen()
totalTasks := suite.pool.tasks.GetLen()
taskSuccesses := suite.pool.taskSuccesses.GetValue()
// channel to know when the postActionFunc is done
externalPostActionFuncDone := make(chan struct{}, 2)
// add a ExternalPostActionFunc to worker to know when the action was processed by a worker
// dequeue the only worker
rawWorker, err := suite.pool.availableWorkers.Dequeue()
suite.NoError(err)
wkr, ok := rawWorker.(*worker)
suite.True(ok, "expected worker's type: *worker")
wkr.SetExternalPostActionFunc(func() {
externalPostActionFuncDone <- struct{}{}
})
// re-enqueue the worker into availableWorkers
err = suite.pool.availableWorkers.Enqueue(wkr)
suite.NoError(err, "unexpected error while enqueueing worker into availableWorkers")
// to let know that the preFunc() was executed
preFuncDone := make(chan struct{}, 2)
// enqueue the action
err = suite.pool.addAction("dummyAction", true, func() {
preFuncDone <- struct{}{}
})
suite.NoError(err)
// wait until action's preFunc execution is done
select {
case <-preFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for action's preFunc execution")
}
select {
case <-externalPostActionFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for worker's postActionFunc")
}
// same amount of workers
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
// same amount of actions as before the action was enqueued
suite.Equal(totalActions, suite.pool.actions.GetLen())
// same amount of tasks as before the action was enqueued
suite.Equal(totalTasks, suite.pool.tasks.GetLen())
// same amount of task successes
suite.Equal(taskSuccesses, suite.pool.taskSuccesses.GetValue())
// same amount of available workers
suite.Equal(totalAvailableWorkers, suite.pool.availableWorkers.GetLen())
}
// ***************************************************************************************
// ** dispatcher - regular task
// ***************************************************************************************
// dispatcher receives an "activity signal" but tasks' dequeue fails
func (suite *PoolTestSuite) TestDispatcherTaskCantDequeueTask() {
// log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// lock the tasks queue, any future dequeue attempt will fail
suite.pool.tasks.Lock()
// send a signal over activityChannel
select {
case suite.pool.activityChan <- struct{}{}:
default:
suite.FailNow("can't send signals over activityChan")
}
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
qErr, ok := pLog.Error.(*goconcurrentqueue.QueueError)
suite.True(ok, "expected error's type: *goconcurrent.QueueError")
suite.Equal(goconcurrentqueue.QueueErrorCodeLockedQueue, qErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
}
// dispatcher receives a task but can't dequeue a worker to pass the task
func (suite *PoolTestSuite) TestDispatcherTaskCantDequeueWorker() {
// log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// worker's func
suite.pool.SetWorkerFunc(func(data interface{}) bool {
return true
})
// lock availableWorkers to avoid dequeue any worker
suite.pool.availableWorkers.Lock()
suite.NoError(suite.pool.AddTask("dummy task"))
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
qErr, ok := pLog.Error.(*goconcurrentqueue.QueueError)
suite.True(ok, "expected error's type: *goconcurrentqueue.QueueError")
suite.Equal(goconcurrentqueue.QueueErrorCodeLockedQueue, qErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
}
// dispatcher receives a task to be executed by a worker
func (suite *PoolTestSuite) TestDispatcherTask() {
workerDone := make(chan interface{}, 2)
// set default worker's handler
suite.pool.SetWorkerFunc(func(data interface{}) bool {
workerDone <- data
return true
})
taskData := "dummy data"
suite.NoError(suite.pool.AddTask(taskData))
select {
case data := <-workerDone:
// verify the task's data
suite.Equal(taskData, data)
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for worker's function execution")
}
}
// ***************************************************************************************
// ** dispatcher - late action (tasks)
// ***************************************************************************************
// dispatcher receives a late action (task) but the data is not a proper action
func (suite *PoolTestSuite) TestDispatcherTaskLateActionWrongType() {
// log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// send the late action
suite.NoError(suite.pool.addTask(taskLateAction, "incorrect data type", nil, nil))
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
}
// dispatcher receives a late action (task) + pre-task function to be executed by the dispatcher
func (suite *PoolTestSuite) TestDispatcherTaskLateActionDoNotSendToWorker() {
// metrics
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
totalActions := suite.pool.actions.GetLen()
totalTasks := suite.pool.tasks.GetLen()
taskSuccesses := suite.pool.taskSuccesses.GetValue()
preFuncDone := make(chan struct{}, 2)
// send the late action
suite.NoError(suite.pool.addTask(taskLateAction,
action{
Code: actionLateKillWorker,
SendToWorker: false,
PreExternalFunc: func() {
preFuncDone <- struct{}{}
},
},
nil,
nil))
select {
case <-preFuncDone:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for preLateTask function")
}
// same amount of workers
suite.Equal(totalWorkers, getSyncMapTotalLen(suite.pool.workers))
// same amount of actions as before the action was enqueued
suite.Equal(totalActions, suite.pool.actions.GetLen())
// same amount of tasks as before the action was enqueued
suite.Equal(totalTasks, suite.pool.tasks.GetLen())
// same amount of task successes
suite.Equal(taskSuccesses, suite.pool.taskSuccesses.GetValue())
// same amount of available workers
suite.Equal(totalAvailableWorkers, suite.pool.availableWorkers.GetLen())
}
// ***************************************************************************************
// ** dispatcher worker feedback
// ***************************************************************************************
// dispatcherWorkerFeedback receives a message for a unknown worker
func (suite *PoolTestSuite) TestDispatcherWorkerFeedbackUnknownWorker() {
totalWorkers := suite.pool.GetTotalWorkers()
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
// replace the external feedback function for all workers
suite.pool.workers.Range(func(key interface{}, value interface{}) bool {
wkr, _ := value.(*worker)
wkr.SetExternalFeedbackFunction(func(workerID int, reEnqueueWorker bool) {
// remove the worker's entry, so the external feedback function will fail
suite.pool.workers.Delete(workerID)
// sends the feedback info through a channel (the channel's listener resides in dispatcherWorkerFeedback)
suite.pool.dispatcherWorkerFeedbackChan <- workerFeedback{
workerID: workerID,
reEnqueueWorker: reEnqueueWorker,
}
})
return true
})
// log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// set worker's func
suite.pool.SetWorkerFunc(func(data interface{}) bool {
return true
})
// send dummy task
suite.pool.AddTask("dummy data")
// wait for log channel
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
suite.Equal("dispatcherWorkerFeedback.unknown worker", pLog.Message)
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
// verify that no extra workers were enqueued
suite.Equal(totalWorkers, suite.pool.GetTotalWorkers())
suite.Equal(totalAvailableWorkers-1, suite.pool.availableWorkers.GetLen())
}
// dispatcherWorkerFeedback receives a message to re-enqueue a worker but the attempt fails
func (suite *PoolTestSuite) TestDispatcherWorkerFeedbackCantReEnqueueWorker() {
totalWorkers := suite.pool.GetTotalWorkers()
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
// log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// set worker's func
suite.pool.SetWorkerFunc(func(data interface{}) bool {
// lock the availableWorkers queue will prevent any near-future attempt to enqueue workers
suite.pool.availableWorkers.Lock()
return true
})
// send dummy task
suite.pool.AddTask("dummy data")
// wait for log channel
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
suite.Equal("dispatcherWorkerFeedback.availableWorkers.Enqueue", pLog.Message)
qErr, ok := pLog.Error.(*goconcurrentqueue.QueueError)
suite.True(ok, "expected error's type: *goconcurrentqueue.QueueError")
suite.Equal(goconcurrentqueue.QueueErrorCodeLockedQueue, qErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
// verify that 1 worker was removed from the lists
suite.Equal(totalWorkers-1, suite.pool.GetTotalWorkers())
suite.Equal(totalAvailableWorkers-1, suite.pool.availableWorkers.GetLen())
}
// dispatcherWorkerFeedback receives a message to not re-enqueue a worker but the removing attempt fails
func (suite *PoolTestSuite) TestDispatcherWorkerFeedbackCantRemoveWorker() {
totalWorkers := getSyncMapTotalLen(suite.pool.workers)
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
// log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
// send the signal to dispatcherWorkerFeedback
go func() {
// add a fake worker (wrong worker's type)
suite.pool.workers.Store(-1, "wrong.worker.type")
select {
case suite.pool.dispatcherWorkerFeedbackChan <- workerFeedback{
workerID: -1,
reEnqueueWorker: false,
}:
default:
suite.FailNow("couldn't send signal to dispatcherWorkerFeedback")
}
}()
select {
case pLog := <-logChan:
suite.Equal(logError, pLog.Code)
pErr, ok := pLog.Error.(*PoolError)
suite.True(ok, "expected error's type: *PoolError")
suite.Equal(ErrorWorkerType, pErr.Code())
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for log channel messages")
}
// verify metrics
// I added a fake worker to workers
suite.Equal(totalWorkers+1, getSyncMapTotalLen(suite.pool.workers))
suite.Equal(totalAvailableWorkers, suite.pool.availableWorkers.GetLen())
}
// dispatcherWorkerFeedback receives a signal to not re-enqueue the worker, so it will be removed
func (suite *PoolTestSuite) TestDispatcherWorkerFeedbackRemoveWorker() {
}
// dispatcherWorkerFeedback receives a signal to re-Enqueue the worker
func (suite *PoolTestSuite) TestDispatcherWorkerFeedback() {
}
// ***************************************************************************************
// ** workers
// ***************************************************************************************
// countTotalWorkers returns the number of workers from a given pool
func countTotalWorkers(pool *Pool) int {
totalWorkers := 0
pool.workers.Range(func(key interface{}, value interface{}) bool {
totalWorkers++
return true
})
return totalWorkers
}
// checkWorkersID checks that every worker has a different ID
func (suite *PoolTestSuite) checkWorkersID(pool *Pool) {
suite.Equal(pool.totalWorkers.GetValue(), countTotalWorkers(pool), "duplicated worker's ID")
}
// ***************************************************************************************
// ** AddWorker
// ***************************************************************************************
// AddWorker() with KillAllWorkers in progress
func (suite *PoolTestSuite) TestAddWorkerKillAllWorkersInProgress() {
suite.pool.setStatus(killAllWorkersInProgress, true)
err := suite.pool.AddWorker()
suite.Error(err, "Error expected if KillAllWorkers is in progress")
pErr, ok := err.(*PoolError)
suite.True(ok, "Expected error's type: *PoolError")
suite.Equal(ErrorKillAllWorkersInProgress, pErr.Code())
}
// AddWorker()
func (suite *PoolTestSuite) TestAddWorker() {
totalWorkers := countTotalWorkers(suite.pool)
totalAvailableWorkers := suite.pool.availableWorkers.GetLen()
// get current workers' IDs
workersIDs := getSyncMapKeys(suite.pool.workers)
// new worker channel
newWorkerChan := make(chan int, 2)
suite.pool.SetNewWorkerChan(newWorkerChan)
err := suite.pool.AddWorker()
suite.NoError(err)
// wait until the "new worker" notification arrives
select {
case <-newWorkerChan:
case <-time.After(5 * time.Second):
suite.FailNow("Too much time waiting for new worker")
}
// totalWorkers by workers map
suite.Equal(totalWorkers+1, countTotalWorkers(suite.pool), "same amount of workers as before AddWorker() was executed")
// totalWorkers
suite.Equal(totalWorkers+1, suite.pool.totalWorkers.GetValue())
// new worker into availableWorkers queue
suite.Equal(totalAvailableWorkers+1, suite.pool.availableWorkers.GetLen())
// get new worker
newWorkers := getSyncMapNewItems(suite.pool.workers, workersIDs)
// expected: only 1 new worker
suite.Equal(1, len(newWorkers), "only 1 new worker expected")
// check worker's type: *worker
newWorker, ok := newWorkers[0].(*worker)
suite.True(ok)
// check new worker's configuration
suite.checkWorkerConfiguration(newWorker)
}
// checkWorkerConfiguration checks the worker's configuration (based on *Pool.setupWorker)
func (suite *PoolTestSuite) checkWorkerConfiguration(wkr *worker) {
// external task successes
suite.NotNil(suite.pool.taskSuccesses, wkr.externalTaskSuccesses)
totalWorkersInProgress := suite.pool.GetTotalWorkersInProgress()
// worker's external preTask function
workerExternalPreTaskFunction := wkr.externalPreTaskFunc
suite.NotNil(workerExternalPreTaskFunction)
workerExternalPreTaskFunction()
suite.Equal(totalWorkersInProgress+1, suite.pool.GetTotalWorkersInProgress())
// update totalWorkerInProgress
totalWorkersInProgress = suite.pool.GetTotalWorkersInProgress()
// worker's external postTask function
workerExternalPostTaskFunction := wkr.externalPostTaskFunc
suite.NotNil(workerExternalPostTaskFunction)
workerExternalPostTaskFunction()
suite.Equal(totalWorkersInProgress-1, suite.pool.GetTotalWorkersInProgress())
// update totalWorkerInProgress
totalWorkersInProgress = suite.pool.GetTotalWorkersInProgress()
// worker's external preAction function
workerExternalPreActionFunction := wkr.externalPreActionFunc
suite.NotNil(workerExternalPreActionFunction)
workerExternalPreActionFunction()
suite.Equal(totalWorkersInProgress+1, suite.pool.GetTotalWorkersInProgress())
// update totalWorkerInProgress
totalWorkersInProgress = suite.pool.GetTotalWorkersInProgress()
// worker's external postAction function
workerExternalPostActionFunction := wkr.externalPostActionFunc
suite.NotNil(workerExternalPostActionFunction)
workerExternalPostActionFunction()
suite.Equal(totalWorkersInProgress-1, suite.pool.GetTotalWorkersInProgress())
}
// AddWorker() sending a newWorker signal over a channel without listener: it can't send the signal
func (suite *PoolTestSuite) TestAddWorkerFullNewWorkerChannel() {
// new worker channel
newWorkerChan := make(chan int)
suite.pool.SetNewWorkerChan(newWorkerChan)
// set log channel
logChan := make(chan PoolLog, 2)
suite.pool.SetLogChan(logChan)
err := suite.pool.AddWorker()
suite.NoError(err)
select {
case logData := <-logChan:
suite.Equal(logError, logData.Code)
pErr, ok := logData.Error.(*PoolError)
// custom error: *PoolError
suite.True(ok, "expected error's type: *PoolError")