Skip to content
Open
Show file tree
Hide file tree
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
59 changes: 59 additions & 0 deletions spec/ParseLiveQuery.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,65 @@ describe('ParseLiveQuery', function () {
await client.close();
});

it('reports the disconnected client ID when two LiveQuery clients share a session', async () => {
const user = new Parse.User({ username: 'presence-user', password: 'password' });
await user.signUp();
const sessionToken = user.getSessionToken();
expect(sessionToken).toEqual(jasmine.any(String));
const installationId = '00000000-0000-4000-8000-000000000001';
const options = {
applicationId: Parse.applicationId,
serverURL: Parse.liveQueryServerURL,
sessionToken,
installationId,
};
const firstClient = new Parse.LiveQueryClient(options);
const secondClient = new Parse.LiveQueryClient(options);
const connectedClientIds = [];
const disconnected = resolvingPromise();
Parse.Cloud.onLiveQueryEvent(request => {
if (request.sessionToken !== sessionToken) {
return;
}
if (request.event === 'connect') {
connectedClientIds.push(request.client.id);
}
if (request.event === 'ws_disconnect') {
disconnected.resolve(request);
}
});

try {
for (const client of [firstClient, secondClient]) {
const opened = new Promise((resolve, reject) => {
client.on('open', resolve);
client.on('error', reject);
});
client.open();
await opened;
}

const firstClientId = firstClient.id;
expect(firstClientId).not.toBe(secondClient.id);
expect(connectedClientIds).toEqual([firstClientId, secondClient.id]);

await firstClient.close();
expect(await disconnected).toEqual(
jasmine.objectContaining({
event: 'ws_disconnect',
clientId: firstClientId,
clients: 1,
subscriptions: 0,
sessionToken,
installationId,
useMasterKey: false,
})
);
} finally {
await Promise.all([firstClient.close(), secondClient.close()]);
}
});

