Skip to content

Commit 0f02820

Browse files
committed
fix(backend:users): handle graceful shutdown in WebSocket gateway to prevent new connections during app termination
1 parent 336fce8 commit 0f02820

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

backend/src/applications/users/users.gateway.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* See the LICENSE file for licensing details
55
*/
66

7-
import { Logger } from '@nestjs/common'
7+
import { BeforeApplicationShutdown, Logger } from '@nestjs/common'
88
import {
99
MessageBody,
1010
OnGatewayConnection,
@@ -26,11 +26,12 @@ import { EventChangeOnlineStatus, EventUpdateOnlineStatus, UserOnline } from './
2626
import { UsersManager } from './services/users-manager.service'
2727

2828
@WebSocketGateway()
29-
export class WebSocketUsers implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
29+
export class WebSocketUsers implements BeforeApplicationShutdown, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
3030
@WebSocketServer() server: Server
3131
private readonly internalEventOnlineUsers = 'listOnlineUsers'
3232
private readonly logger = new Logger(WebSocketUsers.name)
3333
private initialized = false
34+
private shuttingDown = false
3435
private readonly waitTime: number = 3000 //ms
3536
// to show local rooms : this.server.of('/').adapter.rooms
3637

@@ -41,7 +42,12 @@ export class WebSocketUsers implements OnGatewayInit, OnGatewayConnection, OnGat
4142
setTimeout(() => (this.initialized = true), this.waitTime)
4243
}
4344

45+
beforeApplicationShutdown(_signal?: string) {
46+
this.shuttingDown = true
47+
}
48+
4449
async handleConnection(socket: AuthenticatedSocketIO): Promise<void> {
50+
if (this.shuttingDown) return
4551
socket.join(`${USER_ROOM_PREFIX}${socket.user.id}`)
4652
this.sendOnlineUser(socket.user, parseInt((socket.handshake.query.onlineStatus as string) || '0')).catch((e: Error) =>
4753
this.logger.error(`${this.handleConnection.name} - ${e}`)
@@ -53,6 +59,7 @@ export class WebSocketUsers implements OnGatewayInit, OnGatewayConnection, OnGat
5359
}
5460

5561
async handleDisconnect(socket: AuthenticatedSocketIO): Promise<void> {
62+
if (this.shuttingDown) return
5663
socket.leave(`${USER_ROOM_PREFIX}${socket.user.id}`)
5764
this.sendOfflineUser(socket.user.id).catch((e: Error) => this.logger.error(`${this.handleDisconnect.name} - ${e}`))
5865
this.logger.log(

0 commit comments

Comments
 (0)