Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ECO-4914] Fix websocket reconnection can get stuck in disconnected/connecting cycle #1855

Merged
merged 2 commits into from
Sep 6, 2024

Conversation

VeskeR
Copy link
Contributor

@VeskeR VeskeR commented Sep 6, 2024

This fixes a regression introduced in ably-js v2 in this PR.
Under certain network conditions (internet down) a race condition could
occur in the connection manager. Specifically, websocket connectivity
check in the startWebSocketSlowTimer function needed to set the
wsCheckResult flag to false before the timer was cleared by other
code branches. If that happened, it then caused an endless loop of
websocket connection retries, even after the network conditions
stabilized. A websocket transport would successfully open but then be
immediately disposed due to the wsCheckResult flag still being set to
false, without any mechanism to reset it in this scenario.

Upon closer look, it makes sense that the websocket connection health
flags (wsCheckResult and abandonedWebSocket) should be reset when
attempting a new websocket connection. The previous solution did not
explicitly reset these flags in the connectWs function, leading to the
described race condition and endless loop. Thus, wsCheckResult and
abandonedWebSocket are now reset to their neutral values upon entering
the connectWs function.

The websocket reconnection test that was added now checks such condition. You can see it fail on all envrionments on a library version without the aforementioned fix: node, browsers

Resolves #1844

Summary by CodeRabbit

  • Tests
    • Added a new test case to verify WebSocket reconnection behavior after connectivity failures, enhancing the reliability of the WebSocket transport mechanism.
  • Improvements
    • Refined the handling of WebSocket connectivity checks to improve the reliability and clarity of connection state management.

Copy link

coderabbitai bot commented Sep 6, 2024

Walkthrough

The changes include the addition of a test case that verifies the WebSocket connection's behavior during connectivity failures and subsequent recovery. This is achieved by simulating a disconnection with an unroutable host address. Additionally, the ConnectionManager class has been updated to refine the handling of WebSocket connectivity checks and to reset connection state properties during initialization.

Changes

Files Change Summary
src/common/lib/transport/... Modified WebSocket connectivity check handling by removing conditional logic and resetting wsCheckResult and abandonedWebSocket properties.
test/common/modules/... Added new exported options for WebSocket timeouts and connection management to enhance configurability.
test/realtime/transports.test.js Added a test case ws_can_reconnect_after_ws_connectivity_fail to verify WebSocket reconnection after connectivity loss.

Poem

In the meadow, hop and play,
A WebSocket's here to stay!
When the path goes dark and wide,
It finds its way, with joy and pride.
Connectivity's but a game,
Reconnect, and hop again! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot temporarily deployed to staging/pull/1855/bundle-report September 6, 2024 16:22 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1855/typedoc September 6, 2024 16:22 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1855/features September 6, 2024 16:22 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bd66293 and ee76047.

Files selected for processing (1)
  • test/realtime/transports.test.js (1 hunks)
Additional comments not posted (1)
test/realtime/transports.test.js (1)

160-213: Review of New Test Case: ws_can_reconnect_after_ws_connectivity_fail

This test case is designed to verify the WebSocket connection's behavior during connectivity failures and subsequent recovery. Here are some observations and suggestions:

  1. Simulation of Disconnection: The test effectively simulates a disconnection by setting Defaults.wsConnectivityUrl to an unroutable address. This is a good use of the test environment to mimic real-world scenarios.

  2. Short Timeouts: The use of short timeouts (webSocketSlowTimeout, realtimeRequestTimeout, disconnectedRetryTimeout) is appropriate for a test environment as it allows the test to execute quickly and efficiently.

  3. Blocking Initial Connection: The method tryATransport is stubbed to prevent the initial connection attempt, which is a clever way to simulate the connectivity issue without external dependencies.

  4. Restoration of Original Settings: The test ensures that original settings are restored after the test execution, which is crucial to avoid side effects on other tests. This includes restoring Defaults.wsConnectivityUrl, realtime.options.realtimeHost, and connection.connectionManager.wsHosts.

  5. Reconnection Logic: The test checks that the connection can be successfully re-established, which is the core functionality being tested. This is done through a series of asynchronous callbacks, ensuring that each step is completed before moving on to the next.

  6. Error Handling: The test includes error handling in the final callback of the async.series, which is essential to catch and report errors during test execution.

Suggestions:

  • Enhance Readability: Consider breaking down the test into smaller functions or adding more comments to clarify each step of the test. This can improve maintainability and readability.
  • Increase Robustness: Add assertions to check intermediate states or specific error messages to ensure that the test is behaving as expected during each phase of the simulation.

Overall, the test is well-constructed and achieves its objective of testing the reconnection logic under simulated network failure conditions.

@VeskeR VeskeR requested a review from ttypic September 6, 2024 16:35
@github-actions github-actions bot temporarily deployed to staging/pull/1855/typedoc September 6, 2024 16:36 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1855/features September 6, 2024 16:36 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1855/bundle-report September 6, 2024 16:36 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ee76047 and 61757f9.

Files selected for processing (1)
  • src/common/lib/transport/connectionmanager.ts (2 hunks)
Additional comments not posted (2)
src/common/lib/transport/connectionmanager.ts (2)

1494-1495: Resetting connection state properties at the start of connectWs method.

The changes to reset wsCheckResult and abandonedWebSocket at the beginning of the connectWs method are crucial for ensuring that stale state does not affect new connection attempts. This is a positive change that aligns with the PR's objective to fix the reconnection loop issue.


Line range hint 1-1495: Well-structured and documented ConnectionManager class.

The ConnectionManager class is well-organized with clear separation of concerns and comprehensive documentation. The use of modern JavaScript features and helper functions enhances readability and maintainability. This structure supports the robust handling of connection states and transitions, crucial for the functionality of the WebSocket-based communication system.

@VeskeR VeskeR force-pushed the 1844/fix-ws-connection-recovery branch from 61757f9 to d65b03d Compare September 6, 2024 17:23
Copy link
Collaborator

@ttypic ttypic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@github-actions github-actions bot temporarily deployed to staging/pull/1855/bundle-report September 6, 2024 17:24 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1855/typedoc September 6, 2024 17:24 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1855/features September 6, 2024 17:24 Inactive
…ycle

Fixes a regression introduced in ably-js v2 in the "no upgrade" PR [1].
Under certain network conditions (internet down) a race condition could
occur in the connection manager. Specifically, websocket connectivity
check in the `startWebSocketSlowTimer` function needed to set the
`wsCheckResult` flag to `false` before the timer was cleared by other
code branches. If that happened, it then caused an endless loop of
websocket connection retries, even after the network conditions
stabilized. A websocket transport would successfully open but then be
immediately disposed due to the `wsCheckResult` flag still being set to
`false`, without any mechanism to reset it in this scenario.

Upon closer look, it makes sense that the websocket connection health
flags (`wsCheckResult` and `abandonedWebSocket`) should be reset when
attempting a new websocket connection. The previous solution did not
explicitly reset these flags in the `connectWs` function, leading to the
described race condition and endless loop. Thus, `wsCheckResult` and
`abandonedWebSocket` are now reset to their neutral values upon entering
the `connectWs` function.

Resolves #1844

[1] #1645
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 61757f9 and 60288b3.

Files selected for processing (3)
  • src/common/lib/transport/connectionmanager.ts (3 hunks)
  • test/common/modules/private_api_recorder.js (4 hunks)
  • test/realtime/transports.test.js (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • src/common/lib/transport/connectionmanager.ts
  • test/realtime/transports.test.js
Additional comments not posted (4)
test/common/modules/private_api_recorder.js (4)

71-71: Approved: Addition of WebSocket slow timeout option.

The addition of pass.clientOption.webSocketSlowTimeout aligns with the PR's objectives to enhance WebSocket management. This should help in better handling slow or lagging WebSocket connections.


101-101: Approved: Addition of realtime host option.

The inclusion of read.realtime.options.realtimeHost is a positive step towards enhancing real-time communication capabilities and connection reliability.


128-128: Approved: Addition of WebSocket connectivity URL option.

The addition of write.Defaults.wsConnectivityUrl is crucial for specifying endpoints for WebSocket connectivity checks, aligning well with the PR's focus on improving WebSocket reconnection behavior.


140-140: Approved: Addition of WebSocket hosts management option.

The addition of write.connectionManager.wsHosts enhances the management of WebSocket hosts, which is crucial for handling complex connectivity scenarios effectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

Connection recovery not working
2 participants