File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -90,4 +90,23 @@ export class CanvasService {
9090
9191 console . log ( `[CanvasService] Saved lobby '${ lobbyName } ' to DB` ) ;
9292 }
93+
94+ // Unloads a lobby from memory, persisting it first
95+ static async unloadLobby ( lobbyName : string ) {
96+ if ( ! canvasStore . isLobbyInMemory ( lobbyName ) ) return ;
97+
98+ console . log ( `[CanvasService] Unloading idle lobby: ${ lobbyName } ` ) ;
99+
100+ // If there's a pending save timer, cancel it and save immediately
101+ if ( this . saveTimers . has ( lobbyName ) ) {
102+ clearTimeout ( this . saveTimers . get ( lobbyName ) ) ;
103+ this . saveTimers . delete ( lobbyName ) ;
104+ }
105+
106+ // Force strict save
107+ await this . saveToDB ( lobbyName ) ;
108+
109+ // Remove from memory
110+ canvasStore . removeLobby ( lobbyName ) ;
111+ }
93112}
Original file line number Diff line number Diff line change @@ -111,11 +111,20 @@ export const setupSocket = (io: Server) => {
111111
112112
113113 // --- DISCONNECTING ---
114- socket . on ( 'disconnecting' , ( ) => {
114+ socket . on ( 'disconnecting' , async ( ) => {
115115 // Notify rooms that user is leaving
116116 for ( const room of socket . rooms ) {
117117 if ( room !== socket . id ) {
118118 socket . to ( room ) . emit ( CONFIG . EVENTS . SERVER . USER_LEFT , ( socket as AuthenticatedSocket ) . user ) ;
119+
120+ // Check if room is empty (excluding this socket)
121+ const socketsInRoom = await io . in ( room ) . fetchSockets ( ) ;
122+ const remainingUsers = socketsInRoom . length - 1 ; // fetchSockets includes the disconnecting socket
123+
124+ if ( remainingUsers <= 0 ) {
125+ // Room is empty, unload from hot storage
126+ await CanvasService . unloadLobby ( room ) ;
127+ }
119128 }
120129 }
121130 } ) ;
Original file line number Diff line number Diff line change @@ -48,6 +48,11 @@ export class CanvasStore {
4848 public getInMemoryLobbyIds ( ) : string [ ] {
4949 return Array . from ( this . lobbies . keys ( ) ) ;
5050 }
51+
52+ public removeLobby ( lobbyName : string ) : boolean {
53+ console . log ( `[CanvasStore] Removing lobby from memory: ${ lobbyName } ` ) ;
54+ return this . lobbies . delete ( lobbyName ) ;
55+ }
5156}
5257
5358export const canvasStore = new CanvasStore ( ) ;
You can’t perform that action at this time.
0 commit comments