From 2fd6b050cec31e539cc99a15ae73401944c5b8e1 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Wed, 18 Nov 2026 13:23:40 +0100 Subject: [PATCH 01/14] fix: Health endpoint reports stale server state when the express app is created before `start()` `start()` replaced `this.config` with a spread copy to merge the push controller. The express app returned by the `app` getter, and with it the `/health` handler, keeps a reference to the object that existed when the app was created. When `app` is accessed before `start()`, which is a supported way of mounting Parse Server into an existing express app, any state change made after `start()` is applied to the new copy only and the health endpoint keeps reporting the old state. Merge the push controller into the existing object instead so that there is a single config object for the lifetime of the server. Co-Authored-By: Claude Fable 5.1 --- src/ParseServer.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ParseServer.ts b/src/ParseServer.ts index 65d537ae68..5e0e5eb1dd 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -207,7 +207,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) { From 406169e99f6829c13036bb45375d874995613c62 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Wed, 18 Nov 2026 13:23:40 +0100 Subject: [PATCH 02/14] feat: Add graceful shutdown with drain phase via options `shutdownDrainDelay` and `shutdownTimeout` `handleShutdown()` now shuts down in phases instead of closing the server and destroying all connections immediately: 1. The server state is set to `draining`. The `/health` endpoint responds with HTTP 503 and `{"status":"draining"}` while all other requests are still served, so that load balancers and orchestrators (e.g. a Kubernetes readiness probe) stop routing new traffic to the instance. This phase lasts `shutdownDrainDelay` ms. 2. The HTTP server stops accepting new connections and LiveQuery clients are closed, since their upgraded sockets would otherwise keep the server open. In-flight requests may complete for up to `shutdownTimeout` ms; keep-alive connections that become idle meanwhile are closed. Remaining connections, including upgraded WebSocket sockets, are destroyed when the timeout expires. 3. The database, file and cache adapters are shut down only after the HTTP server has stopped serving, so in-flight requests keep their database connection. The state is set to `closed` and `serverCloseComplete` is called last. Both options default to `0`, which keeps the previous immediate shutdown behavior, and are validated to be integers between 0 and the largest delay `setTimeout` supports. `handleShutdown()` is idempotent and returns the promise of the first call; every step runs even if a previous step failed and the promise is then rejected with an `AggregateError` of the collected errors. A shutdown requested while `start()` or `startApp()` is in progress waits for the start to complete, a server that never became ready is not drained, and the server cannot be started again afterwards. A second termination signal received by the listeners installed by `startApp()` while a shutdown is in progress exits the process immediately. The request middleware treats the `draining` state like `ok`; previously any state other than `ok` made every API request fail with HTTP 500, which made the `state` flag unusable as a readiness signal. `Config.loadKeys()` now updates the cached config in place instead of replacing it with a copy on every request, so the request middleware always observes the state of the running server. Connections are tracked per ParseServer instance instead of in a module-level singleton, so one instance's shutdown no longer resets the sockets of other instances in the same process. When Parse Server is mounted into an existing Express app, assign the HTTP server returned by `listen()` to `parseServer.server` so `handleShutdown()` can drain and close it. Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 343 +++++++++++++++++++++++++++++++++++++ src/Config.js | 24 ++- src/Options/Definitions.js | 12 ++ src/Options/docs.js | 2 + src/Options/index.js | 6 + src/ParseServer.ts | 274 +++++++++++++++++++++++------ src/middlewares.js | 2 +- types/Options/index.d.ts | 2 + 8 files changed, 613 insertions(+), 52 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index 1450522579..975babb24f 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -61,3 +61,346 @@ 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); + if (server) { + await server.handleShutdown(); + server = undefined; + } + await reconfigureServer(); + }); + + 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'), + }); + triggers.addFunction( + 'slow', + async () => { + await sleep(500); + return 'done'; + }, + null, + appId + ); + + // 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; + const databaseAdapter = api.config.databaseController.adapter; + const originalDatabaseShutdown = databaseAdapter.handleShutdown; + spyOn(databaseAdapter, 'handleShutdown').and.callFake(function () { + mark('databaseAdapter.handleShutdown'); + return originalDatabaseShutdown.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(); + response = await health(); + expect(response.status).toBe(503); + expect(response.data.status).toBe('starting'); + expect(response.headers['retry-after']).toBe('1'); + 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('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('destroys in-flight connections once the shutdown timeout expires', async () => { + server = await ParseServer.startApp(makeConfig({ shutdownTimeout: 200 })); + triggers.addFunction( + 'slow', + async () => { + await sleep(2000); + return 'done'; + }, + null, + appId + ); + const inFlight = callSlowFunction(); + await sleep(50); + + const started = Date.now(); + await server.handleShutdown(); + expect(Date.now() - started).toBeLessThan(1500); + + const error = await inFlight; + expect(error.status).toBeUndefined(); + expect(error.code).toBe('ECONNRESET'); + }); +}); 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 5e0e5eb1dd..1e9613bb5f 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -45,22 +45,25 @@ 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; /** * @constructor * @param {ParseServerOptions} options the parse server initialization options @@ -137,6 +140,7 @@ 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.config.maintenanceKeyIpsStore = new Map(); this.config.readOnlyMasterKeyIpsStore = new Map(); setRegexTimeout(options.liveQuery?.regexTimeout); @@ -148,6 +152,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; @@ -219,6 +235,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); @@ -229,56 +261,176 @@ 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, 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) { + 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 awaited in full so that its errors are collected + await liveQueryClosed; + // 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' + ); } } @@ -418,6 +570,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) { @@ -471,7 +635,6 @@ class ParseServer { }); }); this.server = server; - connections.track(server); if (options.startLiveQueryServer || options.liveQueryServerOptions) { this.liveQueryServer = await ParseServer.createLiveQueryServer( @@ -480,7 +643,7 @@ class ParseServer { options ); if (this.liveQueryServer.server !== this.server) { - connections.track(this.liveQueryServer.server); + this._connections.track(this.liveQueryServer.server); } } if (options.trustProxy) { @@ -678,9 +841,24 @@ 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'); + parseServer + .handleShutdown() + .catch(error => { + // eslint-disable-next-line no-console + console.error('Error during shutdown', error); + }) + .finally(() => { + shuttingDown = false; + }); }; 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/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; From e50fe6cb8229fa02c1e718b7378eadf7b1c65bdd Mon Sep 17 00:00:00 2001 From: Martin Man Date: Wed, 18 Nov 2026 13:56:09 +0100 Subject: [PATCH 03/14] fix: Shutdown throws unhandled `MongoClientClosedError` when option `enableSchemaHooks` is set With `enableSchemaHooks` the Mongo storage adapter keeps a change stream open on the schema collection. `handleShutdown()` closed the client while that stream still had a connection checked out, which emitted an unhandled error on the stream and terminated the process with exit code 1 instead of completing the shutdown. Close the change stream before the client, and log change stream errors instead of letting an unhandled 'error' event crash the server. Co-Authored-By: Claude Fable 5.1 --- spec/MongoStorageAdapter.spec.js | 44 +++++++++++++++++++ .../Storage/Mongo/MongoStorageAdapter.js | 28 ++++++++++-- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/spec/MongoStorageAdapter.spec.js b/spec/MongoStorageAdapter.spec.js index b17bba9a67..3310e8b5cb 100644 --- a/spec/MongoStorageAdapter.spec.js +++ b/spec/MongoStorageAdapter.spec.js @@ -410,6 +410,50 @@ 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('handleShutdown, close connection', async () => { const adapter = new MongoStorageAdapter({ uri: databaseURI }); diff --git a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js index 8d4c0bd753..cf7f418d0a 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,19 @@ 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. An unhandled 'error' event would terminate the process; + // forget the stream instead so that the next schema access re-establishes the watch. + stream.on('error', error => { + logger.error('Schema change stream error', error); + if (this._stream === stream) { + this._stream = undefined; + } + }); } return new MongoSchemaCollection(collection); }); From c18022c1fb84b31ca344b906c44940141ef4a518 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:13:03 +0100 Subject: [PATCH 04/14] test: Harden graceful shutdown specs - Restore the shared test server in afterEach even if the shutdown rejects - Keep the in-flight requests of the lifecycle spec in flight until the HTTP server has stopped accepting connections, so that they are completed by the timeout phase rather than by the drain phase - Hold the initialization back so that the starting state is observed deterministically - Assert that the shutdown timeout spec does not reset the connection before the grace period expires and that the handler is running when the shutdown begins Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 59 +++++++++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index 975babb24f..d4432e4a19 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -154,11 +154,15 @@ describe('graceful shutdown', () => { afterEach(async () => { triggers.removeFunction('slow', appId); - if (server) { - await server.handleShutdown(); - server = undefined; + const current = server; + server = undefined; + try { + await current?.handleShutdown(); + } finally { + // Restore the shared test server even if the shutdown failed, so that the failure does not + // cascade into the following specs + await reconfigureServer(); } - await reconfigureServer(); }); it('transitions through initialized, starting, ok, draining and closed without resetting connections', async () => { @@ -169,15 +173,6 @@ describe('graceful shutdown', () => { shutdownTimeout: 2000, serverCloseComplete: () => mark('serverCloseComplete'), }); - triggers.addFunction( - 'slow', - async () => { - await sleep(500); - return 'done'; - }, - null, - appId - ); // Parse Server mounted into an Express app that owns the HTTP server const api = new ParseServer(config); @@ -187,12 +182,34 @@ describe('graceful shutdown', () => { 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(); @@ -208,6 +225,7 @@ describe('graceful shutdown', () => { expect(response.status).toBe(503); expect(response.data.status).toBe('starting'); expect(response.headers['retry-after']).toBe('1'); + releaseInitialization(); await starting; // 3. Ready: health is ok and requests are served @@ -383,9 +401,12 @@ describe('graceful shutdown', () => { 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'; }, @@ -393,11 +414,17 @@ describe('graceful shutdown', () => { appId ); const inFlight = callSlowFunction(); - await sleep(50); + await handlerRunning; const started = Date.now(); - await server.handleShutdown(); - expect(Date.now() - started).toBeLessThan(1500); + 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(); From 92b9b1bd5598e94969562cedd559faeb102b3238 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:13:24 +0100 Subject: [PATCH 05/14] fix: Exit with a nonzero status when a signal-driven shutdown fails Co-Authored-By: Claude Fable 5.1 --- src/ParseServer.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ParseServer.ts b/src/ParseServer.ts index 1e9613bb5f..22f63e3010 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -855,6 +855,8 @@ function configureListeners(parseServer) { .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; }) .finally(() => { shuttingDown = false; From ae1b1e87464732ae40f9164354b48802db993361 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:16:55 +0100 Subject: [PATCH 06/14] fix: Shutdown requested during `startApp()` waits for the server URL verification The server URL verification runs after the signal listeners are installed and has no time limit: a server URL that accepts the connection but never responds, or that keeps answering with `Retry-After`, holds the start promise open indefinitely, and a shutdown requested in the meantime waits for it before draining. The verification now accepts an `AbortSignal` which `handleShutdown()` triggers, aborting both a pending request and the wait before a retry, so that the shutdown proceeds immediately. Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 44 ++++++++++++++++++++++++++++++++++++++++ src/ParseServer.ts | 40 +++++++++++++++++++++++++++++------- src/request.js | 3 +++ 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index d4432e4a19..ef4cc2b7ee 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; diff --git a/src/ParseServer.ts b/src/ParseServer.ts index 22f63e3010..a2eee7ed87 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -64,6 +64,7 @@ class ParseServer { _startPromise: Promise | undefined; _startAppPromise: Promise | undefined; _shutdownPromise: Promise | undefined; + _shutdownController: AbortController; /** * @constructor * @param {ParseServerOptions} options the parse server initialization options @@ -141,6 +142,7 @@ class ParseServer { 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); @@ -278,8 +280,9 @@ class ParseServer { * 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, and - * the server cannot be started again afterwards. Every step runs even if a previous step failed; + * 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. * @@ -287,6 +290,8 @@ class ParseServer { */ 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; @@ -653,7 +658,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; @@ -693,7 +698,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 => { @@ -715,12 +725,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 */ 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) { From 4d22b498f9059107e83f103277a4f913970ad49d Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:18:14 +0100 Subject: [PATCH 07/14] fix: Schema change stream is leaked after a recoverable timeout error With `mongoOptions.timeoutMS` set, the driver resumes the schema change stream after a `MongoOperationTimeoutError` and emits the error while the stream stays open. Forgetting the stream in that case makes the next schema access open another watch, accumulating streams and duplicate change callbacks, of which only the last one is closed on shutdown. Keep a stream that is still open after a timeout error; forget and dispose of a stream that is lost for good. Co-Authored-By: Claude Fable 5.1 --- spec/MongoStorageAdapter.spec.js | 26 ++++++++++++++++++- .../Storage/Mongo/MongoStorageAdapter.js | 10 +++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/spec/MongoStorageAdapter.spec.js b/spec/MongoStorageAdapter.spec.js index 3310e8b5cb..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'); @@ -454,6 +454,30 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { 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/src/Adapters/Storage/Mongo/MongoStorageAdapter.js b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js index cf7f418d0a..ff45800cfe 100644 --- a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js +++ b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js @@ -332,13 +332,19 @@ export class MongoStorageAdapter implements StorageAdapter { 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. An unhandled 'error' event would terminate the process; - // forget the stream instead so that the next schema access re-establishes the watch. + // 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); From f31ad86e6687d8e91239357e60a5af50e86bcfec Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:20:11 +0100 Subject: [PATCH 08/14] fix: Shutdown after a failed start runs concurrently with startup operations still in progress `start()` rejected as soon as one startup operation failed while the others, such as the cache adapter connecting, were still pending; a shutdown following the failure could then shut down an adapter whose connection attempt was still in flight. Every startup operation now settles before the first failure is reported. Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 20 ++++++++++++++++++++ src/ParseServer.ts | 16 +++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index ef4cc2b7ee..46194df8db 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -443,6 +443,26 @@ describe('graceful shutdown', () => { ); }); + 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 connected = false; + cacheAdapter.connect = async () => { + await sleep(300); + connected = true; + }; + const api = new ParseServer(makeConfig({ cacheAdapter })); + server = api; + spyOn(api.config.liveQueryController, 'connect').and.rejectWith( + new Error('LiveQuery unavailable') + ); + spyOn(console, 'error').and.callFake(() => {}); + await expectAsync(api.start()).toBeRejectedWithError('LiveQuery unavailable'); + // The failure is reported only once the cache adapter connection has settled as well + expect(connected).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; diff --git a/src/ParseServer.ts b/src/ParseServer.ts index a2eee7ed87..5c08f56adc 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -201,7 +201,21 @@ class ParseServer { startupPromises.push(cacheController.adapter.connect()); } startupPromises.push(liveQueryController.connect()); - await Promise.all(startupPromises); + // Every startup operation settles before a failure is reported, so that a shutdown following + // the failure does not run concurrently with an operation still in progress, such as the cache + // adapter connecting + const settled = await Promise.all( + startupPromises.map(promise => + Promise.resolve(promise).then( + () => undefined, + error => ({ error }) + ) + ) + ); + const failed = settled.find(result => result); + if (failed) { + throw failed.error; + } if (cloud) { addParseCloud(); if (typeof cloud === 'function') { From ade94bb4156cd9ea0d8fb174f09a3014193dcecc Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:38:54 +0100 Subject: [PATCH 09/14] test: Report both errors when shutdown and test server restoration fail Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index 46194df8db..cd3496deee 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -200,12 +200,23 @@ describe('graceful shutdown', () => { triggers.removeFunction('slow', appId); const current = server; server = undefined; + let shutdownError; try { await current?.handleShutdown(); - } finally { - // Restore the shared test server even if the shutdown failed, so that the failure does not - // cascade into the following specs + } 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; } }); From 50743dae0fee3fef3c105892988fae881747f584 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:40:03 +0100 Subject: [PATCH 10/14] test: Release the initialization gate even if the starting-state probe fails Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index cd3496deee..a0c34f99d7 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -276,11 +276,15 @@ describe('graceful shutdown', () => { // 2. Starting: health asks the client to retry const starting = api.start(); - response = await health(); - expect(response.status).toBe(503); - expect(response.data.status).toBe('starting'); - expect(response.headers['retry-after']).toBe('1'); - releaseInitialization(); + 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 From b31b7442c3e19be44507278e9101a5788b90a0c4 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 14:40:55 +0100 Subject: [PATCH 11/14] fix: Failed start reports the first failure only after every startup operation has settled The first rejection in rejection order is reported, as before, but only once every startup operation has settled. Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 14 +++++++++----- src/ParseServer.ts | 27 +++++++++++++-------------- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index a0c34f99d7..0a66bc529f 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -461,10 +461,11 @@ describe('graceful shutdown', () => { 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 connected = false; + let cacheSettled = false; cacheAdapter.connect = async () => { await sleep(300); - connected = true; + cacheSettled = true; + throw new Error('cache unavailable'); }; const api = new ParseServer(makeConfig({ cacheAdapter })); server = api; @@ -472,9 +473,9 @@ describe('graceful shutdown', () => { 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'); - // The failure is reported only once the cache adapter connection has settled as well - expect(connected).toBe(true); + expect(cacheSettled).toBe(true); expect(api.config.state).toBe('error'); }); @@ -498,7 +499,10 @@ describe('graceful shutdown', () => { 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')]); + const early = await Promise.race([ + inFlight.then(() => 'settled'), + sleep(150).then(() => 'pending'), + ]); expect(early).toBe('pending'); await shutdown; const elapsed = Date.now() - started; diff --git a/src/ParseServer.ts b/src/ParseServer.ts index 5c08f56adc..a0f0c20212 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -201,20 +201,19 @@ class ParseServer { startupPromises.push(cacheController.adapter.connect()); } startupPromises.push(liveQueryController.connect()); - // Every startup operation settles before a failure is reported, so that a shutdown following - // the failure does not run concurrently with an operation still in progress, such as the cache - // adapter connecting - const settled = await Promise.all( - startupPromises.map(promise => - Promise.resolve(promise).then( - () => undefined, - error => ({ error }) - ) - ) - ); - const failed = settled.find(result => result); - if (failed) { - throw failed.error; + // 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(); From 2001742d97bdc9f3d751f677dfdd023cdf08af32 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 15:09:31 +0100 Subject: [PATCH 12/14] fix: Shutdown waits indefinitely for the LiveQuery server when its pub/sub adapter does not respond The LiveQuery teardown awaits the pub/sub adapter's unsubscribe and close calls, which never settle when the Redis server is unreachable, so the database, files and cache adapters were never shut down. The wait is now bounded like the wait for the HTTP servers; a timeout is reported with the collected shutdown errors. Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 26 ++++++++++++++++++++++++++ src/ParseServer.ts | 10 ++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index 0a66bc529f..e24b12eaba 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -368,6 +368,32 @@ describe('graceful shutdown', () => { 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 + spyOn(server.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; + }); + it('runs every shutdown step and rejects with the collected errors', async () => { let closeCompleteCalls = 0; server = await ParseServer.startApp( diff --git a/src/ParseServer.ts b/src/ParseServer.ts index a0f0c20212..b170d3ebf5 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -414,8 +414,14 @@ class ParseServer { server.closeAllConnections(); } } - // The LiveQuery teardown is awaited in full so that its errors are collected - await liveQueryClosed; + // 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 From 16fcead19002a8f13ebdfda7f5b48c397e7c6783 Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 15:19:28 +0100 Subject: [PATCH 13/14] fix: Second termination signal does not exit after a shutdown that completed with errors Co-Authored-By: Claude Fable 5.1 --- src/ParseServer.ts | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/ParseServer.ts b/src/ParseServer.ts index b170d3ebf5..36cae212fb 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -895,17 +895,14 @@ function configureListeners(parseServer) { } shuttingDown = true; process.stdout.write('Termination signal received. Shutting down.\n'); - 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; - }) - .finally(() => { - shuttingDown = false; - }); + // 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); From 64d2e7ba0389cefa0d2cf38bac86b991acb870ed Mon Sep 17 00:00:00 2001 From: Martin Man Date: Thu, 19 Nov 2026 15:53:31 +0100 Subject: [PATCH 14/14] test: Unsubscribe the stubbed LiveQuery server from the shared pub/sub emitter after the spec Co-Authored-By: Claude Fable 5.1 --- spec/ParseServer.spec.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index e24b12eaba..736605aa70 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -378,7 +378,9 @@ describe('graceful shutdown', () => { }) ); // The pub/sub adapter never settles, as with an unreachable Redis server - spyOn(server.liveQueryServer, 'shutdown').and.returnValue(new Promise(() => {})); + 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; @@ -392,6 +394,8 @@ describe('graceful shutdown', () => { 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 () => {