Skip to content

Commit

Permalink
Clean up old connections and remove stringify for storage
Browse files Browse the repository at this point in the history
  • Loading branch information
third774 committed Aug 14, 2024
1 parent 5b5aef7 commit 07ccec2
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions app/durableObjects/ChatRoom.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class ChatRoom extends Server<Env> {
connection: Connection<User>,
ctx: ConnectionContext
): Promise<void> {
await this.cleanupOldConnections()
// let's start the periodic alarm if it's not already started
if (!(await this.ctx.storage.getAlarm())) {
// start the alarm to broadcast state every 30 seconds
Expand All @@ -72,7 +73,7 @@ export class ChatRoom extends Server<Env> {
}

// 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()
}
Expand Down Expand Up @@ -134,10 +135,7 @@ export class ChatRoom extends Server<Env> {
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
}
Expand Down Expand Up @@ -172,14 +170,13 @@ export class ChatRoom extends Server<Env> {
const otherUser = await this.ctx.storage.get<User>(
`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',
})
Expand Down Expand Up @@ -237,9 +234,19 @@ export class ChatRoom extends Server<Env> {
// this.broadcastState()
}

async cleanupOldConnections() {
const connections = [...this.getConnections()]
const sessionsToCleanUp = await this.ctx.storage.list<User>()
connections.forEach((connection) =>
sessionsToCleanUp.delete(`session-${connection.id}`)
)
return Promise.all(
[...sessionsToCleanUp.keys()].map((key) => this.ctx.storage.delete(key))
)
}

async alarm(): Promise<void> {
// 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)
Expand Down

0 comments on commit 07ccec2

Please sign in to comment.