@@ -102,6 +102,7 @@ export type ZodWorkerOptions<TMessageCatalog extends MessageCatalogSchema> = {
102102 recurringTasks ?: ZodRecurringTasks ;
103103 cleanup ?: ZodWorkerCleanupOptions ;
104104 reporter ?: ZodWorkerReporter ;
105+ shutdownTimeoutInMs ?: number ;
105106} ;
106107
107108export class ZodWorker < TMessageCatalog extends MessageCatalogSchema > {
@@ -114,6 +115,8 @@ export class ZodWorker<TMessageCatalog extends MessageCatalogSchema> {
114115 #runner?: GraphileRunner ;
115116 #cleanup: ZodWorkerCleanupOptions | undefined ;
116117 #reporter?: ZodWorkerReporter ;
118+ #shutdownTimeoutInMs?: number ;
119+ #shuttingDown = false ;
117120
118121 constructor ( options : ZodWorkerOptions < TMessageCatalog > ) {
119122 this . #name = options . name ;
@@ -124,6 +127,7 @@ export class ZodWorker<TMessageCatalog extends MessageCatalogSchema> {
124127 this . #recurringTasks = options . recurringTasks ;
125128 this . #cleanup = options . cleanup ;
126129 this . #reporter = options . reporter ;
130+ this . #shutdownTimeoutInMs = options . shutdownTimeoutInMs ?? 60000 ; // default to 60 seconds
127131 }
128132
129133 get graphileWorkerSchema ( ) {
@@ -143,6 +147,7 @@ export class ZodWorker<TMessageCatalog extends MessageCatalogSchema> {
143147
144148 this . #runner = await graphileRun ( {
145149 ...this . #runnerOptions,
150+ noHandleSignals : true ,
146151 taskList : this . #createTaskListFromTasks( ) ,
147152 parsedCronItems,
148153 } ) ;
@@ -199,9 +204,36 @@ export class ZodWorker<TMessageCatalog extends MessageCatalogSchema> {
199204 this . #logDebug( "stop" ) ;
200205 } ) ;
201206
207+ process . on ( "SIGTERM" , this . _handleSignal ( "SIGTERM" ) . bind ( this ) ) ;
208+ process . on ( "SIGINT" , this . _handleSignal ( "SIGINT" ) . bind ( this ) ) ;
209+
202210 return true ;
203211 }
204212
213+ private _handleSignal ( signal : string ) {
214+ return ( ) => {
215+ if ( this . #shuttingDown) {
216+ return ;
217+ }
218+
219+ this . #shuttingDown = true ;
220+
221+ if ( this . #shutdownTimeoutInMs) {
222+ setTimeout ( ( ) => {
223+ this . #logDebug( "Shutdown timeout reached, exiting process" ) ;
224+
225+ process . exit ( 0 ) ;
226+ } , this . #shutdownTimeoutInMs) ;
227+ }
228+
229+ this . #logDebug( `Received ${ signal } , shutting down zodWorker...` ) ;
230+
231+ this . stop ( ) . finally ( ( ) => {
232+ this . #logDebug( "zodWorker stopped" ) ;
233+ } ) ;
234+ } ;
235+ }
236+
205237 public async stop ( ) {
206238 await this . #runner?. stop ( ) ;
207239 }
0 commit comments