diff --git a/spec/ParseLiveQuery.spec.js b/spec/ParseLiveQuery.spec.js index 59ab337897..7a163ba93e 100644 --- a/spec/ParseLiveQuery.spec.js +++ b/spec/ParseLiveQuery.spec.js @@ -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(); diff --git a/spec/ParseLiveQueryServer.spec.js b/spec/ParseLiveQueryServer.spec.js index b04e9f0b11..96fcf71e56 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -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 @@ -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'); @@ -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(); @@ -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 () => { diff --git a/src/LiveQuery/ParseLiveQueryServer.ts b/src/LiveQuery/ParseLiveQueryServer.ts index 16ac1a5b43..3057323d59 100644 --- a/src/LiveQuery/ParseLiveQueryServer.ts +++ b/src/LiveQuery/ParseLiveQueryServer.ts @@ -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 { @@ -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); @@ -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}`, @@ -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, @@ -588,6 +605,7 @@ class ParseLiveQueryServer { runLiveQueryEventHandlers({ event: 'ws_connect', + clientId: initialClientId, clients: this.clients.size, subscriptions: this.subscriptions.size, }); @@ -1064,14 +1082,18 @@ class ParseLiveQueryServer { return false; } - async _handleConnect(parseWebsocket: any, request: any): Promise { + async _handleConnect( + parseWebsocket: any, + request: any, + initialClientId?: string + ): Promise { 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, @@ -1083,6 +1105,7 @@ class ParseLiveQueryServer { const req = { client, event: 'connect', + clientId, clients: this.clients.size, subscriptions: this.subscriptions.size, sessionToken: request.sessionToken, @@ -1427,6 +1450,7 @@ class ParseLiveQueryServer { runLiveQueryEventHandlers({ client, event: 'subscribe', + clientId: client.id, clients: this.clients.size, subscriptions: this.subscriptions.size, sessionToken: request.sessionToken, @@ -1515,6 +1539,7 @@ class ParseLiveQueryServer { runLiveQueryEventHandlers({ client, event: 'unsubscribe', + clientId: client.id, clients: this.clients.size, subscriptions: this.subscriptions.size, sessionToken: subscriptionInfo.sessionToken, diff --git a/src/cloud-code/Parse.Cloud.js b/src/cloud-code/Parse.Cloud.js index bff17ad0d4..1998eaae00 100644 --- a/src/cloud-code/Parse.Cloud.js +++ b/src/cloud-code/Parse.Cloud.js @@ -679,6 +679,19 @@ ParseCloud.beforeSubscribe = function (parseClass, handler, validationHandler) { ); }; +/** + * Registers a handler for LiveQuery server events. + * + * Events include a top-level `clientId`. The server reserves it on `ws_connect` and uses it for + * the LiveQuery handshake. A socket allows one handshake at a time, can retry after a rejection, + * and keeps the ID until it closes. A close before a successful handshake reports the reserved ID + * on `ws_disconnect_error`. Events with a `client` also expose the ID as `client.id`. + * + * **Available in Cloud Code only.** + * + * @name Parse.Cloud.onLiveQueryEvent + * @param {Function} handler The function to run when the server emits a LiveQuery event. + */ ParseCloud.onLiveQueryEvent = function (handler) { triggers.addLiveQueryEventHandler(handler, Parse.applicationId); };