Add room cleanup to remove empty sessions
This commit is contained in:
parent
2e370afe2c
commit
83dac38f29
2 changed files with 15 additions and 1 deletions
|
|
@ -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");
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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}`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue