@@ -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,36 @@ 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 = ( ) => this . _workerPromise = null ;
109+
110110 this . _workerPromise = promise ;
111111 this . _workerPromise
112- . then ( ( ) => this . _workerPromise = null )
113- . catch ( ( ) => this . _workerPromise = null ) ;
112+ . then ( nullWorkerPromise )
113+ . catch ( nullWorkerPromise ) ;
114114
115115 return promise ;
116116 }
117117
118- suspend ( ) {
119- console . warn ( 'Suspending worker' ) ;
120- this . killWorker ( ) ;
121- this . worker = null ;
118+ async suspend ( ) {
119+ console . debug ( 'Suspending worker' ) ;
120+ // To prevent async chaos, we should refrain from killing a worker that
121+ // we're in the process of creating.
122+ let promise = this . _workerPromise || Promise . resolve ( ) ;
123+ this . _killingWorkerPromise = promise . then ( ( ) => {
124+ let worker = this . worker ;
125+ this . worker = null ;
126+ this . killWorker ( worker ) ;
127+ this . _killingWorkerPromise = null ;
128+ } ) ;
129+ return this . _killingWorkerPromise ;
122130 }
123131
124- killWorker ( ) {
125- if ( ! this . worker || this . worker . exitCode ) { return ; }
126- this . worker . removeAllListeners ( ) ;
127- this . worker . kill ( ) ;
132+ killWorker ( worker ) {
133+ if ( ! worker || worker . exitCode ) { return ; }
134+ worker . removeAllListeners ( ) ;
135+ worker . kill ( ) ;
128136 }
129137
130138 ensureWorker ( ) {
@@ -170,8 +178,12 @@ class JobManager {
170178 }
171179
172180 async send ( bundle ) {
181+ if ( this . _killingWorkerPromise ) {
182+ console . debug ( 'Waiting for worker to be killed' ) ;
183+ await this . _killingWorkerPromise ;
184+ }
173185 if ( ! this . worker ) {
174- console . warn ( 'Creating worker' ) ;
186+ console . debug ( 'Creating worker' ) ;
175187 await this . createWorker ( ) ;
176188 }
177189
0 commit comments