Skip to content

Commit

Permalink
fix: interrupted WebSocket connection not closed by LiveQuery server (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
pash2048 committed Jun 5, 2022
1 parent 468e987 commit 2d5221e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
25 changes: 25 additions & 0 deletions spec/ParseWebSocketServer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ describe('ParseWebSocketServer', function () {
ws.readyState = 0;
ws.OPEN = 0;
ws.ping = jasmine.createSpy('ping');
ws.terminate = () => {};

parseWebSocketServer.onConnection(ws);

Expand Down Expand Up @@ -75,6 +76,30 @@ describe('ParseWebSocketServer', function () {
expect(wssError).toBe('Invalid Packet');
});

it('closes interrupted connection', async () => {
const onConnectCallback = jasmine.createSpy('onConnectCallback');
const http = require('http');
const server = http.createServer();
const parseWebSocketServer = new ParseWebSocketServer(server, onConnectCallback, {
websocketTimeout: 5,
}).server;
const ws = new EventEmitter();
ws.readyState = 0;
ws.OPEN = 0;
ws.ping = jasmine.createSpy('ping');
ws.terminate = jasmine.createSpy('terminate');

parseWebSocketServer.onConnection(ws);

// Make sure callback is called
expect(onConnectCallback).toHaveBeenCalled();
await new Promise(resolve => setTimeout(resolve, 10));
expect(ws.ping).toHaveBeenCalled();
await new Promise(resolve => setTimeout(resolve, 10));
expect(ws.terminate).toHaveBeenCalled();
server.close();
});

afterEach(function () {
jasmine.restoreLibrary('ws', 'Server');
});
Expand Down
8 changes: 7 additions & 1 deletion src/LiveQuery/ParseWebSocketServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,23 @@ export class ParseWebSocketServer {
logger.info('Parse LiveQuery Server started running');
};
wss.onConnection = ws => {
ws.waitingForPong = false;
ws.on('pong', () => {
this.waitingForPong = false;
});
ws.on('error', error => {
logger.error(error.message);
logger.error(inspect(ws, false));
});
onConnect(new ParseWebSocket(ws));
// Send ping to client periodically
const pingIntervalId = setInterval(() => {
if (ws.readyState == ws.OPEN) {
if (!ws.waitingForPong) {
ws.ping();
ws.waitingForPong = true;
} else {
clearInterval(pingIntervalId);
ws.terminate();
}
}, config.websocketTimeout || 10 * 1000);
};
Expand Down

0 comments on commit 2d5221e

Please sign in to comment.