@@ -2,6 +2,7 @@ const Promise = require('bluebird');
2
2
const Chance = require ( 'chance' ) ;
3
3
const _ = require ( 'lodash' ) ;
4
4
const Base = require ( '../BaseJob' ) ;
5
+ const { TASK_PRIORITY } = require ( '../../constants' ) ;
5
6
const CreatePod = require ( './tasks/CreatePod.task' ) ;
6
7
const DeletePod = require ( './tasks/DeletePod.task' ) ;
7
8
const CreatePvc = require ( './tasks/CreatePvc.task' ) ;
@@ -12,33 +13,41 @@ const ERROR_MESSAGES = {
12
13
} ;
13
14
14
15
class TaskPullerJob extends Base {
16
+ constructor ( ...args ) {
17
+ super ( ...args ) ;
18
+
19
+ this . typeToTaskMap = {
20
+ 'CreatePod' : { executor : this . _executeTask ( CreatePod ) , priority : CreatePod . priority } ,
21
+ 'DeletePod' : { executor : this . _executeTask ( DeletePod ) , priority : DeletePod . priority } ,
22
+ 'CreatePvc' : { executor : this . _executeTask ( CreatePvc ) , priority : CreatePvc . priority } ,
23
+ 'DeletePvc' : { executor : this . _executeTask ( DeletePvc ) , priority : DeletePvc . priority } ,
24
+ 'NOOP' : { executor : _ . noop , priority : TASK_PRIORITY . LOW } ,
25
+ } ;
26
+ }
27
+
15
28
run ( ) {
16
29
return this . codefreshAPI . pullTasks ( this . logger )
17
30
. catch ( ( err ) => {
18
31
const message = `${ ERROR_MESSAGES . FAILED_TO_EXECUTE_TASK } with message: ${ err . message } ` ;
19
32
this . logger . error ( message ) ;
20
33
throw new Error ( message ) ;
21
34
} )
22
- . then ( ( res = [ ] ) => {
35
+ . then ( async ( res = [ ] ) => {
23
36
this . logger . info ( `Got ${ res . length } tasks` ) ;
24
- const promises = _ . chain ( res )
25
- . map ( ( task ) => {
26
- // TODO auto load all tasks
27
- const typeToTaskMap = {
28
- 'CreatePod' : this . _executeTask ( CreatePod ) ,
29
- 'DeletePod' : this . _executeTask ( DeletePod ) ,
30
- 'CreatePvc' : this . _executeTask ( CreatePvc ) ,
31
- 'DeletePvc' : this . _executeTask ( DeletePvc ) ,
32
- } ;
37
+
38
+ const tasks = _ . chain ( res )
39
+ . map ( ( task ) => {
33
40
const type = _ . get ( task , 'type' ) ;
34
41
this . logger . info ( `Got request to run task with type: ${ type } ` ) ;
35
- const fn = typeToTaskMap [ type ] || _ . noop ;
36
- return fn ( task ) ;
42
+ const { executor , priority } = _ . get ( this . typeToTaskMap , type , this . typeToTaskMap . NOOP ) ;
43
+ return { task, priority , executor } ;
37
44
} )
38
- . compact ( )
39
- . flattenDeep ( )
45
+ . filter ( ( { executor } ) => executor !== _ . noop )
46
+ . sortBy ( ( { priority } ) => priority )
40
47
. value ( ) ;
41
- return Promise . all ( promises ) ;
48
+
49
+ // resolves each promise sequentially, in sorted order
50
+ return await Promise . mapSeries ( tasks , ( { task, executor } ) => executor ( task ) ) ;
42
51
} ) ;
43
52
}
44
53
@@ -57,5 +66,6 @@ class TaskPullerJob extends Base {
57
66
return ;
58
67
}
59
68
}
69
+
60
70
TaskPullerJob . Errors = ERROR_MESSAGES ;
61
71
module . exports = TaskPullerJob ;
0 commit comments