diff --git a/spec/MongoStorageAdapter.spec.js b/spec/MongoStorageAdapter.spec.js index b17bba9a67..c29951f31a 100644 --- a/spec/MongoStorageAdapter.spec.js +++ b/spec/MongoStorageAdapter.spec.js @@ -1,7 +1,7 @@ 'use strict'; const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; -const { MongoClient, Collection } = require('mongodb'); +const { MongoClient, Collection, MongoOperationTimeoutError } = require('mongodb'); const databaseURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; const request = require('../lib/request'); const Config = require('../lib/Config'); @@ -410,6 +410,74 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { ).toBeRejectedWith(jasmine.is(error)); }); + it('handleShutdown closes the schema change stream before the client', async () => { + const adapter = new MongoStorageAdapter({ + uri: databaseURI, + mongoOptions: { enableSchemaHooks: true }, + }); + adapter.watch(() => {}); + await adapter._schemaCollection(); + expect(adapter._stream).toBeDefined(); + const stream = adapter._stream; + const closeOrder = []; + spyOn(stream, 'close').and.callFake(async () => closeOrder.push('stream')); + const clientClose = adapter.client.close.bind(adapter.client); + spyOn(adapter.client, 'close').and.callFake(async force => { + closeOrder.push('client'); + return clientClose(force); + }); + + await adapter.handleShutdown(); + + expect(closeOrder).toEqual(['stream', 'client']); + expect(adapter._stream).toBeUndefined(); + }); + + it('re-establishes the schema change stream after it failed', async () => { + const adapter = new MongoStorageAdapter({ + uri: databaseURI, + mongoOptions: { enableSchemaHooks: true }, + }); + const onChange = jasmine.createSpy('onChange'); + adapter.watch(onChange); + await adapter._schemaCollection(); + const stream = adapter._stream; + expect(stream).toBeDefined(); + stream.emit('change'); + expect(onChange).toHaveBeenCalledTimes(1); + stream.emit('error', new Error('simulated non-resumable change stream error')); + expect(adapter._stream).toBeUndefined(); + await adapter._schemaCollection(); + expect(adapter._stream).toBeDefined(); + expect(adapter._stream).not.toBe(stream); + await adapter.handleShutdown(); + await stream.close().catch(() => {}); + }); + + it('keeps the schema change stream after a recoverable timeout error', async () => { + const adapter = new MongoStorageAdapter({ + uri: databaseURI, + mongoOptions: { enableSchemaHooks: true }, + }); + const onChange = jasmine.createSpy('onChange'); + adapter.watch(onChange); + await adapter._schemaCollection(); + const stream = adapter._stream; + expect(stream).toBeDefined(); + const logger = require('../lib/logger').logger; + spyOn(logger, 'error').and.callFake(() => {}); + // The driver resumes the stream and emits the timeout error while the stream stays open + stream.emit('error', new MongoOperationTimeoutError('simulated timeout')); + expect(logger.error).toHaveBeenCalledWith('Schema change stream error', jasmine.any(Error)); + expect(adapter._stream).toBe(stream); + expect(stream.closed).toBe(false); + await adapter._schemaCollection(); + expect(adapter._stream).toBe(stream); + stream.emit('change'); + expect(onChange).toHaveBeenCalledTimes(1); + await adapter.handleShutdown(); + }); + it('handleShutdown, close connection', async () => { const adapter = new MongoStorageAdapter({ uri: databaseURI }); diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index 1450522579..736605aa70 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -42,6 +42,50 @@ describe('Server Url Checks', () => { ); }); + it('aborts the server url verification while the server does not respond', async () => { + const net = require('net'); + const sockets = []; + const silentServer = net.createServer(socket => sockets.push(socket)); + await new Promise(resolve => silentServer.listen(0, resolve)); + Parse.serverURL = `http://localhost:${silentServer.address().port}`; + spyOn(console, 'warn').and.callFake(() => {}); + const controller = new AbortController(); + const verification = ParseServer.verifyServerUrl(controller.signal); + await new Promise(resolve => silentServer.once('connection', resolve)); + const started = Date.now(); + controller.abort(); + expect(await verification).toBeUndefined(); + expect(Date.now() - started).toBeLessThan(500); + expect(console.warn).not.toHaveBeenCalled(); + sockets.forEach(socket => socket.destroy()); + await new Promise(resolve => silentServer.close(resolve)); + }); + + it('aborts the server url verification while waiting to retry', async () => { + const app = express(); + let requests = 0; + app.get('/health', (req, res) => { + requests += 1; + res.set('Retry-After', '1').status(503).json({ status: 'starting' }); + }); + const startingServer = await new Promise(resolve => { + const httpServer = app.listen(0, () => resolve(httpServer)); + }); + Parse.serverURL = `http://localhost:${startingServer.address().port}`; + spyOn(console, 'warn').and.callFake(() => {}); + const controller = new AbortController(); + const verification = ParseServer.verifyServerUrl(controller.signal); + await new Promise(resolve => startingServer.once('request', resolve)); + await new Promise(resolve => setTimeout(resolve, 100)); + const started = Date.now(); + controller.abort(); + expect(await verification).toBeUndefined(); + expect(Date.now() - started).toBeLessThan(500); + expect(requests).toBe(1); + expect(console.warn).not.toHaveBeenCalled(); + await new Promise(resolve => startingServer.close(resolve)); + }); + it('does not have unhandled promise rejection in the case of load error', done => { const parseServerProcess = spawn(path.resolve(__dirname, './support/FailingServer.js')); let stdout; @@ -61,3 +105,442 @@ describe('Server Url Checks', () => { }); }); }); + +describe('graceful shutdown', () => { + const request = require('../lib/request'); + const triggers = require('../lib/triggers'); + const { sleep } = require('../lib/TestUtils'); + const { GridFSBucketAdapter } = require('../lib/Adapters/Files/GridFSBucketAdapter'); + const http = require('http'); + const net = require('net'); + const port = 13377; + const appId = 'lifecycle_test'; + const masterKey = 'lifecycle_test_master'; + const headers = { + 'X-Parse-Application-Id': appId, + 'X-Parse-Master-Key': masterKey, + 'Content-Type': 'application/json', + }; + let server; + + const makeConfig = options => { + const config = Object.assign( + {}, + defaultConfiguration, + { + appId, + masterKey, + port, + mountPath: '/1', + serverURL: `http://localhost:${port}/1`, + silent: true, + verbose: false, + }, + options + ); + // Own adapters against the test database so that shutting them down does not affect the + // shared test server and the data is cleaned up with the other test collections + config.databaseAdapter = new databaseAdapter.constructor({ + uri: databaseURI, + collectionPrefix: 'test_', + }); + config.filesAdapter = + process.env.PARSE_SERVER_TEST_DB === 'postgres' + ? defaultConfiguration.filesAdapter + : new GridFSBucketAdapter(databaseURI); + return config; + }; + + // Every check uses a fresh connection so that pooled keep-alive sockets do not mask the server state + const freshAgent = () => new http.Agent({ keepAlive: false }); + const health = () => + request({ url: `http://localhost:${port}/1/health`, json: true, headers, agent: freshAgent() }).catch( + e => e + ); + const createObject = () => + request({ + method: 'POST', + url: `http://localhost:${port}/1/classes/LifecycleTest`, + json: true, + headers, + body: { foo: 'bar' }, + agent: freshAgent(), + }).catch(e => e); + const callSlowFunction = () => + request({ + method: 'POST', + url: `http://localhost:${port}/1/functions/slow`, + json: true, + headers, + body: {}, + agent: new http.Agent({ keepAlive: true }), + }).catch(e => e); + + // Opens a raw keep-alive connection, performs one request and leaves the connection idle. + // Records whether the server later ends it cleanly (FIN) or resets it (RST). + const openIdleConnection = () => + new Promise(resolve => { + const socket = net.connect(port, 'localhost'); + const state = { socket, ended: false, errors: [], closed: null }; + socket.on('end', () => (state.ended = true)); + socket.on('error', error => state.errors.push(error.code || error.message)); + state.closed = new Promise(res => socket.on('close', hadError => res(hadError))); + socket.once('connect', () => { + socket.write( + `GET /1/health HTTP/1.1\r\nHost: localhost\r\nX-Parse-Application-Id: ${appId}\r\nConnection: keep-alive\r\n\r\n` + ); + }); + socket.once('data', data => { + expect(data.toString()).toMatch(/^HTTP\/1\.1 200/); + resolve(state); + }); + }); + + afterEach(async () => { + triggers.removeFunction('slow', appId); + const current = server; + server = undefined; + let shutdownError; + try { + await current?.handleShutdown(); + } catch (error) { + shutdownError = error; + } + // Restore the shared test server even if the shutdown failed, so that the failure does not + // cascade into the following specs; report both errors if the restoration fails as well + try { + await reconfigureServer(); + } catch (error) { + throw shutdownError + ? new AggregateError([shutdownError, error], 'Shutdown and restoration failed') + : error; + } + if (shutdownError) { + throw shutdownError; + } + }); + + it('transitions through initialized, starting, ok, draining and closed without resetting connections', async () => { + const events = []; + const mark = name => events.push({ name, at: Date.now() }); + const config = makeConfig({ + shutdownDrainDelay: 1000, + shutdownTimeout: 2000, + serverCloseComplete: () => mark('serverCloseComplete'), + }); + + // Parse Server mounted into an Express app that owns the HTTP server + const api = new ParseServer(config); + const app = express(); + app.use('/1', api.app); + api.server = await new Promise(resolve => { + const httpServer = app.listen(port, () => resolve(httpServer)); + }); + server = api; + // The in-flight requests stay in flight until the server has stopped accepting connections, so + // that they are completed by the shutdown timeout phase and not already by the drain phase + triggers.addFunction( + 'slow', + async () => { + while (api.server.listening) { + await sleep(20); + } + return 'done'; + }, + null, + appId + ); + const databaseAdapter = api.config.databaseController.adapter; + const originalDatabaseShutdown = databaseAdapter.handleShutdown; + spyOn(databaseAdapter, 'handleShutdown').and.callFake(function () { + mark('databaseAdapter.handleShutdown'); + return originalDatabaseShutdown.apply(this, arguments); + }); + // Initialization is held back until released so that the starting state can be observed + let releaseInitialization; + const initializationGate = new Promise(resolve => (releaseInitialization = resolve)); + const databaseController = api.config.databaseController; + const originalInitialization = databaseController.performInitialization; + spyOn(databaseController, 'performInitialization').and.callFake(async function () { + await initializationGate; + return originalInitialization.apply(this, arguments); + }); + + // 1. Constructed but not started: health reports the state, API requests are rejected + let response = await health(); + expect(response.status).toBe(503); + expect(response.data.status).toBe('initialized'); + response = await createObject(); + expect(response.status).toBe(500); + expect(response.data.error).toBe('Invalid server state: initialized'); + + // 2. Starting: health asks the client to retry + const starting = api.start(); + try { + response = await health(); + expect(response.status).toBe(503); + expect(response.data.status).toBe('starting'); + expect(response.headers['retry-after']).toBe('1'); + } finally { + // Always released, otherwise a failed probe would block the start and the cleanup + releaseInitialization(); + } + await starting; + + // 3. Ready: health is ok and requests are served + response = await health(); + expect(response.status).toBe(200); + expect(response.data.status).toBe('ok'); + expect(response.headers['retry-after']).toBeUndefined(); + response = await createObject(); + expect(response.status).toBe(201); + expect(response.data.objectId).toBeDefined(); + + // 4. Open connections that must survive the shutdown: idle keep-alive connections and in-flight requests + const idleConnections = await Promise.all([openIdleConnection(), openIdleConnection(), openIdleConnection()]); + const inFlight = [callSlowFunction(), callSlowFunction()]; + await sleep(50); + + // 5. Draining: health fails so that load balancers stop routing here, but requests are still served + const shutdown = api.handleShutdown(); + response = await health(); + expect(response.status).toBe(503); + expect(response.data.status).toBe('draining'); + expect(response.headers['retry-after']).toBeUndefined(); + response = await createObject(); + expect(response.status).toBe(201); + + // 6. In-flight requests complete and idle connections are ended with FIN, not reset + const results = await Promise.all(inFlight); + mark('inFlightCompleted'); + for (const result of results) { + expect(result.status).toBe(200); + expect(result.data.result).toBe('done'); + } + await shutdown; + for (const connection of idleConnections) { + expect(await connection.closed).toBe(false, 'idle connection was closed with an error'); + expect(connection.ended).toBe(true, 'idle connection did not receive FIN'); + expect(connection.errors).toEqual([]); + } + + // 7. Adapters are shut down only after the in-flight requests completed, completion callback runs last + const at = name => events.find(e => e.name === name)?.at; + expect(at('databaseAdapter.handleShutdown')).toBeGreaterThanOrEqual(at('inFlightCompleted')); + expect(at('serverCloseComplete')).toBeGreaterThanOrEqual(at('databaseAdapter.handleShutdown')); + expect(events.filter(e => e.name === 'serverCloseComplete').length).toBe(1); + + // 8. Closed: nothing listens anymore, repeated shutdown is a no-op + response = await health(); + expect(response.status).toBeUndefined(); + expect(response.code).toBe('ECONNREFUSED'); + expect(api.handleShutdown()).toBe(shutdown); + await api.handleShutdown(); + expect(events.filter(e => e.name === 'serverCloseComplete').length).toBe(1); + expect(api.config.state).toBe('closed'); + }); + + it('closes LiveQuery clients during the drain instead of waiting for the shutdown timeout', async () => { + const liveQueryPort = port + 1; + server = await ParseServer.startApp( + makeConfig({ + liveQuery: { classNames: ['LifecycleTest'] }, + startLiveQueryServer: true, + liveQueryServerOptions: { port: liveQueryPort }, + shutdownTimeout: 5000, + }) + ); + // A dedicated client, the shared default client must stay connected to the test server + const client = new Parse.LiveQueryClient({ + applicationId: appId, + serverURL: `ws://localhost:${liveQueryPort}/1`, + javascriptKey: defaultConfiguration.javascriptKey, + }); + client.open(); + const subscription = client.subscribe(new Parse.Query('LifecycleTest')); + await new Promise(resolve => subscription.on('open', resolve)); + const closed = new Promise(resolve => subscription.on('close', resolve)); + const started = Date.now(); + await server.handleShutdown(); + await closed; + // The open WebSocket must not keep the servers open for the whole timeout + expect(Date.now() - started).toBeLessThan(2500); + client.close(); + }); + + it('does not wait for an unresponsive LiveQuery shutdown before shutting down the adapters', async () => { + let closeCompleteCalls = 0; + server = await ParseServer.startApp( + makeConfig({ + liveQuery: { classNames: ['LifecycleTest'] }, + startLiveQueryServer: true, + serverCloseComplete: () => (closeCompleteCalls += 1), + }) + ); + // The pub/sub adapter never settles, as with an unreachable Redis server + const liveQueryServer = server.liveQueryServer; + const liveQueryShutdown = liveQueryServer.shutdown; + spyOn(liveQueryServer, 'shutdown').and.returnValue(new Promise(() => {})); + spyOn(console, 'error').and.callFake(() => {}); + const started = Date.now(); + let error; + await server.handleShutdown().catch(e => (error = e)); + expect(Date.now() - started).toBeLessThan(2500); + expect(error.errors.map(e => e.message)).toEqual([ + 'The LiveQuery server did not shut down in time', + ]); + // The remaining steps ran regardless + expect(server.config.state).toBe('closed'); + expect(closeCompleteCalls).toBe(1); + expect((await health()).code).toBe('ECONNREFUSED'); + server = undefined; + // Unsubscribe the LiveQuery server from the shared pub/sub emitter so it does not outlive the spec + await liveQueryShutdown.call(liveQueryServer); + }); + + it('runs every shutdown step and rejects with the collected errors', async () => { + let closeCompleteCalls = 0; + server = await ParseServer.startApp( + makeConfig({ serverCloseComplete: () => (closeCompleteCalls += 1) }) + ); + const databaseAdapter = server.config.databaseController.adapter; + const originalDatabaseShutdown = databaseAdapter.handleShutdown; + spyOn(databaseAdapter, 'handleShutdown').and.callFake(async function () { + await originalDatabaseShutdown.apply(this, arguments); + throw new Error('database adapter shutdown failed'); + }); + spyOn(console, 'error').and.callFake(() => {}); + + await expectAsync(server.handleShutdown()).toBeRejectedWithError( + /Parse Server shutdown completed with errors/ + ); + let error; + await server.handleShutdown().catch(e => (error = e)); + expect(error.errors.map(e => e.message)).toEqual(['database adapter shutdown failed']); + // The remaining steps ran regardless of the failure + expect(server.config.state).toBe('closed'); + expect(closeCompleteCalls).toBe(1); + expect((await health()).code).toBe('ECONNREFUSED'); + // Already shut down; afterEach must not await the rejected promise again + server = undefined; + }); + + it('warns when there is no HTTP server to close', async () => { + const api = new ParseServer(makeConfig()); + server = api; + await api.start(); + const logger = require('../lib/logger').logger; + spyOn(logger, 'warn').and.callFake(() => {}); + await api.handleShutdown(); + expect(logger.warn).toHaveBeenCalledWith(jasmine.stringMatching(/no HTTP server to close/)); + expect(api.config.state).toBe('closed'); + }); + + it('does not drain or serve requests on shutdown when the server never became ready', async () => { + const api = new ParseServer(makeConfig({ shutdownDrainDelay: 1000 })); + server = api; + const app = express(); + app.use('/1', api.app); + api.server = await new Promise(resolve => { + const httpServer = app.listen(port, () => resolve(httpServer)); + }); + expect((await createObject()).status).toBe(500); + const started = Date.now(); + await api.handleShutdown(); + // No drain phase: the server was never serving, so there is nothing to drain + expect(Date.now() - started).toBeLessThan(1000); + expect(api.config.state).toBe('closed'); + expect((await health()).code).toBe('ECONNREFUSED'); + }); + + it('rejects invalid shutdown options', () => { + expect(() => new ParseServer(makeConfig({ shutdownTimeout: null }))).not.toThrow(); + for (const value of ['5s', -1, 1.5, Infinity, 2147483648]) { + expect(() => new ParseServer(makeConfig({ shutdownTimeout: value }))).toThrow( + 'shutdownTimeout must be an integer between 0 and 2147483647 (milliseconds).' + ); + expect(() => new ParseServer(makeConfig({ shutdownDrainDelay: value }))).toThrow( + 'shutdownDrainDelay must be an integer between 0 and 2147483647 (milliseconds).' + ); + } + }); + + it('waits for a start in progress before shutting down', async () => { + server = new ParseServer(makeConfig()); + const starting = server.startApp(makeConfig()); + const shutdown = server.handleShutdown(); + await expectAsync(starting).toBeResolved(); + await shutdown; + expect(server.config.state).toBe('closed'); + expect((await health()).code).toBe('ECONNREFUSED'); + }); + + it('cannot be started again once shutdown has been requested', async () => { + const api = new ParseServer(makeConfig()); + server = api; + await api.start(); + const shutdown = api.handleShutdown(); + await expectAsync(api.start()).toBeRejectedWithError(/cannot be started after handleShutdown/); + await shutdown; + await expectAsync(api.start()).toBeRejectedWithError(/cannot be started after handleShutdown/); + await expectAsync(api.startApp(makeConfig())).toBeRejectedWithError( + /cannot be started after handleShutdown/ + ); + }); + + it('waits for every startup operation to settle before failing to start', async () => { + const { InMemoryCacheAdapter } = require('../lib/Adapters/Cache/InMemoryCacheAdapter'); + const cacheAdapter = new InMemoryCacheAdapter({ ttl: 5000, maxSize: 100 }); + let cacheSettled = false; + cacheAdapter.connect = async () => { + await sleep(300); + cacheSettled = true; + throw new Error('cache unavailable'); + }; + const api = new ParseServer(makeConfig({ cacheAdapter })); + server = api; + spyOn(api.config.liveQueryController, 'connect').and.rejectWith( + new Error('LiveQuery unavailable') + ); + spyOn(console, 'error').and.callFake(() => {}); + // The first failure is reported, but only once the cache adapter connection has settled as well + await expectAsync(api.start()).toBeRejectedWithError('LiveQuery unavailable'); + expect(cacheSettled).toBe(true); + expect(api.config.state).toBe('error'); + }); + + it('destroys in-flight connections once the shutdown timeout expires', async () => { + server = await ParseServer.startApp(makeConfig({ shutdownTimeout: 200 })); + let handlerStarted; + const handlerRunning = new Promise(resolve => (handlerStarted = resolve)); + triggers.addFunction( + 'slow', + async () => { + handlerStarted(); + await sleep(2000); + return 'done'; + }, + null, + appId + ); + const inFlight = callSlowFunction(); + await handlerRunning; + + const started = Date.now(); + const shutdown = server.handleShutdown(); + // The connection is not reset before the timeout expires + const early = await Promise.race([ + inFlight.then(() => 'settled'), + sleep(150).then(() => 'pending'), + ]); + expect(early).toBe('pending'); + await shutdown; + const elapsed = Date.now() - started; + expect(elapsed).toBeGreaterThanOrEqual(190); + expect(elapsed).toBeLessThan(1500); + + const error = await inFlight; + expect(error.status).toBeUndefined(); + expect(error.code).toBe('ECONNRESET'); + }); +}); diff --git a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js index 8d4c0bd753..ff45800cfe 100644 --- a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js +++ b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js @@ -164,6 +164,7 @@ export class MongoStorageAdapter implements StorageAdapter { _mongoOptions: Object; _onchange: any; _stream: any; + _shuttingDown: boolean; _logClientEvents: ?Array; _clientMetadata: ?{ name: string, version: string }; // Public @@ -211,6 +212,8 @@ export class MongoStorageAdapter implements StorageAdapter { if (this.connectionPromise) { return this.connectionPromise; } + // A new client re-enables the schema change stream after a previous shutdown + this._shuttingDown = false; // parsing and re-formatting causes the auth value (if there) to get URI // encoded @@ -300,6 +303,15 @@ export class MongoStorageAdapter implements StorageAdapter { if (!this.client) { return; } + // No change stream is opened on the closing client by a concurrent _schemaCollection() + this._shuttingDown = true; + // Close the schema change stream before the client, otherwise closing the client + // interrupts the stream's checked-out connection and emits an unhandled error + const stream = this._stream; + this._stream = undefined; + if (stream) { + await stream.close().catch(() => {}); + } await this.client.close(false); delete this.connectionPromise; } @@ -315,9 +327,25 @@ export class MongoStorageAdapter implements StorageAdapter { return this.connect() .then(() => this._adaptiveCollection(MongoSchemaCollectionName)) .then(collection => { - if (!this._stream && this.enableSchemaHooks) { - this._stream = collection._mongoCollection.watch(); - this._stream.on('change', () => this._onchange()); + if (!this._stream && this.enableSchemaHooks && !this._shuttingDown) { + const stream = collection._mongoCollection.watch(); + this._stream = stream; + stream.on('change', () => this._onchange()); + // The driver resumes the stream on resumable errors by itself and only emits 'error' when + // the stream is lost for good, or when an operation timed out (`timeoutMS`), in which case + // it resumes the stream as well and keeps it open. An unhandled 'error' event would + // terminate the process; log it instead, keep a stream that is still open and forget a + // lost stream so that the next schema access re-establishes the watch. + stream.on('error', error => { + logger.error('Schema change stream error', error); + if (error instanceof mongodb.MongoOperationTimeoutError && !stream.closed) { + return; + } + if (this._stream === stream) { + this._stream = undefined; + } + stream.close().catch(() => {}); + }); } return new MongoSchemaCollection(collection); }); diff --git a/src/Config.js b/src/Config.js index f562e1da24..ef50fad8f8 100644 --- a/src/Config.js +++ b/src/Config.js @@ -85,13 +85,13 @@ export class Config { }) ); + // Update the cached config in place: ParseServer and the health endpoint keep a reference to + // the cached object, replacing it would detach them from later state changes const cachedConfig = AppCache.get(this.appId); if (cachedConfig) { - const updatedConfig = { ...cachedConfig }; asyncKeys.forEach(key => { - updatedConfig[key] = this[key]; + cachedConfig[key] = this[key]; }); - AppCache.put(this.appId, updatedConfig); } } @@ -119,6 +119,8 @@ export class Config { } static validateOptions({ + shutdownDrainDelay, + shutdownTimeout, customPages, publicServerURL, revokeSessionOnPasswordReset, @@ -186,6 +188,7 @@ export class Config { this.validateIps('maintenanceKeyIps', maintenanceKeyIps); this.validateIps('readOnlyMasterKeyIps', readOnlyMasterKeyIps); this.validateDefaultLimit(defaultLimit); + this.validateShutdownOptions(shutdownDrainDelay, shutdownTimeout); this.validateMaxLimit(maxLimit); this.validateAllowHeaders(allowHeaders); this.validateIdempotencyOptions(idempotencyOptions); @@ -671,6 +674,21 @@ export class Config { } } + static validateShutdownOptions(shutdownDrainDelay, shutdownTimeout) { + for (const [name, value] of [ + ['shutdownDrainDelay', shutdownDrainDelay], + ['shutdownTimeout', shutdownTimeout], + ]) { + if (value == null) { + continue; + } + // Upper bound is the largest delay setTimeout supports + if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 2147483647) { + throw `${name} must be an integer between 0 and 2147483647 (milliseconds).`; + } + } + } + static validateDefaultLimit(defaultLimit) { if (defaultLimit == null) { defaultLimit = ParseServerOptions.defaultLimit.default; diff --git a/src/Options/Definitions.js b/src/Options/Definitions.js index dba161ec44..2d1c0e8ff8 100644 --- a/src/Options/Definitions.js +++ b/src/Options/Definitions.js @@ -638,6 +638,18 @@ module.exports.ParseServerOptions = { action: parsers.numberParser('sessionLength'), default: 31536000, }, + shutdownDrainDelay: { + env: 'PARSE_SERVER_SHUTDOWN_DRAIN_DELAY', + help: 'Delay in milliseconds between the start of a shutdown via `handleShutdown()` and the moment Parse Server stops accepting new connections.

During this delay the health endpoint responds with HTTP status `503` and `{"status":"draining"}` while all other requests are still served normally. This allows load balancers and orchestrators, for example Kubernetes via a readiness probe on the health endpoint, to stop routing new traffic to this instance before it closes. Set this to a value larger than the time it takes for the routing layer to detect the failing health check.

Defaults to `0`, which stops accepting new connections immediately.', + action: parsers.numberParser('shutdownDrainDelay'), + default: 0, + }, + shutdownTimeout: { + env: 'PARSE_SERVER_SHUTDOWN_TIMEOUT', + help: 'Maximum time in milliseconds to wait for in-flight requests to complete after Parse Server has stopped accepting new connections during a shutdown via `handleShutdown()`.

Idle keep-alive connections are closed immediately. Connections with a request in progress are given until this timeout expires and are destroyed afterwards.

Defaults to `0`, which destroys all open connections immediately.', + action: parsers.numberParser('shutdownTimeout'), + default: 0, + }, silent: { env: 'SILENT', help: 'Disables console output', diff --git a/src/Options/docs.js b/src/Options/docs.js index 53026db1b0..a1c2ecbafc 100644 --- a/src/Options/docs.js +++ b/src/Options/docs.js @@ -115,6 +115,8 @@ * @property {Function} serverCloseComplete Callback when server has closed * @property {String} serverURL The URL to Parse Server.

⚠️ Certain server features or adapters may require Parse Server to be able to call itself by making requests to the URL set in `serverURL`. If a feature requires this, it is mentioned in the documentation. In that case ensure that the URL is accessible from the server itself. * @property {Number} sessionLength Session duration, in seconds, defaults to 1 year + * @property {Number} shutdownDrainDelay Delay in milliseconds between the start of a shutdown via `handleShutdown()` and the moment Parse Server stops accepting new connections.

During this delay the health endpoint responds with HTTP status `503` and `{"status":"draining"}` while all other requests are still served normally. This allows load balancers and orchestrators, for example Kubernetes via a readiness probe on the health endpoint, to stop routing new traffic to this instance before it closes. Set this to a value larger than the time it takes for the routing layer to detect the failing health check.

Defaults to `0`, which stops accepting new connections immediately. + * @property {Number} shutdownTimeout Maximum time in milliseconds to wait for in-flight requests to complete after Parse Server has stopped accepting new connections during a shutdown via `handleShutdown()`.

Idle keep-alive connections are closed immediately. Connections with a request in progress are given until this timeout expires and are destroyed afterwards.

Defaults to `0`, which destroys all open connections immediately. * @property {Boolean} silent Disables console output * @property {Boolean} startLiveQueryServer Starts a LiveQuery server alongside this Parse Server. Events are only delivered for the classes set in `liveQuery.classNames`, so a minimal working setup is `liveQuery: { classNames: [...] }` together with `startLiveQueryServer: true`. * @property {Any} trustProxy The trust proxy settings. It is important to understand the exact setup of the reverse proxy, since this setting will trust values provided in the Parse Server API request. See the express trust proxy settings documentation. Defaults to `false`. diff --git a/src/Options/index.js b/src/Options/index.js index cd790760c5..1bf67b8625 100644 --- a/src/Options/index.js +++ b/src/Options/index.js @@ -395,6 +395,12 @@ export interface ParseServerOptions { schema: ?SchemaOptions; /* Callback when server has closed */ serverCloseComplete: ?() => void; + /* Delay in milliseconds between the start of a shutdown via `handleShutdown()` and the moment Parse Server stops accepting new connections.

During this delay the health endpoint responds with HTTP status `503` and `{"status":"draining"}` while all other requests are still served normally. This allows load balancers and orchestrators, for example Kubernetes via a readiness probe on the health endpoint, to stop routing new traffic to this instance before it closes. Set this to a value larger than the time it takes for the routing layer to detect the failing health check.

Defaults to `0`, which stops accepting new connections immediately. + :DEFAULT: 0 */ + shutdownDrainDelay: ?number; + /* Maximum time in milliseconds to wait for in-flight requests to complete after Parse Server has stopped accepting new connections during a shutdown via `handleShutdown()`.

Idle keep-alive connections are closed immediately. Connections with a request in progress are given until this timeout expires and are destroyed afterwards.

Defaults to `0`, which destroys all open connections immediately. + :DEFAULT: 0 */ + shutdownTimeout: ?number; /* Options to limit the complexity of requests to prevent denial-of-service attacks. Limits are enforced for all requests except those using the master or maintenance key. Each property can be set to `-1` to disable that specific limit. :ENV: PARSE_SERVER_REQUEST_COMPLEXITY :DEFAULT: {} */ diff --git a/src/ParseServer.ts b/src/ParseServer.ts index 65d537ae68..36cae212fb 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -45,22 +45,26 @@ import CheckRunner from './Security/CheckRunner'; import Deprecator from './Deprecator/Deprecator'; import { DefinedSchemas } from './SchemaMigrations/DefinedSchemas'; import OptionsDefinitions from './Options/Definitions'; -import { resolvingPromise, Connections } from './TestUtils'; +import { Connections, sleep } from './TestUtils'; +import { constants as osConstants } from 'os'; // Mutate the Parse object to add the Cloud Code handlers addParseCloud(); -// Track connections to destroy them on shutdown -const connections = new Connections(); // ParseServer works like a constructor of an express app. // https://parseplatform.org/parse-server/api/master/ParseServerOptions.html class ParseServer { _app: any; config: any; - server: any; + _server: any; expressApp: any; liveQueryServer: any; + _connections: Connections; + _startPromise: Promise | undefined; + _startAppPromise: Promise | undefined; + _shutdownPromise: Promise | undefined; + _shutdownController: AbortController; /** * @constructor * @param {ParseServerOptions} options the parse server initialization options @@ -137,6 +141,8 @@ class ParseServer { (options as any).state = 'initialized'; this.config = Config.put(Object.assign({}, options, allControllers)); this.config.masterKeyIpsStore = new Map(); + this._connections = new Connections(); + this._shutdownController = new AbortController(); this.config.maintenanceKeyIpsStore = new Map(); this.config.readOnlyMasterKeyIpsStore = new Map(); setRegexTimeout(options.liveQuery?.regexTimeout); @@ -148,6 +154,18 @@ class ParseServer { */ async start(): Promise { + if (this._shutdownPromise) { + throw new Error('Parse Server cannot be started after handleShutdown() has been called'); + } + if (!this._startPromise) { + this._startPromise = this._start().finally(() => { + this._startPromise = undefined; + }); + } + return this._startPromise; + } + + async _start(): Promise { try { if (this.config.state === 'ok') { return this; @@ -183,7 +201,20 @@ class ParseServer { startupPromises.push(cacheController.adapter.connect()); } startupPromises.push(liveQueryController.connect()); - await Promise.all(startupPromises); + // The first failure is reported, but only once every startup operation has settled, so that + // a shutdown following the failure does not run concurrently with an operation still in + // progress, such as the cache adapter connecting + let failure; + const startup = Promise.all(startupPromises).catch(error => { + failure = { error }; + }); + await Promise.all([ + startup, + ...startupPromises.map(promise => Promise.resolve(promise).catch(() => {})), + ]); + if (failure) { + throw failure.error; + } if (cloud) { addParseCloud(); if (typeof cloud === 'function') { @@ -207,7 +238,8 @@ class ParseServer { new CheckRunner(security).run(); } this.config.state = 'ok'; - this.config = { ...this.config, ...pushController }; + // Merge in place: the express app and the health endpoint hold a reference to this object + Object.assign(this.config, pushController); Config.put(this.config); return this; } catch (error) { @@ -218,6 +250,22 @@ class ParseServer { } } + /** + * The HTTP server that serves this Parse Server. Set automatically by `startApp()`. When Parse + * Server is mounted into an existing express app, assign the server returned by `listen()` here + * so that `handleShutdown()` can drain and close it; connections are tracked from that moment on. + */ + get server() { + return this._server; + } + + set server(server: any) { + if (server && server !== this._server) { + this._connections.track(server); + } + this._server = server; + } + get app() { if (!this._app) { this._app = ParseServer.app(this.config); @@ -228,56 +276,185 @@ class ParseServer { /** * Stops the parse server, cancels any ongoing requests and closes all connections. * - * Currently, express doesn't shut down immediately after receiving SIGINT/SIGTERM - * if it has client connections that haven't timed out. - * (This is a known issue with node - https://github.com/nodejs/node/issues/2642) + * The shutdown happens in phases: + * 1. The server state is set to `draining`. The health endpoint responds with HTTP status `503` + * while all other requests are still served, so that load balancers and orchestrators can stop + * routing new traffic to this instance. This phase lasts `shutdownDrainDelay` milliseconds. + * 2. The HTTP server stops accepting new connections, LiveQuery clients are closed and idle + * keep-alive connections are closed. Requests that are still in-flight are allowed to complete + * for up to `shutdownTimeout` milliseconds, after which any remaining connections are destroyed. + * 3. The database, file and cache adapters are shut down, the state is set to `closed` and + * `serverCloseComplete` is called. + * + * With the default option values of `0` the shutdown is immediate. + * + * If Parse Server is mounted into an existing Express app and the HTTP server is created outside + * of Parse Server, assign that HTTP server to `parseServer.server` after calling `listen()` so + * that it can be drained and closed here. + * + * Calling this method more than once returns the promise of the first call. A shutdown that is + * requested while `start()` or `startApp()` is in progress waits for the start to complete, except + * for the verification of the server URL which is aborted, and the server cannot be started again + * afterwards. Every step runs even if a previous step failed; + * the promise is rejected with an `AggregateError` of the collected errors once the shutdown has + * completed. * - * @returns {Promise} a promise that resolves when the server is stopped + * @returns {Promise} a promise that resolves once the server has shut down. */ - async handleShutdown() { - const serverClosePromise = resolvingPromise(); - const liveQueryServerClosePromise = resolvingPromise(); - const promises = []; - this.server.close((error) => { - /* istanbul ignore next */ - if (error) { + handleShutdown(): Promise { + if (!this._shutdownPromise) { + // Aborts the server URL verification of a start in progress so that it cannot delay the shutdown + this._shutdownController.abort(); + this._shutdownPromise = this._handleShutdown(); + } + return this._shutdownPromise; + } + + async _handleShutdown() { + // Both options are validated in Config.validateOptions + const drainDelay = this.config.shutdownDrainDelay || 0; + const timeout = this.config.shutdownTimeout || 0; + const errors = []; + // One failing step must not prevent the remaining steps from running + const attempt = async (step: string, fn: () => any) => { + try { + await fn(); + } catch (error) { // eslint-disable-next-line no-console - console.error('Error while closing parse server', error); + console.error(`Error during shutdown while ${step}`, error); + errors.push(error); } - serverClosePromise.resolve(); - }); + }; + const waitAtMost = async (promise: Promise, ms: number, onTimeout?: () => void) => { + let timer; + await Promise.race([ + promise, + new Promise(resolve => { + timer = setTimeout(() => { + onTimeout?.(); + resolve(); + }, ms); + }), + ]); + clearTimeout(timer); + }; + + // A shutdown that is requested while the server is starting waits for the start to complete, + // whether it succeeds or fails, so that the two never run concurrently. + const starting = this._startAppPromise || this._startPromise; + if (starting) { + await starting.catch(() => {}); + } + + // Phase 1: announce the shutdown via the health endpoint while still serving requests. A server + // that is not serving (never started, failed to start) must not start serving now. + if (this.config.state === 'ok') { + this.config.state = 'draining'; + if (drainDelay > 0) { + await sleep(drainDelay); + } + } + + // Phase 2: stop accepting new connections and let in-flight requests complete. LiveQuery + // clients are closed at the same time because their upgraded sockets keep the HTTP server open. + const servers = []; + if (this.server) { + servers.push(this.server); + } if (this.liveQueryServer?.server?.close && this.liveQueryServer.server !== this.server) { - this.liveQueryServer.server.close((error) => { - /* istanbul ignore next */ - if (error) { - // eslint-disable-next-line no-console - console.error('Error while closing live query server', error); + servers.push(this.liveQueryServer.server); + } + if (servers.length === 0) { + logging + .getLogger() + .warn( + 'Parse Server has no HTTP server to close. Assign the server returned by listen() to parseServer.server when mounting Parse Server into an existing express app.' + ); + } + const serversClosed = Promise.all( + servers.map( + server => + new Promise(resolve => { + server.close((error: any) => { + /* istanbul ignore next */ + if (error) { + // eslint-disable-next-line no-console + console.error('Error while closing server', error); + } + resolve(); + }); + }) + ) + ); + const liveQueryClosed = this.liveQueryServer + ? attempt('shutting down the LiveQuery server', () => this.liveQueryServer.shutdown()) + : Promise.resolve(); + const allClosed = Promise.all([serversClosed, liveQueryClosed]); + if (timeout > 0) { + // Keep-alive connections that become idle after their current request completes are closed + // periodically, so that the shutdown does not wait for the client to close them. + const closeIdleInterval = setInterval(() => { + for (const server of servers) { + // Not available on http2 servers + if (typeof server.closeIdleConnections === 'function') { + server.closeIdleConnections(); + } } - liveQueryServerClosePromise.resolve(); - }); - } else { - liveQueryServerClosePromise.resolve(); + }, 100); + await waitAtMost(allClosed, timeout); + clearInterval(closeIdleInterval); } - const { adapter: databaseAdapter } = this.config.databaseController; - if (databaseAdapter && typeof databaseAdapter.handleShutdown === 'function') { - promises.push(databaseAdapter.handleShutdown()); + + // Phase 3: destroy remaining connections, including upgraded WebSocket sockets that + // closeAllConnections() does not cover, then shut down the adapters. + this._connections.destroyAll(); + for (const server of servers) { + // Not available on http2 servers + if (typeof server.closeAllConnections === 'function') { + server.closeAllConnections(); + } } + // The LiveQuery teardown is bounded as well: its pub/sub adapter may never settle when the + // Redis server is unreachable. Its errors are collected by attempt(); a timeout is reported too. + await waitAtMost(liveQueryClosed, 1000, () => { + const error = new Error('The LiveQuery server did not shut down in time'); + // eslint-disable-next-line no-console + console.error('Error during shutdown while shutting down the LiveQuery server', error); + errors.push(error); + }); + // Connections opened before the server was tracked cannot be destroyed; do not wait forever. + await waitAtMost(serversClosed, 1000, /* istanbul ignore next */ () => { + logging + .getLogger() + .warn('Shutdown proceeds with connections still open; they could not be closed.'); + }); + const { adapter: databaseAdapter } = this.config.databaseController; const { adapter: fileAdapter } = this.config.filesController; - if (fileAdapter && typeof fileAdapter.handleShutdown === 'function') { - promises.push(fileAdapter.handleShutdown()); - } const { adapter: cacheAdapter } = this.config.cacheController; - if (cacheAdapter && typeof cacheAdapter.handleShutdown === 'function') { - promises.push(cacheAdapter.handleShutdown()); - } - if (this.liveQueryServer) { - promises.push(this.liveQueryServer.shutdown()); - } - await Promise.all(promises); - connections.destroyAll(); - await Promise.all([serverClosePromise, liveQueryServerClosePromise]); + await Promise.all( + [ + ['database', databaseAdapter], + ['files', fileAdapter], + ['cache', cacheAdapter], + ] + .filter(([, adapter]) => adapter && typeof adapter.handleShutdown === 'function') + .map(([name, adapter]) => + attempt(`shutting down the ${name} adapter`, () => adapter.handleShutdown()) + ) + ); + this.config.state = 'closed'; if (this.config.serverCloseComplete) { - this.config.serverCloseComplete(); + // Not awaited: the callback has always been fire-and-forget + await attempt('running serverCloseComplete', () => { + this.config.serverCloseComplete(); + }); + } + if (errors.length > 0) { + // AggregateError is not in the TypeScript lib used by this project + throw new (globalThis as any).AggregateError( + errors, + 'Parse Server shutdown completed with errors' + ); } } @@ -417,6 +594,18 @@ class ParseServer { */ async startApp(options: ParseServerOptions) { + if (this._shutdownPromise) { + throw new Error('Parse Server cannot be started after handleShutdown() has been called'); + } + if (!this._startAppPromise) { + this._startAppPromise = this._startApp(options).finally(() => { + this._startAppPromise = undefined; + }); + } + return this._startAppPromise; + } + + async _startApp(options: ParseServerOptions) { try { await this.start(); } catch (e) { @@ -470,7 +659,6 @@ class ParseServer { }); }); this.server = server; - connections.track(server); if (options.startLiveQueryServer || options.liveQueryServerOptions) { this.liveQueryServer = await ParseServer.createLiveQueryServer( @@ -479,7 +667,7 @@ class ParseServer { options ); if (this.liveQueryServer.server !== this.server) { - connections.track(this.liveQueryServer.server); + this._connections.track(this.liveQueryServer.server); } } if (options.trustProxy) { @@ -489,7 +677,7 @@ class ParseServer { if (!process.env.TESTING) { configureListeners(this); if (options.verifyServerUrl !== false) { - await ParseServer.verifyServerUrl(); + await ParseServer.verifyServerUrl(this._shutdownController.signal); } } this.expressApp = app; @@ -529,7 +717,12 @@ class ParseServer { return server; } - static async verifyServerUrl() { + /** + * Verifies that the server URL responds to a health check; retries while the server is starting. + * @param {AbortSignal} [signal] Aborts the verification, including a pending request and the wait + * before a retry, in which case the verification resolves without a result. + */ + static async verifyServerUrl(signal?: AbortSignal) { // perform a health check on the serverURL value if (Parse.serverURL) { const isValidHttpUrl = string => { @@ -551,12 +744,28 @@ class ParseServer { return; } const request = require('./request'); - const response = await request({ url }).catch(response => response); + const response = await request({ url, signal }).catch(response => response); + if (signal?.aborted) { + return; + } const json = response.data || null; const retry = response.headers?.['retry-after']; if (retry) { - await new Promise(resolve => setTimeout(resolve, retry * 1000)); - return this.verifyServerUrl(); + await new Promise(resolve => { + const onAbort = () => { + clearTimeout(timer); + resolve(); + }; + const timer = setTimeout(() => { + signal?.removeEventListener('abort', onAbort); + resolve(); + }, retry * 1000); + signal?.addEventListener('abort', onAbort, { once: true }); + }); + if (signal?.aborted) { + return; + } + return this.verifyServerUrl(signal); } if (response.status !== 200 || json?.status !== 'ok') { /* eslint-disable no-console */ @@ -677,9 +886,23 @@ function injectDefaults(options: ParseServerOptions) { // Those can't be tested as it requires a subprocess /* istanbul ignore next */ function configureListeners(parseServer) { - const handleShutdown = function () { - process.stdout.write('Termination signal received. Shutting down.'); - parseServer.handleShutdown(); + let shuttingDown = false; + const handleShutdown = function (signal) { + if (shuttingDown) { + // A second signal aborts a graceful shutdown that is still in progress + process.stdout.write('Second termination signal received. Exiting immediately.\n'); + process.exit(128 + (osConstants.signals[signal] || 15)); + } + shuttingDown = true; + process.stdout.write('Termination signal received. Shutting down.\n'); + // The flag stays set once the shutdown has started: a second signal must exit the process even + // after a shutdown that completed with errors, since handles may still be open + parseServer.handleShutdown().catch(error => { + // eslint-disable-next-line no-console + console.error('Error during shutdown', error); + // The process exits once the remaining handles are closed; report the failure in the exit status + process.exitCode = 1; + }); }; process.on('SIGTERM', handleShutdown); process.on('SIGINT', handleShutdown); diff --git a/src/middlewares.js b/src/middlewares.js index 172b2e1fd1..3e4837d3ad 100644 --- a/src/middlewares.js +++ b/src/middlewares.js @@ -216,7 +216,7 @@ export async function handleParseHeaders(req, res, next) { const clientIp = getClientIp(req); const config = req.config || Config.get(info.appId, mount); - if (config.state && config.state !== 'ok') { + if (config.state && config.state !== 'ok' && config.state !== 'draining') { res.status(500); res.json({ code: Parse.Error.INTERNAL_SERVER_ERROR, diff --git a/src/request.js b/src/request.js index d5754d9201..c654f7e0ee 100644 --- a/src/request.js +++ b/src/request.js @@ -158,6 +158,9 @@ function httpRequest(options) { if (options.agent) { requestOptions.agent = options.agent; } + if (options.signal) { + requestOptions.signal = options.signal; + } return new Promise((resolve, reject) => { const req = client.request(requestOptions, makeCallback(resolve, reject, options)); if (options.body) { diff --git a/types/Options/index.d.ts b/types/Options/index.d.ts index 2086395ff6..97b6ae23dc 100644 --- a/types/Options/index.d.ts +++ b/types/Options/index.d.ts @@ -133,6 +133,8 @@ export interface ParseServerOptions { playgroundPath?: string; schema?: SchemaOptions; serverCloseComplete?: () => void; + shutdownDrainDelay?: number; + shutdownTimeout?: number; security?: SecurityOptions; enforcePrivateUsers?: boolean; allowExpiredAuthDataToken?: boolean;