From 83dac38f293dae9b619c1c2c0ff3b9bbe1fa6b4d Mon Sep 17 00:00:00 2001 From: Jared Miller Date: Tue, 27 Jan 2026 16:19:41 -0500 Subject: [PATCH] Add room cleanup to remove empty sessions --- src/index.ts | 4 +++- src/session.ts | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 926813e..a7338c1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ 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; @@ -43,6 +43,7 @@ Bun.serve({ if (ws.data.room) { const session = getSession(ws.data.room); session?.leave(client); + removeSession(ws.data.room); ws.data.room = null; } break; @@ -60,6 +61,7 @@ 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 dbde65b..76b244a 100644 --- a/src/session.ts +++ b/src/session.ts @@ -27,6 +27,10 @@ export class Session { this.broadcastPeerCount(); } + isEmpty(): boolean { + return this.clients.size === 0; + } + applyUpdate(update: Uint8Array, from: Client) { try { Y.applyUpdate(this.doc, update); @@ -71,3 +75,11 @@ export function getOrCreateSession(name: string): Session { export function getSession(name: string): Session | undefined { 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}`); + } +}