Skip to content

FIX REST writes crash the server when several documents of a request fail - #485

Merged
pubkey merged 3 commits into
masterfrom
claude/eloquent-hopper-6e78eb-rest-write-error-crash
Nov 30, 2026
Merged

pubkey merged 3 commits into
masterfrom
claude/eloquent-hopper-6e78eb-rest-write-error-crash

Conversation

@pubkey

@pubkey pubkey commented Nov 30, 2026

Copy link
Copy Markdown
Owner

Bug

The REST /set//patch handler (onWriteError in setDocuments) and the /delete handler run the writes of a request with Promise.all. On a non-conflict write error, each failing write calls adapter.closeConnection(res, 500, ...).

When two or more writes of one request fail, the second closeConnection runs after the response was already sent. For example, a client sends two documents that do not match the schema. The express adapter's closeConnection is async and calls response.set(...), which throws ERR_HTTP_HEADERS_SENT. That rejected promise is never handled. Node exits on unhandled rejections by default, so any client could crash the server process with one request.

Fix

Both handlers send the error response only once per request, using an errorResponseSent flag. The errors are still rethrown, and express handles the rejected route handler.

Test

test/unit/endpoint-rest.test.ts: should answer with an error when several documents of a request fail to be written. It sends two invalid documents and expects a 500, then checks that the server still answers a normal /set and /query. Without the fix the test process exits with the unhandled ERR_HTTP_HEADERS_SENT rejection.

Full unit suite: 108 passing. npm run check-types passes.

An independent review reproduced the crash on master and confirmed the fix. It also checked every other closeConnection call site in the REST and replication endpoints, and none of them can be called twice or after the response was sent.

The review also suggested an optional hardening that is not in this PR. The express adapter's closeConnection could return early when response.headersSent, because the adapter type declares it as void and no caller handles its promise.

Changelog: orga/changelog/fix-rest-write-error-crash.md


Generated by Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015P6w6gSU5X3tPquwWNPFbs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015P6w6gSU5X3tPquwWNPFbs
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Verify Test Reproduction: Tests FAILED without the fix (expected)

This confirms the changed tests correctly reproduce the bug that the source changes fix.

This workflow runs the changed tests without the source fix to verify they reproduce the bug.

Show output
=== test:unit output ===
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 test:unit
> npm run build && mocha --import=tsx ./test/unit.test.ts --bail --exit

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 prebuild
> npm run prebuild:babel && npm run prebuild:scripts

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 prebuild:babel
> rimraf -rf babel.config.js && cp node_modules/rxdb/babel.config.js babel.config.js

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 prebuild:scripts
> rimraf -rf scripts/generate-plugins-package-json.mjs && cp node_modules/rxdb/scripts/generate-plugins-package-json.mjs scripts/generate-plugins-package-json.mjs


> rxdb-server@0.0.0 build
> npm run prebuild && rimraf -rf ./dist && npm run build:plugins && concurrently "npm run build:cjs" "npm run build:es" "npm run build:types" --success all

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 prebuild
> npm run prebuild:babel && npm run prebuild:scripts

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 prebuild:babel
> rimraf -rf babel.config.js && cp node_modules/rxdb/babel.config.js babel.config.js

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 prebuild:scripts
> rimraf -rf scripts/generate-plugins-package-json.mjs && cp node_modules/rxdb/scripts/generate-plugins-package-json.mjs scripts/generate-plugins-package-json.mjs

npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.

> rxdb-server@0.0.0 build:plugins
> node ./scripts/generate-plugins-package-json.mjs

