fix(#100): Ensure correct connection closure #112
Merged
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.
The connection closure method sets the readyState to CLOSING and emits a close event to the socket, then sets the ready state to CLOSED.
However, due to a race condition, the readyState is already at the state of CLOSED when the socket close method is triggered. This causes an exception and a reconnection attempt. As reported in #100
This fix ensures the connectionTimer is cleared before emitting the close event, and updates the socket close handler to only throw an exception if the closure was unexpected (e.g. readyState is not CLOSED and the connectionTimer was not previously destroyed).
Tests added to ensure the new logic is closing the connection correctly. Removing the changes to the connection.ts method the tests correctly catch the closure exception and fail.