Initial commit - realms platform
This commit is contained in:
parent
c590ab6d18
commit
c717c3751c
234 changed files with 74103 additions and 15231 deletions
|
|
@ -1,8 +1,25 @@
|
|||
let ws = null;
|
||||
let reconnectTimeout = null;
|
||||
let reconnectAttempts = 0;
|
||||
const MAX_RECONNECT_ATTEMPTS = 10;
|
||||
const BASE_RECONNECT_DELAY = 1000; // 1 second
|
||||
const MAX_RECONNECT_DELAY = 30000; // 30 seconds
|
||||
|
||||
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost/ws';
|
||||
|
||||
/**
|
||||
* Calculate exponential backoff delay with jitter
|
||||
* @returns {number} Delay in milliseconds
|
||||
*/
|
||||
function getReconnectDelay() {
|
||||
// Exponential backoff: 1s, 2s, 4s, 8s, 16s, 30s, 30s...
|
||||
const exponentialDelay = BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts);
|
||||
const cappedDelay = Math.min(exponentialDelay, MAX_RECONNECT_DELAY);
|
||||
// Add random jitter (±20%) to prevent thundering herd
|
||||
const jitter = cappedDelay * 0.2 * (Math.random() - 0.5);
|
||||
return Math.floor(cappedDelay + jitter);
|
||||
}
|
||||
|
||||
export function connectWebSocket(onMessage) {
|
||||
if (ws?.readyState === WebSocket.OPEN) return;
|
||||
|
||||
|
|
@ -12,6 +29,7 @@ export function connectWebSocket(onMessage) {
|
|||
|
||||
ws.onopen = () => {
|
||||
console.log('WebSocket connected');
|
||||
reconnectAttempts = 0; // Reset on successful connection
|
||||
ws?.send(JSON.stringify({ type: 'subscribe' }));
|
||||
};
|
||||
|
||||
|
|
@ -30,10 +48,19 @@ export function connectWebSocket(onMessage) {
|
|||
|
||||
ws.onclose = () => {
|
||||
console.log('WebSocket disconnected');
|
||||
// Reconnect after 5 seconds
|
||||
|
||||
if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
|
||||
console.error('Max reconnect attempts reached, giving up');
|
||||
return;
|
||||
}
|
||||
|
||||
const delay = getReconnectDelay();
|
||||
reconnectAttempts++;
|
||||
|
||||
console.log(`Reconnecting in ${delay}ms (attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
|
||||
reconnectTimeout = setTimeout(() => {
|
||||
connectWebSocket(onMessage);
|
||||
}, 5000);
|
||||
}, delay);
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -47,6 +74,15 @@ export function disconnectWebSocket() {
|
|||
ws.close();
|
||||
ws = null;
|
||||
}
|
||||
|
||||
reconnectAttempts = 0; // Reset attempts on explicit disconnect
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset reconnect attempts counter (call this to allow reconnection after max attempts)
|
||||
*/
|
||||
export function resetReconnectAttempts() {
|
||||
reconnectAttempts = 0;
|
||||
}
|
||||
|
||||
export function sendMessage(message) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue