From 70efa1d0290f5b43d2fd851c4306a9cdb2f77c6a Mon Sep 17 00:00:00 2001 From: Kevin Kipp Date: Wed, 14 Aug 2024 16:49:06 -0500 Subject: [PATCH] Clean up old connections and remove stringify for storage --- app/durableObjects/ChatRoom.server.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/app/durableObjects/ChatRoom.server.ts b/app/durableObjects/ChatRoom.server.ts index 8c468b33..1cbe6190 100644 --- a/app/durableObjects/ChatRoom.server.ts +++ b/app/durableObjects/ChatRoom.server.ts @@ -72,7 +72,7 @@ export class ChatRoom extends Server { } // store the user's data in storage - await this.ctx.storage.put(`session-${connection.id}`, JSON.stringify(user)) + await this.ctx.storage.put(`session-${connection.id}`, user) await this.broadcastRoomState() } @@ -134,10 +134,7 @@ export class ChatRoom extends Server { break } case 'userUpdate': { - this.ctx.storage.put( - `session-${connection.id}`, - JSON.stringify(data.user) - ) + this.ctx.storage.put(`session-${connection.id}`, data.user) await this.broadcastRoomState() break } @@ -172,14 +169,13 @@ export class ChatRoom extends Server { const otherUser = await this.ctx.storage.get( `session-${data.id}` ) - this.ctx.storage.put(`session-${data.id}`, { + await this.ctx.storage.put(`session-${data.id}`, { ...otherUser!, tracks: { ...otherUser!.tracks, audioEnabled: false, }, }) - // this.sendMessage(otherConnection, { type: 'muteMic', }) @@ -237,9 +233,17 @@ export class ChatRoom extends Server { // this.broadcastState() } + async cleanupOldConnections() { + const connections = [...this.getConnections()] + const sessionsToCleanUp = await this.ctx.storage.list() + connections.forEach((connection) => + sessionsToCleanUp.delete(`session-${connection.id}`) + ) + return this.ctx.storage.delete([...sessionsToCleanUp.keys()]) + } + async alarm(): Promise { - // technically we don't need to broadcast state on an alarm, - // but let's keep it for a while and see if it's useful + await this.cleanupOldConnections() await this.broadcastRoomState() if ([...this.getConnections()].length !== 0) { this.ctx.storage.setAlarm(Date.now() + 30000)