fix: end() hangs forever after ECONNRESET error #1142
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When a query fails with
ECONNRESET(or any connection error), callingpg.end()hangs forever. This happens because:queryvariable in the connection is never clearedReadyForQueryclearsquery = null, but connection errors never reach that handlerend()is called, it checks!queryto determine if it can terminate immediatelyquerystill references the rejected query object, the condition fails andend()creates a promise waiting forendedto be calledendedis only called interminate(), which is only called when!queryis true - creating a deadlockSolution
I've made two changes to ensure the
queryvariable is properly cleared when connection errors occur:errored()function: Clearquery = nullafter rejecting the queryclosed()function: WhenhadErroris true, clear the query before closing (sinceerrored()might not always be called in all error paths)Changes
src/connection.js:errored()to clearqueryafterqueryError()closed()to clearquerywhenhadErroris truetests/index.js: Added test'end() completes after ECONNRESET error'to verify the fixTesting
The new test creates a real PostgreSQL connection, terminates the backend during a query execution, and verifies that
end()completes quickly (within 1 second) instead of hanging forever.Notes
I'm not entirely sure if this is the best approach - I spent a significant amount of time understanding the codebase and the problem. The connection lifecycle and query state management is quite complex, and I wanted to make sure I understood the flow before making changes. I also received help from AI to better understand the problem and explore the codebase, which was invaluable in identifying where the
queryvariable needed to be cleared.I'm open to feedback and alternative approaches if there's a better way to handle this!
Fixes #1130