./plugins/server
./plugins/adapter-express
./plugins/replication-server
./plugins/client-rest
[2] npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
[2] npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
[2] 
[2] > rxdb-server@0.0.0 build:types
[2] > rimraf -rf ./dist/types && tsc --project ./config/tsconfig.types.json
[2] 
[0] npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
[0] npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
[1] npm warn Unknown env config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
[1] npm warn Unknown project config "unsafe-perm". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options.
[0] 
[0] > rxdb-server@0.0.0 build:cjs
[0] > rimraf -rf dist/cjs && cross-env NODE_ENV=es5 babel src --out-dir dist/cjs --source-maps --extensions ".ts,.js"
[0] 
[1] 
[1] > rxdb-server@0.0.0 build:es
[1] > rimraf -rf dist/esm && cross-env NODE_ENV=es6 babel src --out-dir dist/esm --source-maps --extensions ".ts,.js" && echo '{ "type": "module", "sideEffects": false }' > dist/esm/package.json
[1] 
[1] @babel/plugin-transform-template-literals: The 'loose' option has been deprecated, use the `ignoreToPrimitiveHint` and `mutableTemplateObject` assumptions instead (https://babeljs.io/assumptions).
[0] @babel/plugin-transform-template-literals: The 'loose' option has been deprecated, use the `ignoreToPrimitiveHint` and `mutableTemplateObject` assumptions instead (https://babeljs.io/assumptions).
[0] @babel/plugin-transform-classes: The 'loose' option has been deprecated, use the 'setClassMethods', 'constantSuper', 'superIsCallableConstructor', 'noClassCalls', 'noClassPrototypeAssign', and 'noConstructorPrimitiveReturn' assumptions instead (https://babeljs.io/assumptions).
[2] npm run build:types exited with code 0
[1] Successfully compiled 15 files with Babel (525ms).
[1] npm run build:es exited with code 0
[0] Successfully compiled 15 files with Babel (621ms).
[0] npm run build:cjs exited with code 0
DEFAULT_STORAGE: undefined
# use RxStorage: memory


  server.test.ts
    init
-------------- RxDB dev-mode warning -------------------------------
you are seeing this because you use the RxDB dev-mode plugin https://rxdb.info/dev-mode.html?console=dev-mode 
This is great in development mode, because it will run many checks to ensure
that you use RxDB correct. If you see this in production mode,
you did something wrong because the dev-mode plugin will decrease the performance.

🤗 Hint: To get the most out of RxDB, check out the Premium Plugins
to get access to faster storages and more professional features: https://rxdb.info/premium/?console=dev-mode 

💬 Need help? The RxDB Discord is the fastest place to reach maintainers: https://rxdb.info/chat/?console=dev-mode 

You can disable this warning by calling disableWarnings() from the dev-mode plugin.
---------------------------------------------------------------------
      �[32m✔�[39m init
    basics
      �[32m✔�[39m should start end stop the server (68ms)
      �[32m✔�[39m should apply CORS (45ms)
      �[32m✔�[39m should not combine Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true
      �[32m✔�[39m should add multiple endpoints
      �[32m✔�[39m should end open streams on close()
      �[32m✔�[39m should resolve close() after the database was closed
      �[32m✔�[39m should resolve when close() is called multiple times
      �[32m✔�[39m should reject start() when the port is already in use
    express adapter
      �[32m✔�[39m should work on an existing express app that does not parse JSON bodies
    .doesContainRegexQuerySelector()
      �[32m✔�[39m should return false
      �[32m✔�[39m should return true
    .mergeServerDocumentFieldsMonad()
      �[32m✔�[39m should merge the documents
      �[32m✔�[39m should not add server-only fields when serverDoc is undefined (new document)
      �[32m✔�[39m should return falsy clientDoc as-is without transforming it
      �[32m✔�[39m should not add the field when serverDoc lacks it (new-doc-on-server)
      �[32m✔�[39m should strip client-sent values for server-only fields missing on serverDoc
      �[32m✔�[39m should not produce extra keys when serverDoc is missing the field (no false conflict)

  endpoint-rest.test.ts
    basics
      �[32m✔�[39m should start end stop the server
      �[32m✔�[39m should work without auth handler
    /query
      �[32m✔�[39m should not allow a query when validUntil of the auth data has expired
      �[32m✔�[39m should return the correct query results
      �[32m✔�[39m should respect the auth header and queryModifier
      �[32m✔�[39m should not allow $regex queries
      �[32m✔�[39m should have access-control-allow-credentials set to true
    /query/observe
      �[32m✔�[39m should return the correct query results (71ms)
      �[32m✔�[39m should emit the newest result last when the authHandler has a varying latency (433ms)
      �[32m✔�[39m should disconnect an open stream when the auth becomes invalid (3048ms)
      �[32m✔�[39m should should automatically reconnect (3045ms)
      �[32m✔�[39m should respect the auth header and queryModifier
      �[32m✔�[39m should not allow $regex queries
      �[32m✔�[39m should work when the base64-encoded query contains URL-reserved characters
      �[32m✔�[39m should observe queries that contain characters outside of Latin-1 (69ms)
      �[32m✔�[39m should keep the Latin-1 query encoding of older clients (49ms)
      �[32m✔�[39m should not keep the stream open when the client closes it while the authHandler runs (2059ms)
      �[32m✔�[39m should stop observing on the server when the client unsubscribes (630ms)
      �[32m✔�[39m should emit an error when the auth of the open stream has expired (3042ms)
    /get
      �[32m✔�[39m should return the correct documents
      �[32m✔�[39m should respect the auth header and queryModifier
      �[32m✔�[39m should have access-control-allow-credentials set to true for /query/observe
    /set
      �[32m✔�[39m should write the documents
      �[32m✔�[39m should not accept if changeValidator says no
      �[32m✔�[39m should not accept new document inserts if changeValidator says no
      �[32m✔�[39m should throw an error via handleError when the server rejects a set
init.test.js: unhandledRejection
init.test.js: unhandledRejection
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:684:11)
    at ServerResponse.header (/home/runner/work/rxdb-server/rxdb-server/node_modules/express/lib/response.js:686:10)
    at Object.closeConnection (/home/runner/work/rxdb-server/rxdb-server/src/plugins/adapter-express/index.ts:70:18)
    at onWriteError (/home/runner/work/rxdb-server/rxdb-server/src/plugins/server/endpoint-rest.ts:241:29)
    at <anonymous> (/home/runner/work/rxdb-server/rxdb-server/src/plugins/server/endpoint-rest.ts:289:94)
    at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
    at async Promise.all (index 1)
    at async setDocuments (/home/runner/work/rxdb-server/rxdb-server/src/plugins/server/endpoint-rest.ts:316:17)
{
    "code": "ERR_HTTP_HEADERS_SENT"
}
------- COULD NOT AWAIT p


View full workflow run

@pubkey
pubkey merged commit ef6247a into master Nov 30, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants