Skip to content

Commit 5aa20e5

Browse files
committed
Store sessions strongly
1 parent d64af95 commit 5aa20e5

1 file changed

Lines changed: 23 additions & 6 deletions

File tree

web/src/index.ts

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,26 @@ export class QueueDO extends DurableObject<Env> {
574574
"dev": 2,
575575
};
576576

577+
ctx.blockConcurrencyWhile(async () => {
578+
const stored = await ctx.storage.list<{ type: string; ip: string }>({ prefix: "session:" });
579+
for (const [key, value] of stored) {
580+
const sessionId = key.slice("session:".length);
581+
this.activeSessions.set(sessionId, value.type);
582+
this.sessionIPs.set(sessionId, value.ip);
583+
}
584+
});
585+
}
586+
587+
private async persistSession(sessionId: string, type: string, ip: string) {
588+
this.activeSessions.set(sessionId, type);
589+
this.sessionIPs.set(sessionId, ip);
590+
await this.ctx.storage.put(`session:${sessionId}`, { type, ip });
591+
}
592+
593+
private async removeSession(sessionId: string) {
594+
this.activeSessions.delete(sessionId);
595+
this.sessionIPs.delete(sessionId);
596+
await this.ctx.storage.delete(`session:${sessionId}`);
577597
}
578598

579599
activeSessionCountForIP(ip: string): number {
@@ -648,8 +668,7 @@ export class QueueDO extends DurableObject<Env> {
648668

649669
if (this.hasCapacity(sessionType)) {
650670
const sessionId = crypto.randomUUID();
651-
this.activeSessions.set(sessionId, sessionType);
652-
this.sessionIPs.set(sessionId, clientIP);
671+
await this.persistSession(sessionId, sessionType, clientIP);
653672
return new Response(JSON.stringify({ status: "READY", sessionId }), { headers: { "Content-Type": "application/json" }, });
654673
} else {
655674
const ticketId = crypto.randomUUID();
@@ -726,16 +745,14 @@ export class QueueDO extends DurableObject<Env> {
726745
if (url.pathname === "/api/session-closed") {
727746
const { sessionId } = await request.json<{sessionId: string}>();
728747
const closedType = this.activeSessions.get(sessionId);
729-
this.activeSessions.delete(sessionId);
730-
this.sessionIPs.delete(sessionId);
748+
await this.removeSession(sessionId);
731749

732750
if (closedType) {
733751
const idx = this.waitingQueue.findIndex(w => w.sessionType === closedType);
734752
if (idx !== -1) {
735753
const nextInLine = this.waitingQueue.splice(idx, 1)[0];
736754
const newSessionId = crypto.randomUUID();
737-
this.activeSessions.set(newSessionId, nextInLine.sessionType);
738-
this.sessionIPs.set(newSessionId, nextInLine.ip);
755+
await this.persistSession(newSessionId, nextInLine.sessionType, nextInLine.ip);
739756
nextInLine.resolve(newSessionId);
740757
}
741758
}

0 commit comments

Comments
 (0)