From 8ce1e098e6458e85d7bb731d9b05629f34cb7d3c Mon Sep 17 00:00:00 2001 From: Jared Miller Date: Tue, 27 Jan 2026 17:59:49 -0500 Subject: [PATCH] Make session cleanup atomic in leave() --- src/index.ts | 9 +-------- src/session.ts | 4 ++++ 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/index.ts b/src/index.ts index 6991854..1e408ee 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,5 @@ import { decode } from "./protocol"; -import { - type Client, - getOrCreateSession, - getSession, - removeSession, -} from "./session"; +import { type Client, getOrCreateSession, getSession } from "./session"; const PORT = Number(process.env.PORT) || 4040; @@ -66,7 +61,6 @@ Bun.serve({ if (ws.data.room) { const session = getSession(ws.data.room); session?.leave(client); - removeSession(ws.data.room); ws.data.room = null; } break; @@ -84,7 +78,6 @@ Bun.serve({ if (ws.data.room && ws.data.client) { const session = getSession(ws.data.room); session?.leave(ws.data.client); - removeSession(ws.data.room); } console.debug("client disconnected"); }, diff --git a/src/session.ts b/src/session.ts index 26b555d..6b316eb 100644 --- a/src/session.ts +++ b/src/session.ts @@ -31,6 +31,10 @@ export class Session { leave(client: Client) { this.clients.delete(client); this.broadcastPeerCount(); + if (this.isEmpty()) { + sessions.delete(this.name); + console.debug(`session removed: ${this.name}`); + } } isEmpty(): boolean {