@@ -2,6 +2,7 @@ const Promise = require('bluebird');
22const Chance = require ( 'chance' ) ;
33const _ = require ( 'lodash' ) ;
44const Base = require ( '../BaseJob' ) ;
5+ const { TASK_PRIORITY } = require ( '../../constants' ) ;
56const CreatePod = require ( './tasks/CreatePod.task' ) ;
67const DeletePod = require ( './tasks/DeletePod.task' ) ;
78const CreatePvc = require ( './tasks/CreatePvc.task' ) ;
@@ -12,33 +13,41 @@ const ERROR_MESSAGES = {
1213} ;
1314
1415class 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+
1528 run ( ) {
1629 return this . codefreshAPI . pullTasks ( this . logger )
1730 . catch ( ( err ) => {
1831 const message = `${ ERROR_MESSAGES . FAILED_TO_EXECUTE_TASK } with message: ${ err . message } ` ;
1932 this . logger . error ( message ) ;
2033 throw new Error ( message ) ;
2134 } )
22- . then ( ( res = [ ] ) => {
35+ . then ( async ( res = [ ] ) => {
2336 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 ) => {
3340 const type = _ . get ( task , 'type' ) ;
3441 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 } ;
3744 } )
38- . compact ( )
39- . flattenDeep ( )
45+ . filter ( ( { executor } ) => executor !== _ . noop )
46+ . sortBy ( ( { priority } ) => priority )
4047 . 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 ) ) ;
4251 } ) ;
4352 }
4453
@@ -57,5 +66,6 @@ class TaskPullerJob extends Base {
5766 return ;
5867 }
5968}
69+
6070TaskPullerJob . Errors = ERROR_MESSAGES ;
6171module . exports = TaskPullerJob ;
0 commit comments