refactor: refactor NotificationsHub to use hibernation api

- Updated NotificationsHub class to extend DurableObject.
- Persisted connection state into attachment instead of memory.
- Removed unnecessary ping functions & server-side periodic ping logic and added auto response which integrated into the WebSocket lifecycle.
- Added echo for binary ws messages (for keeplive of MessagePack).
- Added ping timer functionality in the App component to manage WebSocket connections more effectively.
This commit is contained in:
qaz741wsd856
2026-03-28 11:13:55 +08:00
committed by Shuai
parent 3bd4f6a9fe
commit 10707cf902
2 changed files with 105 additions and 117 deletions
+23 -2
View File
@@ -884,6 +884,15 @@ export default function App() {
return;
}
let pingTimer: number | null = null;
const clearPingTimer = () => {
if (pingTimer !== null) {
window.clearInterval(pingTimer);
pingTimer = null;
}
};
socket.addEventListener('open', () => {
reconnectAttempts = 0;
void refreshAuthorizedDevicesRef.current();
@@ -891,7 +900,16 @@ export default function App() {
socket?.send(`{"protocol":"json","version":1}${SIGNALR_RECORD_SEPARATOR}`);
} catch {
socket?.close();
return;
}
clearPingTimer();
pingTimer = window.setInterval(() => {
try {
socket?.send(`{"type":6}${SIGNALR_RECORD_SEPARATOR}`);
} catch {
// send failure will trigger close event
}
}, 15_000);
});
socket.addEventListener('message', (event) => {
@@ -934,6 +952,7 @@ export default function App() {
socket.addEventListener('close', () => {
socket = null;
clearPingTimer();
void refreshAuthorizedDevicesRef.current();
scheduleReconnect();
});
@@ -952,9 +971,11 @@ export default function App() {
return () => {
disposed = true;
clearReconnectTimer();
if (socket && socket.readyState === WebSocket.OPEN) {
if (socket) {
const s = socket;
socket = null;
try {
socket.close();
s.close();
} catch {
// ignore close races
}