Skip to content
51 changes: 51 additions & 0 deletions spec/CLI.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,8 @@ describe('execution', () => {
done();
});
childProcess.kill();
} else {
done();
}
});

Expand Down Expand Up @@ -313,4 +315,53 @@ describe('execution', () => {
);
await waitForStartup(childProcess, ['parse-server running on']);
});

// Parse Server handles termination signals only outside of tests, so the process runs without TESTING
async function startAndTerminate(args) {
const env = { ...process.env };
env.NODE_OPTIONS = '--dns-result-order=ipv4first --trace-deprecation';
delete env.TESTING;
childProcess = spawn(binPath, args, { env });
let output = '';
childProcess.stdout.on('data', data => (output += data));
childProcess.stderr.on('data', data => (output += data));
await waitForStartup(childProcess, ['parse-server running on']);
const exit = new Promise(resolve => {
// The close event is emitted after the output streams have ended
childProcess.once('close', (code, signal) => resolve({ code, signal }));
});
const killTimeout = setTimeout(() => childProcess.kill('SIGKILL'), 5000);
childProcess.kill('SIGTERM');
const { code, signal } = await exit;
clearTimeout(killTimeout);
childProcess = undefined;
return { code, signal, output };
}

const it_only_redis = process.env.PARSE_SERVER_TEST_CACHE === 'redis' ? it : xit;

it_only_redis('should exit after a termination signal with Redis cache and LiveQuery', async () => {
const { code, signal, output } = await startAndTerminate(
[
'--appId',
'test',
'--masterKey',
'test',
'--databaseURI',
databaseURI,
'--port',
'1343',
'--cacheAdapter',
JSON.stringify({
module: path.resolve(__dirname, '../lib/Adapters/Cache/RedisCacheAdapter'),
options: { url: 'redis://localhost:6379' },
}),
'--liveQuery',
JSON.stringify({ classNames: ['TestObject'], redisURL: 'redis://localhost:6379' }),
]
);
expect(signal).toBeNull();
expect(code).toBe(0);
expect(output).not.toContain('error on shutdown');
});
});
184 changes: 184 additions & 0 deletions spec/ParseCloudCodePublisher.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const ParseCloudCodePublisher = require('../lib/LiveQuery/ParseCloudCodePublisher')
.ParseCloudCodePublisher;
const Parse = require('parse/node');
const net = require('net');
const { createClient } = require('redis');

