Skip to content

Commit 511eb6a

Browse files
committed
PIX-41 Automatically unload empty lobbies from server memory and clean up client state on view unmount.
1 parent 01ccd3e commit 511eb6a

3 files changed

Lines changed: 34 additions & 1 deletion

File tree

server/src/services/canvas.service.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

server/src/sockets/index.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff 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
});

server/src/store/canvas.store.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff 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

5358
export const canvasStore = new CanvasStore();

0 commit comments

Comments
 (0)