mirror of
https://github.com/Shik3i/KoalaSync.git
synced 2026-08-28 03:27:10 +00:00
feat(extension): lazy-connect — only maintain WebSocket when actively in room
- Add connectIntent flag to gate all reconnect attempts - Only auto-connect on startup if roomId exists in storage - Close socket + stop reconnect after leaveRoom or idleLeave - Preserve existing behavior 1:1 when actively in a room - Guard force-sync state and peer list clearing during transient disconnects - Guard WEB_JOIN_REQUEST against empty sanitized roomId
This commit is contained in:
+46
-19
@@ -176,6 +176,7 @@ let reconnectAttempts = 0;
|
|||||||
let currentServerUrl = null;
|
let currentServerUrl = null;
|
||||||
let roomIdleSince = null;
|
let roomIdleSince = null;
|
||||||
let lastContentHeartbeatAt = null;
|
let lastContentHeartbeatAt = null;
|
||||||
|
let connectIntent = false;
|
||||||
const MAX_RECONNECT_ATTEMPTS = 20;
|
const MAX_RECONNECT_ATTEMPTS = 20;
|
||||||
const _RECONNECT_BASE_DELAY = 500;
|
const _RECONNECT_BASE_DELAY = 500;
|
||||||
const _RECONNECT_MAX_DELAY = 5000;
|
const _RECONNECT_MAX_DELAY = 5000;
|
||||||
@@ -404,7 +405,9 @@ function clearTargetTabForIdle() {
|
|||||||
|
|
||||||
async function leaveRoomAfterIdleGrace(reason) {
|
async function leaveRoomAfterIdleGrace(reason) {
|
||||||
if (!currentRoom) return;
|
if (!currentRoom) return;
|
||||||
|
connectIntent = false;
|
||||||
emit(EVENTS.LEAVE_ROOM, { peerId });
|
emit(EVENTS.LEAVE_ROOM, { peerId });
|
||||||
|
forceDisconnect();
|
||||||
currentRoom = null;
|
currentRoom = null;
|
||||||
currentTabId = null;
|
currentTabId = null;
|
||||||
currentTabTitle = null;
|
currentTabTitle = null;
|
||||||
@@ -457,7 +460,9 @@ async function connect() {
|
|||||||
addLog('Browser is offline. Waiting...', 'warn');
|
addLog('Browser is offline. Waiting...', 'warn');
|
||||||
broadcastConnectionStatus('offline');
|
broadcastConnectionStatus('offline');
|
||||||
isConnecting = false;
|
isConnecting = false;
|
||||||
scheduleReconnect();
|
if (currentRoom || connectIntent) {
|
||||||
|
scheduleReconnect();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -564,25 +569,32 @@ async function connect() {
|
|||||||
isNamespaceJoined = false;
|
isNamespaceJoined = false;
|
||||||
stopPing();
|
stopPing();
|
||||||
|
|
||||||
isForceSyncInitiator = false;
|
if (!connectIntent && !currentRoom) {
|
||||||
forceSyncAcks.clear();
|
isForceSyncInitiator = false;
|
||||||
if (forceSyncTimeout) clearTimeout(forceSyncTimeout);
|
forceSyncAcks.clear();
|
||||||
chrome.storage.session.set({
|
if (forceSyncTimeout) clearTimeout(forceSyncTimeout);
|
||||||
isForceSyncInitiator: false,
|
chrome.storage.session.set({
|
||||||
forceSyncAcks: [],
|
isForceSyncInitiator: false,
|
||||||
forceSyncDeadline: null
|
forceSyncAcks: [],
|
||||||
}).catch(() => {});
|
forceSyncDeadline: null
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
if (currentRoom) {
|
if (currentRoom && !connectIntent) {
|
||||||
currentRoom.peers = [];
|
currentRoom.peers = [];
|
||||||
if (storageInitialized) chrome.storage.session.set({ currentRoom }).catch(() => {});
|
if (storageInitialized) chrome.storage.session.set({ currentRoom }).catch(() => {});
|
||||||
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: [] }).catch(() => {});
|
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: [] }).catch(() => {});
|
||||||
}
|
}
|
||||||
broadcastConnectionStatus('disconnected');
|
broadcastConnectionStatus('disconnected');
|
||||||
addLog('Disconnected. Scheduling reconnect...', 'warn');
|
if (currentRoom || connectIntent) {
|
||||||
socket = null;
|
addLog('Disconnected. Scheduling reconnect...', 'warn');
|
||||||
scheduleReconnect();
|
socket = null;
|
||||||
|
scheduleReconnect();
|
||||||
|
} else {
|
||||||
|
addLog('Disconnected. No active session — staying disconnected.', 'info');
|
||||||
|
socket = null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
socket.onerror = () => {
|
socket.onerror = () => {
|
||||||
@@ -597,7 +609,9 @@ async function connect() {
|
|||||||
const errMsg = (e && e.message) ? e.message : String(e || 'Unknown connection error');
|
const errMsg = (e && e.message) ? e.message : String(e || 'Unknown connection error');
|
||||||
addLog(errMsg, logType);
|
addLog(errMsg, logType);
|
||||||
broadcastConnectionStatus('disconnected');
|
broadcastConnectionStatus('disconnected');
|
||||||
scheduleReconnect();
|
if (currentRoom || connectIntent) {
|
||||||
|
scheduleReconnect();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -738,6 +752,9 @@ function sendPing() {
|
|||||||
addLog('Ping timeout reached, force disconnecting to trigger reconnect', 'warn');
|
addLog('Ping timeout reached, force disconnecting to trigger reconnect', 'warn');
|
||||||
pendingPingT = null;
|
pendingPingT = null;
|
||||||
forceDisconnect();
|
forceDisconnect();
|
||||||
|
if (currentRoom || connectIntent) {
|
||||||
|
scheduleReconnect();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pingTimeout = null;
|
pingTimeout = null;
|
||||||
}, 5000);
|
}, 5000);
|
||||||
@@ -1334,7 +1351,7 @@ chrome.alarms.onAlarm.addListener(async (alarm) => {
|
|||||||
if (alarm.name === 'keepAlive') {
|
if (alarm.name === 'keepAlive') {
|
||||||
chrome.storage.session.get('keepAlive', () => {});
|
chrome.storage.session.get('keepAlive', () => {});
|
||||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||||
if (!reconnectFailed) {
|
if (!reconnectFailed && (currentRoom || connectIntent)) {
|
||||||
connect();
|
connect();
|
||||||
}
|
}
|
||||||
} else if (currentRoom) {
|
} else if (currentRoom) {
|
||||||
@@ -1417,6 +1434,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
|
|
||||||
if (message.type === 'CONNECT') {
|
if (message.type === 'CONNECT') {
|
||||||
const settings = await getSettings();
|
const settings = await getSettings();
|
||||||
|
connectIntent = !!settings.roomId;
|
||||||
const desiredUrl = resolveServerUrl(settings);
|
const desiredUrl = resolveServerUrl(settings);
|
||||||
|
|
||||||
if (settings.roomId && currentRoom && currentRoom.roomId === settings.roomId && socket && socket.readyState === WebSocket.OPEN && isNamespaceJoined && desiredUrl === currentServerUrl) {
|
if (settings.roomId && currentRoom && currentRoom.roomId === settings.roomId && socket && socket.readyState === WebSocket.OPEN && isNamespaceJoined && desiredUrl === currentServerUrl) {
|
||||||
@@ -1439,7 +1457,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
}
|
}
|
||||||
if (desiredUrl !== currentServerUrl || !socket || socket.readyState !== WebSocket.OPEN || !isNamespaceJoined) {
|
if (desiredUrl !== currentServerUrl || !socket || socket.readyState !== WebSocket.OPEN || !isNamespaceJoined) {
|
||||||
if (desiredUrl !== currentServerUrl) forceDisconnect();
|
if (desiredUrl !== currentServerUrl) forceDisconnect();
|
||||||
connect();
|
if (settings.roomId) connect();
|
||||||
} else if (settings.roomId) {
|
} else if (settings.roomId) {
|
||||||
emit(EVENTS.JOIN_ROOM, {
|
emit(EVENTS.JOIN_ROOM, {
|
||||||
roomId: settings.roomId,
|
roomId: settings.roomId,
|
||||||
@@ -1452,6 +1470,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
}
|
}
|
||||||
sendResponse({ status: 'ok' });
|
sendResponse({ status: 'ok' });
|
||||||
} else if (message.type === 'RETRY_CONNECT') {
|
} else if (message.type === 'RETRY_CONNECT') {
|
||||||
|
connectIntent = true;
|
||||||
reconnectFailed = false;
|
reconnectFailed = false;
|
||||||
reconnectStartTime = null;
|
reconnectStartTime = null;
|
||||||
reconnectAttempts = 0;
|
reconnectAttempts = 0;
|
||||||
@@ -1480,6 +1499,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
ping: currentPingMs
|
ping: currentPingMs
|
||||||
});
|
});
|
||||||
} else if (message.type === 'LEAVE_ROOM') {
|
} else if (message.type === 'LEAVE_ROOM') {
|
||||||
|
connectIntent = false;
|
||||||
resetAudioProcessingInTab(currentTabId);
|
resetAudioProcessingInTab(currentTabId);
|
||||||
emit(EVENTS.LEAVE_ROOM, { peerId });
|
emit(EVENTS.LEAVE_ROOM, { peerId });
|
||||||
currentRoom = null;
|
currentRoom = null;
|
||||||
@@ -1510,8 +1530,10 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
episodeLobby: null,
|
episodeLobby: null,
|
||||||
expectedAcksCount: 0
|
expectedAcksCount: 0
|
||||||
});
|
});
|
||||||
|
chrome.storage.local.set({ roomId: '', password: '' }).catch(() => {});
|
||||||
addLog('Left Room', 'info');
|
addLog('Left Room', 'info');
|
||||||
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: [] }).catch(() => {});
|
chrome.runtime.sendMessage({ type: 'PEER_UPDATE', peers: [] }).catch(() => {});
|
||||||
|
forceDisconnect();
|
||||||
sendResponse({ status: 'ok' });
|
sendResponse({ status: 'ok' });
|
||||||
} else if (message.type === 'CLEAR_LOGS') {
|
} else if (message.type === 'CLEAR_LOGS') {
|
||||||
logs = [];
|
logs = [];
|
||||||
@@ -1526,6 +1548,8 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
} else if (message.type === 'WEB_JOIN_REQUEST') {
|
} else if (message.type === 'WEB_JOIN_REQUEST') {
|
||||||
const { roomId: rawRoomId, password, useCustomServer, serverUrl } = message;
|
const { roomId: rawRoomId, password, useCustomServer, serverUrl } = message;
|
||||||
const roomId = typeof rawRoomId === 'string' ? rawRoomId.replace(/[^a-zA-Z0-9\-]/g, '') : '';
|
const roomId = typeof rawRoomId === 'string' ? rawRoomId.replace(/[^a-zA-Z0-9\-]/g, '') : '';
|
||||||
|
connectIntent = !!roomId;
|
||||||
|
if (!roomId) { sendResponse({ error: 'invalid_room_id' }); return; }
|
||||||
chrome.storage.local.set({
|
chrome.storage.local.set({
|
||||||
roomId,
|
roomId,
|
||||||
password,
|
password,
|
||||||
@@ -1554,7 +1578,7 @@ async function handleAsyncMessage(message, sender, sendResponse) {
|
|||||||
if (desiredUrl !== currentServerUrl || !socket || socket.readyState !== WebSocket.OPEN || !isNamespaceJoined) {
|
if (desiredUrl !== currentServerUrl || !socket || socket.readyState !== WebSocket.OPEN || !isNamespaceJoined) {
|
||||||
if (desiredUrl !== currentServerUrl) forceDisconnect();
|
if (desiredUrl !== currentServerUrl) forceDisconnect();
|
||||||
connect();
|
connect();
|
||||||
} else {
|
} else if (roomId) {
|
||||||
emit(EVENTS.JOIN_ROOM, {
|
emit(EVENTS.JOIN_ROOM, {
|
||||||
roomId,
|
roomId,
|
||||||
password,
|
password,
|
||||||
@@ -1939,5 +1963,8 @@ chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, _tab) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Initial Connect
|
// Initial Connect — only if user has an active room configuration
|
||||||
connect();
|
getSettings().then(settings => {
|
||||||
|
connectIntent = !!settings.roomId;
|
||||||
|
if (connectIntent) connect();
|
||||||
|
}).catch(() => connectIntent = false);
|
||||||
|
|||||||
Reference in New Issue
Block a user