Skip to content

Disconnect the WebSocket after an idle period #911

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion ui/frontend/websocketMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,35 @@ const openWebSocket = (currentLocation: Location) => {
// https://exponentialbackoffcalculator.com
const backoffMs = (n: number) => Math.min(100 * Math.pow(2, n), 10000);

const idleTimeoutMs = 60 * 60 * 1000;

export const websocketMiddleware =
(window: Window): Middleware =>
(store) => {
let socket: WebSocket | null = null;
let wasConnected = false;
let reconnectAttempt = 0;

let timeout: number | null = null;
const resetTimeout = () => {
if (timeout) {
window.clearTimeout(timeout);
}

timeout = window.setTimeout(() => {
if (!socket) {
return;
}

socket.close();
}, idleTimeoutMs);
};

const connect = () => {
socket = openWebSocket(window.location);

if (socket) {
resetTimeout();

socket.addEventListener('open', () => {
store.dispatch(websocketConnected());

Expand Down Expand Up @@ -85,6 +103,7 @@ export const websocketMiddleware =
const rawMessage = JSON.parse(event.data);
const message = WSMessageResponse.parse(rawMessage);
store.dispatch(message);
resetTimeout();
} catch (e) {
console.log('Unable to parse WebSocket message', event.data, e);
}
Expand All @@ -110,6 +129,7 @@ export const websocketMiddleware =
if (socket && socket.readyState == socket.OPEN && sendActionOnWebsocket(action)) {
const message = JSON.stringify(action);
socket.send(message);
resetTimeout();
}

next(action);
Expand Down