@@ -57,7 +57,11 @@ class JobManager {
5757
5858 let nodeBin = Config . get ( 'nodeBin' ) ;
5959 console . debug ( 'JobManager creating worker at:' , nodeBin ) ;
60- this . killWorker ( ) ;
60+
61+ // TODO: Figure out if this can even happen anymore.
62+ if ( this . worker ) {
63+ this . killWorker ( this . worker ) ;
64+ }
6165
6266 // We choose to do a sync test here because this method is much easier to
6367 // reason about without an `await` keyword introducing side effects.
@@ -99,32 +103,37 @@ class JobManager {
99103 this . worker . stderr
100104 . pipe ( ndjson . parse ( ) )
101105 . on ( 'data' , this . receiveError . bind ( this ) ) ;
102-
103- this . worker . on ( 'close' , ( ) => {
104- if ( this . worker . killed === false ) {
105- this . createWorker ( ) ;
106- }
107- } ) ;
108106 } ) ;
109107
108+ let nullWorkerPromise = ( ) => {
109+ this . _workerPromise = null ;
110+ } ;
111+
110112 this . _workerPromise = promise ;
111113 this . _workerPromise
112- . then ( ( ) => this . _workerPromise = null )
113- . catch ( ( ) => this . _workerPromise = null ) ;
114+ . then ( nullWorkerPromise )
115+ . catch ( nullWorkerPromise ) ;
114116
115117 return promise ;
116118 }
117119
118- suspend ( ) {
119- console . warn ( 'Suspending worker' ) ;
120- this . killWorker ( ) ;
121- this . worker = null ;
120+ async suspend ( ) {
121+ console . debug ( 'Suspending worker' ) ;
122+ // To prevent async chaos, we should refrain from killing a worker that we're in the process of
123+ let promise = this . _workerPromise || Promise . resolve ( ) ;
124+ this . _killingWorkerPromise = promise . then ( ( ) => {
125+ let worker = this . worker ;
126+ this . worker = null ;
127+ this . killWorker ( worker ) ;
128+ this . _killingWorkerPromise = null ;
129+ } ) ;
130+ return this . _killingWorkerPromise ;
122131 }
123132
124- killWorker ( ) {
125- if ( ! this . worker || this . worker . exitCode ) { return ; }
126- this . worker . removeAllListeners ( ) ;
127- this . worker . kill ( ) ;
133+ killWorker ( worker ) {
134+ if ( ! worker || worker . exitCode ) { return ; }
135+ worker . removeAllListeners ( ) ;
136+ worker . kill ( ) ;
128137 }
129138
130139 ensureWorker ( ) {
@@ -170,8 +179,12 @@ class JobManager {
170179 }
171180
172181 async send ( bundle ) {
182+ if ( this . _killingWorkerPromise ) {
183+ console . debug ( 'Waiting for worker to be killed' ) ;
184+ await this . _killingWorkerPromise ;
185+ }
173186 if ( ! this . worker ) {
174- console . warn ( 'Creating worker' ) ;
187+ console . debug ( 'Creating worker' ) ;
175188 await this . createWorker ( ) ;
176189 }
177190
0 commit comments