From 1959fe1da9c84a42b722e693e0dfdf053402d23f Mon Sep 17 00:00:00 2001 From: Helder Mattos Date: Tue, 24 Nov 2026 22:57:02 +0100 Subject: [PATCH 1/3] feat: expose the client ID in LiveQuery disconnect events --- spec/ParseLiveQuery.spec.js | 52 +++++++++++++++++++++++++++ spec/ParseLiveQueryServer.spec.js | 9 ++--- src/LiveQuery/ParseLiveQueryServer.ts | 2 ++ src/cloud-code/Parse.Cloud.js | 11 ++++++ 4 files changed, 70 insertions(+), 4 deletions(-) diff --git a/spec/ParseLiveQuery.spec.js b/spec/ParseLiveQuery.spec.js index 59ab337897..54d9b63fd8 100644 --- a/spec/ParseLiveQuery.spec.js +++ b/spec/ParseLiveQuery.spec.js @@ -39,6 +39,58 @@ 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(); + const event = await disconnected; + expect(event.clientId).toBe(firstClientId); + expect(event.installationId).toBe(installationId); + expect(event.clients).toBe(1); + } 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..7bc2122838 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -727,7 +727,7 @@ describe('ParseLiveQueryServer', function () { parseWebSocket.emit('disconnect'); }); - it('can forward event to cloud code', function () { + it('reports the client ID to cloud code on a disconnect error', function () { const cloudCodeHandler = { handler: () => { }, }; @@ -743,9 +743,10 @@ describe('ParseLiveQueryServer', function () { // 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); + expect(spy).toHaveBeenCalledTimes(2); + expect(spy).toHaveBeenCalledWith( + jasmine.objectContaining({ event: 'ws_disconnect_error', clientId: parseWebSocket.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..632661d9c0 100644 --- a/src/LiveQuery/ParseLiveQueryServer.ts +++ b/src/LiveQuery/ParseLiveQueryServer.ts @@ -544,6 +544,7 @@ class ParseLiveQueryServer { 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 +579,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, diff --git a/src/cloud-code/Parse.Cloud.js b/src/cloud-code/Parse.Cloud.js index bff17ad0d4..44d08ca92a 100644 --- a/src/cloud-code/Parse.Cloud.js +++ b/src/cloud-code/Parse.Cloud.js @@ -679,6 +679,17 @@ ParseCloud.beforeSubscribe = function (parseClass, handler, validationHandler) { ); }; +/** + * Registers a handler for LiveQuery server events. + * + * The `ws_disconnect` event includes the same `clientId` as `client.id` in the `connect` event + * for that connection. The `ws_disconnect_error` event includes the ID when one was assigned. + * + * **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); }; From 54574e7b1021a29ffeb0ddfeac2339894097b3d7 Mon Sep 17 00:00:00 2001 From: Helder Mattos Date: Wed, 25 Nov 2026 11:17:04 +0100 Subject: [PATCH 2/3] feat: expose the client ID across LiveQuery events --- spec/ParseLiveQuery.spec.js | 15 ++- spec/ParseLiveQueryServer.spec.js | 167 +++++++++++++++++++++++--- src/LiveQuery/ParseLiveQueryServer.ts | 28 ++++- src/cloud-code/Parse.Cloud.js | 6 +- 4 files changed, 185 insertions(+), 31 deletions(-) diff --git a/spec/ParseLiveQuery.spec.js b/spec/ParseLiveQuery.spec.js index 54d9b63fd8..7a163ba93e 100644 --- a/spec/ParseLiveQuery.spec.js +++ b/spec/ParseLiveQuery.spec.js @@ -82,10 +82,17 @@ describe('ParseLiveQuery', function () { expect(connectedClientIds).toEqual([firstClientId, secondClient.id]); await firstClient.close(); - const event = await disconnected; - expect(event.clientId).toBe(firstClientId); - expect(event.installationId).toBe(installationId); - expect(event.clients).toBe(1); + 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()]); } diff --git a/spec/ParseLiveQueryServer.spec.js b/spec/ParseLiveQueryServer.spec.js index 7bc2122838..bc6dfd882d 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -1,4 +1,5 @@ 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; @@ -22,6 +23,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 +584,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,26 +729,151 @@ describe('ParseLiveQueryServer', function () { parseWebSocket.emit('disconnect'); }); - it('reports the client ID to cloud code on a disconnect error', 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).toHaveBeenCalledTimes(2); - expect(spy).toHaveBeenCalledWith( - jasmine.objectContaining({ event: 'ws_disconnect_error', clientId: parseWebSocket.clientId }) - ); + 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('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 632661d9c0..8ab313ab9b 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 initialConnectPending = false; parseWebsocket.on('message', request => { if (typeof request === 'string') { try { @@ -521,7 +524,14 @@ class ParseLiveQueryServer { switch (request.op) { case 'connect': - this._handleConnect(parseWebsocket, request); + if (initialConnectPending || parseWebsocket.clientId !== undefined) { + this._handleConnect(parseWebsocket, request); + } else { + initialConnectPending = true; + this._handleConnect(parseWebsocket, request, initialClientId).finally(() => { + initialConnectPending = false; + }); + } break; case 'subscribe': this._handleSubscribe(parseWebsocket, request); @@ -539,8 +549,8 @@ 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', @@ -590,6 +600,7 @@ class ParseLiveQueryServer { runLiveQueryEventHandlers({ event: 'ws_connect', + clientId: initialClientId, clients: this.clients.size, subscriptions: this.subscriptions.size, }); @@ -1066,14 +1077,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, @@ -1085,6 +1100,7 @@ class ParseLiveQueryServer { const req = { client, event: 'connect', + clientId, clients: this.clients.size, subscriptions: this.subscriptions.size, sessionToken: request.sessionToken, @@ -1429,6 +1445,7 @@ class ParseLiveQueryServer { runLiveQueryEventHandlers({ client, event: 'subscribe', + clientId: client.id, clients: this.clients.size, subscriptions: this.subscriptions.size, sessionToken: request.sessionToken, @@ -1517,6 +1534,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 44d08ca92a..f8b8afae4c 100644 --- a/src/cloud-code/Parse.Cloud.js +++ b/src/cloud-code/Parse.Cloud.js @@ -682,8 +682,10 @@ ParseCloud.beforeSubscribe = function (parseClass, handler, validationHandler) { /** * Registers a handler for LiveQuery server events. * - * The `ws_disconnect` event includes the same `clientId` as `client.id` in the `connect` event - * for that connection. The `ws_disconnect_error` event includes the ID when one was assigned. + * Events include a top-level `clientId`. The server reserves this ID on `ws_connect` for the + * initial LiveQuery handshake. If the socket closes before the handshake succeeds, + * `ws_disconnect_error` reports the reserved ID. Events with a `client` also expose its ID + * as `client.id`. * * **Available in Cloud Code only.** * From cf9536561e1a37d7ff898c54c33c4e019f87628c Mon Sep 17 00:00:00 2001 From: Helder Mattos Date: Wed, 25 Nov 2026 11:43:45 +0100 Subject: [PATCH 3/3] fix: preserve the LiveQuery client ID on repeated connect requests --- spec/ParseLiveQueryServer.spec.js | 31 +++++++++++++++++++++++++++ src/LiveQuery/ParseLiveQueryServer.ts | 21 +++++++++++------- src/cloud-code/Parse.Cloud.js | 8 +++---- 3 files changed, 48 insertions(+), 12 deletions(-) diff --git a/spec/ParseLiveQueryServer.spec.js b/spec/ParseLiveQueryServer.spec.js index bc6dfd882d..96fcf71e56 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -3,6 +3,7 @@ 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 @@ -799,6 +800,36 @@ describe('ParseLiveQueryServer', function () { ); }); + 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); diff --git a/src/LiveQuery/ParseLiveQueryServer.ts b/src/LiveQuery/ParseLiveQueryServer.ts index 8ab313ab9b..3057323d59 100644 --- a/src/LiveQuery/ParseLiveQueryServer.ts +++ b/src/LiveQuery/ParseLiveQueryServer.ts @@ -500,7 +500,7 @@ class ParseLiveQueryServer { _onConnect(parseWebsocket: any): void { // Reserve the ID early while leaving clientId unset until the handshake succeeds. const initialClientId = randomUUID(); - let initialConnectPending = false; + let connectPending = false; parseWebsocket.on('message', request => { if (typeof request === 'string') { try { @@ -524,14 +524,19 @@ class ParseLiveQueryServer { switch (request.op) { case 'connect': - if (initialConnectPending || parseWebsocket.clientId !== undefined) { - this._handleConnect(parseWebsocket, request); - } else { - initialConnectPending = true; - this._handleConnect(parseWebsocket, request, initialClientId).finally(() => { - initialConnectPending = false; - }); + 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); diff --git a/src/cloud-code/Parse.Cloud.js b/src/cloud-code/Parse.Cloud.js index f8b8afae4c..1998eaae00 100644 --- a/src/cloud-code/Parse.Cloud.js +++ b/src/cloud-code/Parse.Cloud.js @@ -682,10 +682,10 @@ ParseCloud.beforeSubscribe = function (parseClass, handler, validationHandler) { /** * Registers a handler for LiveQuery server events. * - * Events include a top-level `clientId`. The server reserves this ID on `ws_connect` for the - * initial LiveQuery handshake. If the socket closes before the handshake succeeds, - * `ws_disconnect_error` reports the reserved ID. Events with a `client` also expose its ID - * as `client.id`. + * 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.** *