@@ -13,6 +13,7 @@ import {
1313 CompiledOptions ,
1414 getUtilsAndReleasersFromOptions ,
1515 Releasers ,
16+ sleep ,
1617} from "./lib" ;
1718import { _runTaskList , runTaskListInternal } from "./main" ;
1819
@@ -164,32 +165,37 @@ function buildRunner(input: {
164165 } ) ;
165166
166167 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 > => {
168172 compiledOptions . logger [ itsFine ? "debug" : "warn" ] (
169173 `Runner stopping${ reason ? ` (reason: ${ reason } )` : "" } ` ,
170174 ) ;
171175 if ( running ) {
172176 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 ( ) ) ( ) ) ;
190182 }
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+ ) ;
191197 } else {
192- throw new Error ( "Runner is already stopped" ) ;
198+ return Promise . reject ( new Error ( "Runner is already stopped" ) ) ;
193199 }
194200 } ;
195201
@@ -232,7 +238,14 @@ function buildRunner(input: {
232238 stop ( `runner.kill() called${ reason ? `: ${ reason } ` : "" } ` ) . catch ( noop ) ;
233239 }
234240 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+ }
236249 }
237250 } ,
238251 addJob,
0 commit comments