@@ -13,6 +13,7 @@ import {
13
13
CompiledOptions ,
14
14
getUtilsAndReleasersFromOptions ,
15
15
Releasers ,
16
+ sleep ,
16
17
} from "./lib" ;
17
18
import { _runTaskList , runTaskListInternal } from "./main" ;
18
19
@@ -164,32 +165,37 @@ function buildRunner(input: {
164
165
} ) ;
165
166
166
167
let running = true ;
167
- const stop = async ( reason : string | null , itsFine = reason === null ) => {
168
+ const stop = (
169
+ reason : string | null ,
170
+ itsFine = reason === null ,
171
+ ) : Promise < void > => {
168
172
compiledOptions . logger [ itsFine ? "debug" : "warn" ] (
169
173
`Runner stopping${ reason ? ` (reason: ${ reason } )` : "" } ` ,
170
174
) ;
171
175
if ( running ) {
172
176
running = false ;
173
- events . emit ( "stop" , { ctx } ) ;
174
- try {
175
- const promises : Array < PromiseOrDirect < void > > = [ ] ;
176
- if ( cron . _active ) {
177
- promises . push ( cron . release ( ) ) ;
178
- }
179
- if ( workerPool . _active ) {
180
- promises . push ( workerPool . gracefulShutdown ( ) ) ;
181
- }
182
- await Promise . all ( promises ) . then ( release ) ;
183
- } catch ( error ) {
184
- logger . error (
185
- `Error occurred whilst attempting to release runner options: ${
186
- coerceError ( error ) . message
187
- } `,
188
- { error } ,
189
- ) ;
177
+ const promises : Array < PromiseOrDirect < void > > = [ ] ;
178
+ // Wrap in async IIFE to capture synchronous errors
179
+ promises . push ( ( async ( ) => void events . emit ( "stop" , { ctx } ) ) ( ) ) ;
180
+ if ( cron . _active ) {
181
+ promises . push ( ( async ( ) => cron . release ( ) ) ( ) ) ;
190
182
}
183
+ if ( workerPool . _active ) {
184
+ promises . push ( ( async ( ) => workerPool . gracefulShutdown ( ) ) ( ) ) ;
185
+ }
186
+ return Promise . all ( promises ) . then (
187
+ ( ) => release ( ) ,
188
+ ( error ) => {
189
+ logger . error (
190
+ `Error occurred whilst attempting to release runner options: ${
191
+ coerceError ( error ) . message
192
+ } `,
193
+ { error } ,
194
+ ) ;
195
+ } ,
196
+ ) ;
191
197
} else {
192
- throw new Error ( "Runner is already stopped" ) ;
198
+ return Promise . reject ( new Error ( "Runner is already stopped" ) ) ;
193
199
}
194
200
} ;
195
201
@@ -232,7 +238,14 @@ function buildRunner(input: {
232
238
stop ( `runner.kill() called${ reason ? `: ${ reason } ` : "" } ` ) . catch ( noop ) ;
233
239
}
234
240
if ( workerPool . _active ) {
235
- await workerPool . forcefulShutdown ( `Terminated through .kill() command` ) ;
241
+ // `stop()` will already have triggered gracefulShutdown, we'll
242
+ // go forceful after a short delay
243
+ await sleep ( 500 ) ;
244
+ if ( workerPool . _active ) {
245
+ await workerPool . forcefulShutdown (
246
+ `Terminated through .kill() command` ,
247
+ ) ;
248
+ }
236
249
}
237
250
} ,
238
251
addJob,
0 commit comments