Improve WebSocket hook: limit queue size and add cleanup on unmount

Co-authored-by: nate <nate@buster.so>
This commit is contained in:
Cursor Agent 2025-08-08 14:08:33 +00:00
parent 8cd8db7d01
commit 8c8ea819a8
1 changed files with 15 additions and 0 deletions

View File

@ -22,6 +22,7 @@ interface QueuedMessage {
}
const BASE_DELAY = 3000;
const MAX_QUEUE_LENGTH = 5000;
const useWebSocket = ({ url, checkTokenValidity, canConnect, onMessage }: WebSocketHookProps) => {
const { online } = useNetwork();
@ -117,6 +118,11 @@ const useWebSocket = ({ url, checkTokenValidity, canConnect, onMessage }: WebSoc
messageQueue.current.push(queuedMessage);
// Bound the queue length to prevent unbounded memory growth
if (messageQueue.current.length > MAX_QUEUE_LENGTH) {
messageQueue.current.splice(0, messageQueue.current.length - MAX_QUEUE_LENGTH);
}
if (!processing.current) {
processQueue();
}
@ -224,6 +230,15 @@ const useWebSocket = ({ url, checkTokenValidity, canConnect, onMessage }: WebSoc
handleVisibilityChange();
});
// Cleanup on unmount: close socket and clear queues
useEffect(() => {
return () => {
disconnect();
messageQueue.current = [];
sendQueue.current = [];
};
}, [disconnect]);
return {
sendJSONMessage,
disconnect,