Fix client identity tracking to prevent memory leak
This commit is contained in:
parent
3cf16586aa
commit
925c7a3c0d
1 changed files with 10 additions and 5 deletions
15
src/index.ts
15
src/index.ts
|
|
@ -8,7 +8,7 @@ Bun.serve({
|
|||
fetch(req, server) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/ws") {
|
||||
const upgraded = server.upgrade(req, { data: { room: null } });
|
||||
const upgraded = server.upgrade(req, { data: { room: null, client: null } });
|
||||
if (!upgraded) {
|
||||
return new Response("websocket upgrade failed", { status: 400 });
|
||||
}
|
||||
|
|
@ -17,14 +17,19 @@ Bun.serve({
|
|||
return new Response("collabd running");
|
||||
},
|
||||
websocket: {
|
||||
open() {
|
||||
open(ws) {
|
||||
// create client object once and store in ws.data
|
||||
const client: Client = { ws };
|
||||
ws.data.client = client;
|
||||
console.debug("client connected");
|
||||
},
|
||||
message(ws, raw) {
|
||||
const msg = decode(raw.toString());
|
||||
if (!msg) return;
|
||||
|
||||
const client: Client = { ws };
|
||||
// reuse the client object from ws.data
|
||||
const client = ws.data.client;
|
||||
if (!client) return;
|
||||
|
||||
switch (msg.type) {
|
||||
case "join": {
|
||||
|
|
@ -52,9 +57,9 @@ Bun.serve({
|
|||
}
|
||||
},
|
||||
close(ws) {
|
||||
if (ws.data.room) {
|
||||
if (ws.data.room && ws.data.client) {
|
||||
const session = getSession(ws.data.room);
|
||||
session?.leave({ ws });
|
||||
session?.leave(ws.data.client);
|
||||
}
|
||||
console.debug("client disconnected");
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in a new issue