describe('ParseCloudCodePublisher', function () {
beforeEach(function (done) {
Expand Down Expand Up @@ -70,6 +72,188 @@ describe('ParseCloudCodePublisher', function () {
expect(message.originalParseObject).toEqual(request.original._toFullJSON());
});

it('logs an error if publishing fails', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error');
const publisher = new ParseCloudCodePublisher({});
const error = new Error('The client is closed');
publisher.parsePublisher.publish.and.rejectWith(error);
publisher._onCloudCodeMessage('afterSave', { object: new Parse.Object('Test') });
await new Promise(resolve => setImmediate(resolve));

expect(loggerErrorSpy).toHaveBeenCalledWith('LiveQuery publisher error', { error });
});

it('closes an open publisher that cannot be destroyed', async () => {
const publisher = new ParseCloudCodePublisher({});
publisher.parsePublisher.isOpen = true;
publisher.parsePublisher.close = jasmine.createSpy('close').and.resolveTo();
await publisher.shutdown();

expect(publisher.parsePublisher.close).toHaveBeenCalledTimes(1);
});

it('waits for the messages in flight before destroying the publisher', async () => {
const publisher = new ParseCloudCodePublisher({});
let resolvePublish;
publisher.parsePublisher.publish.and.returnValue(
new Promise(resolve => (resolvePublish = resolve))
);
publisher.parsePublisher.isOpen = true;
publisher.parsePublisher.isReady = true;
publisher.parsePublisher.close = jasmine.createSpy('close').and.resolveTo();
publisher.parsePublisher.destroy = jasmine.createSpy('destroy');
publisher._onCloudCodeMessage('afterSave', { object: new Parse.Object('Test') });
const shutdown = publisher.shutdown();
await new Promise(resolve => setImmediate(resolve));
expect(publisher.parsePublisher.destroy).not.toHaveBeenCalled();
resolvePublish();
await shutdown;

expect(publisher.parsePublisher.destroy).toHaveBeenCalledTimes(1);
expect(publisher.parsePublisher.close).not.toHaveBeenCalled();
});

it('destroys a publisher that is not ready with messages in flight', async () => {
const publisher = new ParseCloudCodePublisher({});
publisher.parsePublisher.publish.and.returnValue(new Promise(() => {}));
publisher.parsePublisher.isOpen = true;
publisher.parsePublisher.isReady = false;
publisher.parsePublisher.close = jasmine.createSpy('close').and.resolveTo();
publisher.parsePublisher.destroy = jasmine.createSpy('destroy');
publisher._onCloudCodeMessage('afterSave', { object: new Parse.Object('Test') });
await publisher.shutdown();

expect(publisher.parsePublisher.destroy).toHaveBeenCalledTimes(1);
expect(publisher.parsePublisher.close).not.toHaveBeenCalled();
});

describe('with a Redis server that does not respond', () => {
let server;
let sockets;
let client;
let connectionCount;
let replyToHandshake;

// Starts a server that completes the handshake of the Redis client and never replies to
// another command, and connects a Redis client to it
async function connectClient(options) {
sockets = new Set();
connectionCount = 0;
replyToHandshake = true;
server = net.createServer(socket => {
connectionCount++;
sockets.add(socket);
socket.on('close', () => sockets.delete(socket));
socket.on('error', () => {});
// A command can arrive split over several chunks, so the commands are counted on all data
// received on the connection
let received = '';
let replies = 0;
socket.on('data', data => {
received += data.toString();
const handshakeCommands = (received.match(/SETINFO/g) || []).length;
if (replyToHandshake) {
socket.write('+OK\r\n'.repeat(handshakeCommands - replies));
replies = handshakeCommands;
}
});
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
client = createClient({ url: `redis://127.0.0.1:${server.address().port}`, ...options });
client.on('error', () => {});
await client.connect();
}

afterEach(async () => {
if (client?.isOpen) {
client.destroy();
}
sockets.forEach(socket => socket.destroy());
await new Promise(resolve => server.close(resolve));
});

it('destroys the connection with a message in flight', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error');
await connectClient();
const publisher = new ParseCloudCodePublisher({});
publisher.parsePublisher = client;
publisher._onCloudCodeMessage('afterSave', { object: new Parse.Object('Test') });
expect(sockets.size).toBe(1);
await publisher.shutdown();
await new Promise(resolve => setTimeout(resolve, 100));

expect(client.isOpen).toBeFalse();
expect(sockets.size).toBe(0);
expect(loggerErrorSpy).toHaveBeenCalledWith('LiveQuery publisher error', {
error: jasmine.any(Error),
});
});

it('destroys the connection with a ping in flight', async () => {
await connectClient({ pingInterval: 10 });
const publisher = new ParseCloudCodePublisher({});
publisher.parsePublisher = client;
// Wait for the client to send a ping
await new Promise(resolve => setTimeout(resolve, 100));
expect(sockets.size).toBe(1);
await publisher.shutdown();
await new Promise(resolve => setTimeout(resolve, 100));

expect(client.isOpen).toBeFalse();
expect(sockets.size).toBe(0);
});

it('destroys the connection with a reconnect handshake in flight', async () => {
await connectClient();
const publisher = new ParseCloudCodePublisher({});
publisher.parsePublisher = client;
// Drop the connection and leave the handshake of the reconnection without a reply
replyToHandshake = false;
sockets.forEach(socket => socket.destroy());
while (connectionCount < 2 || sockets.size !== 1) {
await new Promise(resolve => setTimeout(resolve, 10));
}
await new Promise(resolve => setTimeout(resolve, 50));
expect(client.isOpen).toBeTrue();
expect(client.isReady).toBeFalse();
expect(publisher.pendingMessages.size).toBe(0);
await publisher.shutdown();
await new Promise(resolve => setTimeout(resolve, 100));

expect(client.isOpen).toBeFalse();
expect(sockets.size).toBe(0);
});
});

it('does not close a publisher that is not open', async () => {
const publisher = new ParseCloudCodePublisher({});
publisher.parsePublisher.isOpen = false;
publisher.parsePublisher.close = jasmine.createSpy('close').and.resolveTo();
await publisher.shutdown();

expect(publisher.parsePublisher.close).not.toHaveBeenCalled();
});

it('can shutdown a publisher without connection', async () => {
const publisher = new ParseCloudCodePublisher({});

await expectAsync(publisher.shutdown()).toBeResolved();
});

it('logs an error if the publisher fails to close', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error');
const publisher = new ParseCloudCodePublisher({});
const error = new Error('close failed');
publisher.parsePublisher.isOpen = true;
publisher.parsePublisher.close = jasmine.createSpy('close').and.rejectWith(error);

await expectAsync(publisher.shutdown()).toBeResolved();
expect(loggerErrorSpy).toHaveBeenCalledWith('LiveQuery publisher error on shutdown', { error });
});

afterEach(function () {
jasmine.restoreLibrary('../lib/LiveQuery/ParsePubSub', 'ParsePubSub');
});
Expand Down
29 changes: 29 additions & 0 deletions spec/ParseLiveQueryRedis.spec.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const ParseServer = require('../lib/index').ParseServer;

if (process.env.PARSE_SERVER_TEST_CACHE === 'redis') {
describe('ParseLiveQuery redis', () => {
afterEach(async () => {
Expand Down Expand Up @@ -54,5 +56,32 @@ if (process.env.PARSE_SERVER_TEST_CACHE === 'redis') {
await server.liveQueryServer.connect();
expect(server.liveQueryServer.subscriber.isOpen).toBe(true);
});

it('closes the publisher on shutdown', async () => {
await reconfigureServer({ appId: 'test_app_id' });
// The server under test uses the test database, with its own adapter instance to shut down
const server = await ParseServer.startApp({
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
appId: 'redis_live_query_shutdown',
masterKey: 'world',
port: 1347,
mountPath: '/1',
serverURL: 'http://localhost:1347/1',
databaseAdapter: new databaseAdapter.constructor({
uri: databaseURI,
collectionPrefix: 'test_',
}),
filesAdapter: defaultConfiguration.filesAdapter,
liveQuery: {
classNames: ['TestObject'],
redisURL: 'redis://localhost:6379',
},
verbose: false,
silent: true,
});
const publisher = server.config.liveQueryController.liveQueryPublisher.parsePublisher;
expect(publisher.isOpen).toBeTrue();
await server.handleShutdown();
expect(publisher.isOpen).toBeFalse();
});
});
}
19 changes: 19 additions & 0 deletions spec/RedisCacheAdapter.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,25 @@ describe_only(() => {
expect(cache.client.isOpen).toBe(false);
}, 0);
});

it('handleShutdown can be called more than once', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
await cache.handleShutdown();
await cache.handleShutdown();

expect(cache.client.isOpen).toBe(false);
expect(loggerErrorSpy).not.toHaveBeenCalled();
});

it('handleShutdown does not close a client that is not connected', async () => {
const logger = require('../lib/logger').default;
const loggerErrorSpy = spyOn(logger, 'error').and.callThrough();
const notConnectedCache = new RedisCacheAdapter(null, 100);
await notConnectedCache.handleShutdown();

expect(loggerErrorSpy).not.toHaveBeenCalled();
});
});

describe_only(() => {
Expand Down
3 changes: 2 additions & 1 deletion src/Adapters/Cache/RedisCacheAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export class RedisCacheAdapter {
}

async handleShutdown() {
if (!this.client) {
// Closing a client that is not open, e.g. never connected or already closed, throws
if (!this.client?.isOpen) {
return;
}
try {
Expand Down
4 changes: 4 additions & 0 deletions src/Controllers/LiveQueryController.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ export class LiveQueryController {
return this.liveQueryPublisher.connect();
}

shutdown() {
return this.liveQueryPublisher.shutdown();
}

onAfterSave(
className: string,
currentObject: any,
Expand Down
Loading