Skip to content

Commit

Permalink
Server shutdown only if no errors
Browse files Browse the repository at this point in the history
Summary:
The socket will close as the endpoint is terminating the connection.

Status code 1000 and 1001 are used for normal closures. Either the connection is no longer needed or the endpoint is going away i.e. browser navigating away from the current page.

WS RFC: https://www.rfc-editor.org/rfc/rfc6455

Reviewed By: LukeDefeo

Differential Revision: D48896696

fbshipit-source-id: 22070ae34b7f35d35589db06108feb718e73e866
  • Loading branch information
lblasa authored and facebook-github-bot committed Sep 1, 2023
1 parent 43c549e commit 4e7a6a7
Showing 1 changed file with 32 additions and 16 deletions.
48 changes: 32 additions & 16 deletions desktop/flipper-server-core/src/server/attachSocketServer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,8 @@ export function attachSocketServer(
safe(() => onClientMessage(data));
});

async function onClientClose(error: Error | undefined = undefined) {
async function onClientClose(closeOnIdle: boolean) {
console.log(`Client disconnected ${clientAddress}`);
if (error) {
console.error('Client disconnected with error', error);
}

numberOfConnectedClients--;

Expand All @@ -244,24 +241,43 @@ export function attachSocketServer(
clearTimeout(disconnectTimeout);
}

/**
* If, after 60 seconds, there are no more connected clients, we exit the process.
*/
disconnectTimeout = setTimeout(() => {
if (numberOfConnectedClients === 0 && isProduction()) {
console.info('Shutdown as no clients are currently connected');
process.exit(0);
}
}, 60 * 1000);
if (closeOnIdle) {
/**
* If, after 60 seconds, there are no more connected clients, we exit the process.
*/
disconnectTimeout = setTimeout(() => {
if (numberOfConnectedClients === 0 && isProduction()) {
console.info('Shutdown as no clients are currently connected');
process.exit(0);
}
}, 60 * 1000);
}
}
}

client.on('close', () => {
safe(() => onClientClose());
client.on('close', (code, _reason) => {
/**
* The socket will close as the endpoint is terminating
* the connection. Status code 1000 and 1001 are used for normal
* closures. Either the connection is no longer needed or the
* endpoint is going away i.e. browser navigating away from the
* current page.
* WS RFC: https://www.rfc-editor.org/rfc/rfc6455
*/
const closeOnIdle = code === 1000 || code === 1001;
safe(() => onClientClose(closeOnIdle));
});

client.on('error', (error) => {
safe(() => onClientClose(error));
safe(() => {
/**
* The socket will close due to an error. In this case,
* do not close on idle as there's a high probability the
* client will attempt to connect again.
*/
onClientClose(false);
console.error('Client disconnected with error', error);
});
});
});
}

0 comments on commit 4e7a6a7

Please sign in to comment.