Add room cleanup to remove empty sessions

This commit is contained in:
Jared Miller 2026-01-27 16:19:41 -05:00
parent 2e370afe2c
commit 83dac38f29
Signed by: shmup
GPG key ID: 22B5C6D66A38B06C
2 changed files with 15 additions and 1 deletions

View file

@ -1,5 +1,5 @@
import { decode } from "./protocol"; import { decode } from "./protocol";
import { type Client, getOrCreateSession, getSession } from "./session"; import { type Client, getOrCreateSession, getSession, removeSession } from "./session";
const PORT = Number(process.env.PORT) || 4040; const PORT = Number(process.env.PORT) || 4040;
@ -43,6 +43,7 @@ Bun.serve({
if (ws.data.room) { if (ws.data.room) {
const session = getSession(ws.data.room); const session = getSession(ws.data.room);
session?.leave(client); session?.leave(client);
removeSession(ws.data.room);
ws.data.room = null; ws.data.room = null;
} }
break; break;
@ -60,6 +61,7 @@ Bun.serve({
if (ws.data.room && ws.data.client) { if (ws.data.room && ws.data.client) {
const session = getSession(ws.data.room); const session = getSession(ws.data.room);
session?.leave(ws.data.client); session?.leave(ws.data.client);
removeSession(ws.data.room);
} }
console.debug("client disconnected"); console.debug("client disconnected");
}, },

View file

@ -27,6 +27,10 @@ export class Session {
this.broadcastPeerCount(); this.broadcastPeerCount();
} }
isEmpty(): boolean {
return this.clients.size === 0;
}
applyUpdate(update: Uint8Array, from: Client) { applyUpdate(update: Uint8Array, from: Client) {
try { try {
Y.applyUpdate(this.doc, update); Y.applyUpdate(this.doc, update);
@ -71,3 +75,11 @@ export function getOrCreateSession(name: string): Session {
export function getSession(name: string): Session | undefined { export function getSession(name: string): Session | undefined {
return sessions.get(name); return sessions.get(name);
} }
export function removeSession(name: string): void {
const session = sessions.get(name);
if (session?.isEmpty()) {
sessions.delete(name);
console.debug(`session removed: ${name}`);
}
}