it('can subscribe to query', async done => {
const object = new TestObject();
await object.save();
Expand Down
197 changes: 178 additions & 19 deletions spec/ParseLiveQueryServer.spec.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const Parse = require('parse/node');
const { EventEmitter } = require('events');
const ParseLiveQueryServer = require('../lib/LiveQuery/ParseLiveQueryServer').ParseLiveQueryServer;
const ParseServer = require('../lib/ParseServer').default;
const LiveQueryController = require('../lib/Controllers/LiveQueryController').LiveQueryController;
const { resolvingPromise } = require('../lib/TestUtils');
const auth = require('../lib/Auth');

// Global mock info
Expand All @@ -22,6 +24,7 @@ describe('ParseLiveQueryServer', function () {
);
// Mock Client
const mockClient = function (id, socket, hasMasterKey) {
this.id = id;
this.pushConnect = jasmine.createSpy('pushConnect');
this.pushSubscribe = jasmine.createSpy('pushSubscribe');
this.pushUnsubscribe = jasmine.createSpy('pushUnsubscribe');
Expand Down Expand Up @@ -582,7 +585,7 @@ describe('ParseLiveQueryServer', function () {
it('can set connect command message handler for a parseWebSocket', function () {
const parseLiveQueryServer = new ParseLiveQueryServer({});
// Register mock connect/subscribe/unsubscribe handler for the server
parseLiveQueryServer._handleConnect = jasmine.createSpy('_handleSubscribe');
parseLiveQueryServer._handleConnect = jasmine.createSpy('_handleConnect').and.resolveTo();
// Make mock parseWebsocket
const EventEmitter = require('events');
const parseWebSocket = new EventEmitter();
Expand Down Expand Up @@ -727,25 +730,181 @@ describe('ParseLiveQueryServer', function () {
parseWebSocket.emit('disconnect');
});

it('can forward event to cloud code', function () {
const cloudCodeHandler = {
handler: () => { },
};
const spy = spyOn(cloudCodeHandler, 'handler').and.callThrough();
Parse.Cloud.onLiveQueryEvent(cloudCodeHandler.handler);
const parseLiveQueryServer = new ParseLiveQueryServer({});
const EventEmitter = require('events');
const parseWebSocket = new EventEmitter();
parseWebSocket.clientId = 1;
// Register message handlers for the parseWebSocket
parseLiveQueryServer._onConnect(parseWebSocket);
describe('LiveQuery event payloads', () => {
const masterKey = 'payload-master-key';
const installationId = 'payload-installation';
let server;
let onEvent;

// Make sure we do not crash
// Trigger disconnect event
parseWebSocket.emit('disconnect');
expect(spy).toHaveBeenCalled();
// call for ws_connect, another for ws_disconnect
expect(spy.calls.count()).toBe(2);
beforeEach(() => {
server = new ParseLiveQueryServer({}, { keyPairs: { masterKey } });
onEvent = jasmine.createSpy('onLiveQueryEvent');
Parse.Cloud.onLiveQueryEvent(onEvent);
});

it('reports the ws_connect payload before the LiveQuery handshake', () => {
const socket = new EventEmitter();
server._onConnect(socket);

expect(onEvent).toHaveBeenCalledOnceWith(
jasmine.objectContaining({
event: 'ws_connect',
clientId: jasmine.any(String),
clients: 0,
subscriptions: 0,
})
);
expect(socket.clientId).toBeUndefined();
expect(server.clients.size).toBe(0);
});

it('reports the connect payload with the ID from ws_connect after a handshake retry', async () => {
const socket = new EventEmitter();
const handleConnect = spyOn(server, '_handleConnect').and.callThrough();
const beforeConnect = jasmine.createSpy('beforeConnect').and.throwError('Retry connect');
Parse.Cloud.beforeConnect(beforeConnect);
server._onConnect(socket);
const { clientId } = onEvent.calls.first().args[0];
const request = {
op: 'connect',
applicationId: Parse.applicationId,
masterKey,
installationId,
sessionToken: 'sessionToken',
};

socket.emit('message', request);
await handleConnect.calls.mostRecent().returnValue;
expect(onEvent).toHaveBeenCalledTimes(1);
expect(socket.clientId).toBeUndefined();

beforeConnect.and.stub();
socket.emit('message', request);
await handleConnect.calls.mostRecent().returnValue;
const client = server.clients.get(socket.clientId);

expect(client?.id).toBe(socket.clientId);
expect(clientId).toEqual(jasmine.any(String));
expect(socket.clientId).toBe(clientId);
expect(onEvent).toHaveBeenCalledWith(
jasmine.objectContaining({
event: 'connect',
clientId,
client,
clients: 0,
subscriptions: 0,
sessionToken: 'sessionToken',
installationId,
useMasterKey: true,
})
);
});

it('keeps the WebSocket client ID when connect requests overlap or repeat', async () => {
const { Client } = require('../lib/LiveQuery/Client');
const socket = new EventEmitter();
const handshake = resolvingPromise();
Parse.Cloud.beforeConnect(() => handshake);
const handleConnect = spyOn(server, '_handleConnect').and.callThrough();
server._onConnect(socket);
const { clientId } = onEvent.calls.first().args[0];
const request = { op: 'connect', applicationId: Parse.applicationId, masterKey };

socket.emit('message', request);
socket.emit('message', request);
expect(Client.pushError).toHaveBeenCalledOnceWith(socket, 1, jasmine.any(String), false);
handshake.resolve();
await Promise.all(handleConnect.calls.all().map(call => call.returnValue));

socket.emit('message', request);
await handleConnect.calls.mostRecent().returnValue;

expect(Client.pushError).toHaveBeenCalledTimes(2);
expect(onEvent).toHaveBeenCalledTimes(2);
expect(onEvent).toHaveBeenCalledWith(jasmine.objectContaining({ event: 'connect', clientId }));
expect(socket.clientId).toBe(clientId);

socket.emit('disconnect');
expect(onEvent.calls.mostRecent().args[0]).toEqual(
jasmine.objectContaining({ event: 'ws_disconnect', clientId, clients: 0 })
);
});

it('reports the subscribe payload with the registered client ID', async () => {
const clientId = 'subscribing-client';
const client = addMockClient(server, clientId);
client.installationId = installationId;
client.hasMasterKey = false;
await server._handleSubscribe(
{ clientId },
{
requestId: 1,
query: { className: testClassName, where: {} },
sessionToken: 'sessionToken',
}
);

expect(onEvent).toHaveBeenCalledOnceWith(
jasmine.objectContaining({
event: 'subscribe',
clientId,
client,
clients: 1,
subscriptions: 1,
sessionToken: 'sessionToken',
installationId,
useMasterKey: false,
})
);
});

it('reports the unsubscribe payload after removing the subscription', async () => {
const clientId = 'unsubscribing-client';
const client = addMockClient(server, clientId);
client.installationId = installationId;
client.hasMasterKey = false;
const socket = { clientId };
const requestId = 1;
await addMockSubscription(server, clientId, requestId, socket);
const [, subscriptionInfo] = client.addSubscriptionInfo.calls.mostRecent().args;
client.getSubscriptionInfo.and.returnValue(subscriptionInfo);
onEvent.calls.reset();

server._handleUnsubscribe(socket, { requestId });

expect(onEvent).toHaveBeenCalledOnceWith(
jasmine.objectContaining({
event: 'unsubscribe',
clientId,
client,
clients: 1,
subscriptions: 0,
sessionToken: 'sessionToken',
installationId,
useMasterKey: false,
})
);
});

it('reports the ws_disconnect_error payload when a socket closes before the handshake', () => {
const socket = new EventEmitter();
server._onConnect(socket);
const { clientId } = onEvent.calls.first().args[0];
onEvent.calls.reset();

socket.emit('disconnect');

expect(clientId).toEqual(jasmine.any(String));
expect(onEvent).toHaveBeenCalledOnceWith(
jasmine.objectContaining({
event: 'ws_disconnect_error',
clientId,
clients: 0,
subscriptions: 0,
error: `Unable to find client ${clientId}`,
})
);
});
});

it('does not delete subscription info on client disconnect', async () => {
Expand Down
35 changes: 30 additions & 5 deletions src/LiveQuery/ParseLiveQueryServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,9 @@ class ParseLiveQueryServer {
}

_onConnect(parseWebsocket: any): void {
// Reserve the ID early while leaving clientId unset until the handshake succeeds.
const initialClientId = randomUUID();
let connectPending = false;
parseWebsocket.on('message', request => {
if (typeof request === 'string') {
try {
Expand All @@ -521,7 +524,19 @@ class ParseLiveQueryServer {

switch (request.op) {
case 'connect':
this._handleConnect(parseWebsocket, request);
if (connectPending || parseWebsocket.clientId !== undefined) {
Client.pushError(
parseWebsocket,
1,
'A LiveQuery handshake is already in progress or complete on this WebSocket',
false
);
break;
}
connectPending = true;
this._handleConnect(parseWebsocket, request, initialClientId).finally(() => {
connectPending = false;
});
break;
case 'subscribe':
this._handleSubscribe(parseWebsocket, request);
Expand All @@ -539,11 +554,12 @@ class ParseLiveQueryServer {
});

parseWebsocket.on('disconnect', () => {
logger.info(`Client disconnect: ${parseWebsocket.clientId}`);
const clientId = parseWebsocket.clientId;
const clientId = parseWebsocket.clientId ?? initialClientId;
logger.info(`Client disconnect: ${clientId}`);
if (!this.clients.has(clientId)) {
runLiveQueryEventHandlers({
event: 'ws_disconnect_error',
clientId,
clients: this.clients.size,
subscriptions: this.subscriptions.size,
error: `Unable to find client ${clientId}`,
Expand Down Expand Up @@ -578,6 +594,7 @@ class ParseLiveQueryServer {
logger.verbose('Current subscriptions %d', this.subscriptions.size);
runLiveQueryEventHandlers({
event: 'ws_disconnect',
clientId,
clients: this.clients.size,
subscriptions: this.subscriptions.size,
useMasterKey: client.hasMasterKey,
Expand All @@ -588,6 +605,7 @@ class ParseLiveQueryServer {

runLiveQueryEventHandlers({
event: 'ws_connect',
clientId: initialClientId,
clients: this.clients.size,
subscriptions: this.subscriptions.size,
});
Expand Down Expand Up @@ -1064,14 +1082,18 @@ class ParseLiveQueryServer {
return false;
}

async _handleConnect(parseWebsocket: any, request: any): Promise<any> {
async _handleConnect(
parseWebsocket: any,
request: any,
initialClientId?: string
): Promise<any> {
if (!this._validateKeys(request, this.keyPairs)) {
Client.pushError(parseWebsocket, 4, 'Key in request is not valid');
logger.error('Key in request is not valid');
return;
}
const hasMasterKey = this._hasMasterKey(request, this.keyPairs);
const clientId = randomUUID();
const clientId = initialClientId ?? randomUUID();
const client = new Client(
clientId,
parseWebsocket,
Expand All @@ -1083,6 +1105,7 @@ class ParseLiveQueryServer {
const req = {
client,
event: 'connect',
clientId,
clients: this.clients.size,
subscriptions: this.subscriptions.size,
sessionToken: request.sessionToken,
Expand Down Expand Up @@ -1427,6 +1450,7 @@ class ParseLiveQueryServer {
runLiveQueryEventHandlers({
client,
event: 'subscribe',
clientId: client.id,
clients: this.clients.size,
subscriptions: this.subscriptions.size,
sessionToken: request.sessionToken,
Expand Down Expand Up @@ -1515,6 +1539,7 @@ class ParseLiveQueryServer {
runLiveQueryEventHandlers({
client,
event: 'unsubscribe',
clientId: client.id,
clients: this.clients.size,
subscriptions: this.subscriptions.size,
sessionToken: subscriptionInfo.sessionToken,
Expand Down
Loading