@@ -24,6 +24,7 @@ export class ClusterService
2424 private serviceName : string
2525 private sessionId : string | null = null
2626 private consul ?: Consul
27+ private renewInterval ?: NodeJS . Timeout
2728
2829 constructor (
2930 private readonly config : ConfigService < {
@@ -122,7 +123,13 @@ export class ClusterService
122123 }
123124
124125 async beforeApplicationShutdown ( ) : Promise < void > {
126+ this . logger . log ( 'Shutting down cluster...' )
127+ if ( this . renewInterval ) {
128+ clearInterval ( this . renewInterval ) ;
129+ this . renewInterval = undefined ;
130+ }
125131 if ( this . consul && this . isLocalLeader ( ) && this . sessionId ) {
132+ this . logger . log ( 'Cleaning up leader locks...' )
126133 await this . consul . session . destroy ( this . sessionId )
127134 }
128135 }
@@ -135,11 +142,16 @@ export class ClusterService
135142 const { ID } = await this . consul . session . create ( {
136143 name : this . serviceId ,
137144 ttl : '15s' ,
145+ behavior : 'delete' ,
138146 } )
139147
140- setInterval ( ( ) => {
148+ this . renewInterval = setInterval ( async ( ) => {
141149 if ( this . consul ) {
142- this . consul . session . renew ( ID )
150+ try {
151+ await this . consul . session . renew ( ID )
152+ } catch ( error ) {
153+ this . logger . error ( 'Failed to renew consul session' , error )
154+ }
143155 }
144156 } , 10000 )
145157
@@ -156,7 +168,7 @@ export class ClusterService
156168 const result = await this . consul . kv . set ( {
157169 key : leaderKey ,
158170 value : this . serviceId ,
159- acquire : this . sessionId ,
171+ acquire : this . sessionId
160172 } )
161173
162174 this . isLeader = result
0 commit comments