|
| 1 | +/* |
| 2 | + * Copyright (C) 2023-2025 XMOJ-bbs contributors |
| 3 | + * This file is part of XMOJ-bbs. |
| 4 | + * XMOJ-bbs is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU Affero General Public License as published by |
| 6 | + * the Free Software Foundation, either version 3 of the License, or |
| 7 | + * (at your option) any later version. |
| 8 | + * |
| 9 | + * XMOJ-bbs is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU Affero General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU Affero General Public License |
| 15 | + * along with XMOJ-bbs. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * Durable Object used to manage notification WebSocket sessions per user. |
| 20 | + * |
| 21 | + * This implementation uses the WebSocket Hibernation API via |
| 22 | + * `state.acceptWebSocket(...)` so idle websocket connections do not keep the DO |
| 23 | + * actively running. |
| 24 | + */ |
| 25 | +interface NotificationAttachment { |
| 26 | + userId: string; |
| 27 | + connectedAt: number; |
| 28 | +} |
| 29 | + |
| 30 | +interface HibernationWebSocket extends WebSocket { |
| 31 | + serializeAttachment: (value: NotificationAttachment) => void; |
| 32 | + deserializeAttachment: () => NotificationAttachment | null; |
| 33 | +} |
| 34 | + |
| 35 | +interface NotificationEnvironment { |
| 36 | + NOTIFICATION_PUSH_TOKEN?: string; |
| 37 | +} |
| 38 | + |
| 39 | +export class NotificationManager { |
| 40 | + private readonly state: DurableObjectState; |
| 41 | + private readonly sessions: Map<string, Set<WebSocket>>; |
| 42 | + private readonly pushToken: string; |
| 43 | + private static readonly MAX_SESSIONS_PER_USER = 20; |
| 44 | + |
| 45 | + constructor(state: DurableObjectState, env: NotificationEnvironment) { |
| 46 | + this.state = state; |
| 47 | + this.sessions = new Map<string, Set<WebSocket>>(); |
| 48 | + this.pushToken = env.NOTIFICATION_PUSH_TOKEN || ""; |
| 49 | + // `state.getWebSockets()` is synchronous in the current Cloudflare runtime. |
| 50 | + this.rebuildSessionIndex(); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Rebuild in-memory session index from hibernated sockets on cold start. |
| 55 | + */ |
| 56 | + private rebuildSessionIndex(): void { |
| 57 | + for (const websocket of this.state.getWebSockets()) { |
| 58 | + const userId = this.getSocketUserId(websocket); |
| 59 | + if (!userId) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + this.addSession(userId, websocket); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Store a socket in the per-user set (supports multi-tab / multi-device). |
| 68 | + * |
| 69 | + * To avoid abuse, each user is capped at MAX_SESSIONS_PER_USER sockets. When |
| 70 | + * exceeded, the oldest socket is closed and removed. |
| 71 | + */ |
| 72 | + private addSession(userId: string, websocket: WebSocket): void { |
| 73 | + let userSessions = this.sessions.get(userId); |
| 74 | + if (!userSessions) { |
| 75 | + userSessions = new Set<WebSocket>(); |
| 76 | + this.sessions.set(userId, userSessions); |
| 77 | + } |
| 78 | + |
| 79 | + userSessions.add(websocket); |
| 80 | + while (userSessions.size > NotificationManager.MAX_SESSIONS_PER_USER) { |
| 81 | + const oldestSession = userSessions.values().next().value as WebSocket | undefined; |
| 82 | + if (!oldestSession) { |
| 83 | + break; |
| 84 | + } |
| 85 | + this.removeSession(userId, oldestSession); |
| 86 | + try { |
| 87 | + oldestSession.close(1008, "Too many websocket sessions"); |
| 88 | + } catch (_) { |
| 89 | + // Best effort close. |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * Remove a socket from the in-memory index and cleanup empty user entries. |
| 96 | + */ |
| 97 | + private removeSession(userId: string, websocket: WebSocket): void { |
| 98 | + const userSessions = this.sessions.get(userId); |
| 99 | + if (!userSessions) { |
| 100 | + return; |
| 101 | + } |
| 102 | + |
| 103 | + userSessions.delete(websocket); |
| 104 | + if (userSessions.size === 0) { |
| 105 | + this.sessions.delete(userId); |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Read the socket's bound user ID from hibernation attachment metadata. |
| 111 | + */ |
| 112 | + private getSocketUserId(websocket: WebSocket): string { |
| 113 | + try { |
| 114 | + const attachment = (websocket as HibernationWebSocket).deserializeAttachment(); |
| 115 | + if (attachment && attachment.userId !== "") { |
| 116 | + return attachment.userId; |
| 117 | + } |
| 118 | + } catch (_) { |
| 119 | + // Ignore attachment parse failures and treat socket as anonymous. |
| 120 | + } |
| 121 | + return ""; |
| 122 | + } |
| 123 | + |
| 124 | + async fetch(request: Request): Promise<Response> { |
| 125 | + const url = new URL(request.url); |
| 126 | + |
| 127 | + // Internal push channel from Process.ts. |
| 128 | + if (url.pathname === "/notify") { |
| 129 | + if (this.pushToken === "" || request.headers.get("X-Notification-Token") !== this.pushToken) { |
| 130 | + return new Response("Unauthorized", {status: 401}); |
| 131 | + } |
| 132 | + |
| 133 | + const body = await request.json() as { userId: string; notification: object }; |
| 134 | + const userSessions = this.sessions.get(body.userId); |
| 135 | + if (userSessions) { |
| 136 | + const payload = JSON.stringify(body.notification); |
| 137 | + for (const websocket of userSessions) { |
| 138 | + if (websocket.readyState === 1) { |
| 139 | + websocket.send(payload); |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + return new Response("OK"); |
| 144 | + } |
| 145 | + |
| 146 | + const upgradeHeader = request.headers.get("Upgrade"); |
| 147 | + if (upgradeHeader !== "websocket") { |
| 148 | + return new Response("Expected WebSocket", {status: 426}); |
| 149 | + } |
| 150 | + |
| 151 | + const userId = url.searchParams.get("userId"); |
| 152 | + if (!userId) { |
| 153 | + return new Response("Missing userId", {status: 400}); |
| 154 | + } |
| 155 | + |
| 156 | + const pair = new WebSocketPair(); |
| 157 | + const [client, server] = Object.values(pair); |
| 158 | + |
| 159 | + // Hibernation API: allow DO to sleep while websocket is idle. |
| 160 | + this.state.acceptWebSocket(server); |
| 161 | + (server as HibernationWebSocket).serializeAttachment({ |
| 162 | + userId, |
| 163 | + connectedAt: Date.now() |
| 164 | + }); |
| 165 | + this.addSession(userId, server); |
| 166 | + |
| 167 | + server.send(JSON.stringify({ |
| 168 | + type: "connected", |
| 169 | + timestamp: Date.now() |
| 170 | + })); |
| 171 | + |
| 172 | + return new Response(null, {status: 101, webSocket: client}); |
| 173 | + } |
| 174 | + |
| 175 | + webSocketMessage(websocket: WebSocket, message: string | ArrayBuffer): void { |
| 176 | + try { |
| 177 | + const parsedMessage = JSON.parse(typeof message === "string" ? message : new TextDecoder().decode(message)); |
| 178 | + if (parsedMessage.type === "ping") { |
| 179 | + websocket.send(JSON.stringify({type: "pong"})); |
| 180 | + } |
| 181 | + } catch (_) { |
| 182 | + // Ignore malformed client messages to keep the connection alive. |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + webSocketClose(websocket: WebSocket): void { |
| 187 | + const userId = this.getSocketUserId(websocket); |
| 188 | + if (userId !== "") { |
| 189 | + this.removeSession(userId, websocket); |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + webSocketError(websocket: WebSocket): void { |
| 194 | + const userId = this.getSocketUserId(websocket); |
| 195 | + if (userId !== "") { |
| 196 | + this.removeSession(userId, websocket); |
| 197 | + } |
| 198 | + |
| 199 | + try { |
| 200 | + websocket.close(1011, "Socket error"); |
| 201 | + } catch (_) { |
| 202 | + // Socket may already be closed by runtime/client. |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments