Skip to content

fix: retry the socket when the first connect attempt fails - #7833

Merged
diegolmello merged 17 commits into
developfrom
fix.connection-issue-ios
Nov 26, 2026
Merged

diegolmello merged 17 commits into
developfrom
fix.connection-issue-ios

Conversation

@OtavioStasiak

@OtavioStasiak OtavioStasiak commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

A plain connect that fails schedules no reopen in the SDK, so a cold start without network stayed on "Connecting..." with a stale room list until the next foreground. The SDK socket takes an opt-in reopenAfterFailedOpen (RocketChat/Rocket.Chat.js.SDK#441): with it, a failed connect schedules the normal Reopen, which a later reopenNow() (foreground recovery, native call accept) can still replace. The app's main client turns it on; the probe clients (getWebsocketInfo, logoutFromServer) stay one-shot.

Issue(s)

https://rocketchat.atlassian.net/browse/SUP-1128

Depends on RocketChat/Rocket.Chat.js.SDK#441

How to test or reproduce

  • Turn off the internet;
  • Open the app;
  • Wait 20 seconds;
  • Turn internet on;

Screenshots

Recorded on the iOS simulator through a local proxy to mobile.qa (stopping the proxy simulates no network), so the header shows localhost:3999 instead of mobile.qa.rocket.chat.

Before

connection-ios-BEFORE.mp4

After

connection-ios-AFTER.mp4

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • Improvement (non-breaking change which improves a current function)
  • New feature (non-breaking change which adds functionality)
  • Documentation update (if none of the other choices apply)

Checklist

  • I have read the CONTRIBUTING doc
  • I have signed the CLA
  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works (if applicable)
  • I have added necessary documentation (if applicable)
  • Any dependent changes have been merged and published in downstream modules

Further comments

Summary by CodeRabbit

  • Bug Fixes
    • Connections now retry after an initial connection failure, allowing the app to reconnect and complete setup when the connection becomes available.
    • Reopening a failed connection starts a fresh attempt, and replacing a connection avoids creating an unnecessary extra retry.

A plain open that fails schedules no reopen in the SDK, so a cold start
without network stayed on "Connecting..." with a stale room list until
the next foreground. Hand the failure to a forced attempt, which enters
the SDK's reopen loop, unless the connect() was already superseded.
@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

Walkthrough

The SDK client now enables reopening after a failed connection. Integration tests cover retries after socket errors, immediate reopening, and replacing a connection.

Changes

Connection retry handling

Layer / File(s) Summary
Retry configuration and connection tests
app/lib/services/sdk.ts, app/lib/services/__tests__/connect.integration.test.ts
initializeSdk sets reopenAfterFailedOpen to true. Integration tests check retry attempts, reopenNow() after an initial error, and connection replacement without an extra retry connection.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested labels: type: bug

Suggested reviewers: diegolmello

Merge Risk: Moderate · previous review 4bb81

The change adds an SDK option that the pinned SDK version ignores, so the app can still stay on "Connecting..." after a cold start without internet. The SDK dependency needs to support this behavior, or be updated, before this fix can work. Merging now ships a change that has no effect on the reported issue.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title says the fix retries the socket when the first connect attempt fails. The raw summary says Sdk.initializeSdk now sets reopenAfterFailedOpen to true, so the SDK reopens after a failed open. T…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title says the fix retries the socket when the first connect attempt fails. The raw summary says Sdk.initializeSdk now sets reopenAfterFailedOpen to true, so the SDK reopens after a failed open. The integration tests cover retries after socket errors and reopenNow() after an initial failure. The title matches the main change. The PR objectives say the commit message shifts the approach from a forced retry to relying on the SDK reopen, which is a small wording mismatch, but the title still describes the same behavior: a retry after the first connect fails.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Errors were encountered while retrieving linked issues.

Errors: 1

  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

Copy link
Copy Markdown

iOS Build Available

Rocket.Chat 4.78.0.110065

@github-actions

Copy link
Copy Markdown

@OtavioStasiak
OtavioStasiak marked this pull request as ready for review October 23, 2026 15:05

@diegolmello diegolmello left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The fix does what it says: a failed first open now enters the SDK's Reopen loop through a forced attempt. I checked these races and they are safe: a newer connect() or a logout, a foreground recoverSocket() at the same moment, and onerror followed by onclose. One inline cleanup on the tests, plus two decisions:

Fix it in the SDK instead? In the pinned SDK, Connection.open (lib/drivers/connection.ts) calls start(false, recovery), so a fresh open's failure is the only failure path that never schedules a Reopen. Having that failure enter the Reopen loop in the SDK would remove the app-side code here: the captured driver, the guard, the comment and the second test. The trade-off is that the first retry would wait the normal reopen delay (5s in prod) instead of running at once.

Retry forever for hosts that refuse the socket (app/lib/services/connect.ts:104-108). A stored server whose WebSocket is disabled or rejected (the 400 case getWebsocketInfo warns about), or a host that makes constructTransport throw, used to fail once and stop. Now it retries every 5s until logout or a server switch, including while Android is in the background. This matches what already happens after any unexpected disconnect, so it is probably intended, but it is a behaviour change worth confirming.

The replaced transport never settled its close, so reopenNow() was
rejected regardless of the guard. Let the mock answer close() so the
old driver would reopen without it.

@diegolmello diegolmello left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

No bugs found. The sdk.driver === driver guard holds against logout, a newer connect() and a concurrent recoverSocket(), and both new tests fail when the code they cover is removed. Two small cleanups inline, plus one decision:

Make the shared mock's close() settle by default (app/lib/testUtils/sdkIntegration.ts:36, used at app/lib/services/__tests__/connect.integration.test.ts:209-213). The default close = jest.fn() never fires onclose, so the SDK's close never settles. That is why the first version of the superseded-connect test passed without the guard. If close() set readyState = 3 and called onclose by default, the per-test mockImplementation would go away and future tests couldn't make the same mistake. The socketHealth tests share this mock, so it's your call.

Comment thread app/lib/services/connect.ts Resolved

@diegolmello diegolmello left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Overall the fix is correct against the pinned SDK. The sdk.driver === driver guard holds on every disconnect and server-switch path, because Sdk.disconnect() nulls the SDK synchronously, and the retry joins a recoverSocket() already in flight instead of duplicating it. One cleanup is inline. One decision for you:

Unbounded retry now also covers the first connect (app/lib/services/connect.ts:105-106)

  • An unreachable host, TLS or client-certificate failure, or a proxy that blocks WebSockets now retries every 5s for as long as the process lives. Before, the socket stayed dead until the foreground recoverSocket().
  • This matches the loop that runs after an established connection drops. It now also runs on the login screen and, on Android, in the background.
  • Is that intended, or should the SDK cap or back off?

Comment thread app/lib/services/connect.ts Resolved

@diegolmello diegolmello left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The fix works against the pinned SDK, and both new tests fail without it. I'd still like the retry to move into Rocket.Chat.js.SDK before this merges.

The failed first open not retrying is deliberate SDK behaviour, introduced in RocketChat/Rocket.Chat.js.SDK#421: a plain open() that fails gives the caller one answer and stays idle. The app's main client wants the opposite, but other clients rely on it. getWebsocketInfo returns on a 400 without disconnecting, and logoutFromServer builds a short-lived client of its own. So the SDK can't simply retry every failed open. It needs an opt-in instead.

Proposal:

  • SDK: add a socket option, e.g. reopenAfterFailedOpen. In Connection.open(), use this.start(false, recovery || this.options.reopenAfterFailedOpen), and pass the option through ISocketOptions / ConnectionOptions. With it on, a failed plain open schedules the normal Reopen after reopenDelayMs. connect() still rejects with the first failure, and close() still cancels everything.
  • App:
    • Bump the SDK pin.
    • Pass reopenAfterFailedOpen: true in initializeSdk (app/lib/services/sdk.ts).
    • Delete const { driver } = sdk and the reopenNow() branch in connect.ts.
    • Leave the probes (getWebsocketInfo, logoutFromServer) without the option.
  • Tests: keep both new integration tests as regression tests over the real SDK, with two adjustments:
    • The first retry now comes after the reopen delay, not immediately.
    • The replaced-connect test should advance past the reopen delay before it asserts, so a delayed retry from the closed driver would be caught.
  • SDK specs to add:
    • A failed first open rejects and schedules exactly one retry.
    • It keeps retrying until a handshake succeeds.
    • A first open that times out also retries.
    • A close during or after the failure leaves nothing scheduled.
    • reopenNow() replaces a scheduled or in-flight retry.
    • Without the option, the socket stays idle after a failed open.

I prototyped this against the SDK at ecf4fed: the existing suite plus the new specs pass, and tsc is clean.

A permanently unreachable server would still retry every 5s with no cap under this design, the same as after a dropped connection today. I think that's acceptable here, but it's worth knowing.

Comment thread app/lib/services/connect.ts Resolved

@diegolmello diegolmello left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The fix works with the pinned SDK. A failed first open now schedules the normal Reopen. A later connect(), a logout, an expired workspace and account deletion all cancel it, and a foreground recovery or a native call accept replaces it without opening a second socket. The probe clients stay one-shot. One cleanup is inline, plus one decision:

The SDK pin is an unmerged commit (package.json:60)

  • 03b1d58 is a commit on RocketChat/Rocket.Chat.js.SDK#441, which is still open.
  • Its code matches that PR's current head; the later commits only change docs and tests.
  • If the SDK PR is squash-merged, this app is left pinned to a commit that is not on the SDK's main branch, and a fresh install could fail once the branch is gone.
  • Merge the SDK PR first and re-pin to the merged commit?

@diegolmello diegolmello left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The fix works with the pinned SDK. The new test "keeps retrying when the first attempt fails" fails without reopenAfterFailedOpen: true. The earlier test cleanup is done. No bugs or cleanups to raise inline. Two decisions:

A pending login on a dropped workspace now retries forever (app/lib/services/sdk.ts:50, app/lib/services/connect.ts:422)

  • disconnect() lets go of the client without aborting its requests. If a REST login finishes afterwards, the SDK's Driver.login calls connect() on that dropped client. Its close has already settled, so the call opens a new socket.
  • Before this PR, a failed open there stopped after one try. With reopenAfterFailedOpen, it schedules a Reopen every 5s, and nothing in the app holds that client any more to close it. The old connect() listeners stay attached, so each attempt dispatches connectRequest(). A success dispatches connectSuccess(), plus a resume loginRequest if a token is still in Redux.
  • Steps:
    1. Start a password or resume login. Its REST /api/v1/login is still in flight.
    2. disconnect() runs without a connect() after it: logout (app/lib/methods/logout.ts:148), an expired workspace (app/sagas/selectServer.ts:139), account deletion (app/sagas/login.js:482), clear cache (app/lib/methods/clearCache.ts:48), or Add workspace with no previous server (app/views/NewServerView/hooks/useConnectServer.tsx:27).
    3. The login response arrives while the network is down or the WebSocket is blocked, so the dropped client's open fails.
  • Over 5 failing reopen cycles against the real SDK: this branch opened 7 transports and dispatched 5 connectRequests after disconnect(). Base opened 2 transports and dispatched none.
  • Likelihood is low: a login has to be in flight when one of those disconnect() calls runs.
  • This branch fixed it in "fix: abort a client's requests when it is disconnected so a pending login can't reopen it", then reverted that to keep the PR narrow. Ship as is and track the abort in a follow-up issue, or bring the abort back here?

The SDK pin is still an unmerged commit (package.json:60)

  • 03b1d58 is a commit on RocketChat/Rocket.Chat.js.SDK#441, which is still open. Its head adds only docs and a spec on top.
  • If that PR is squash-merged, this app stays pinned to a commit that isn't on the SDK's main branch. Merge the SDK PR first and re-pin to the merged commit?

@diegolmello
diegolmello merged commit fb99c2c into develop Nov 26, 2026
7 of 10 checks passed
@diegolmello
diegolmello deleted the fix.connection-issue-ios branch November 26, 2026 21:35

This branch is waiting to be deployed

3 waiting deployments
ios_build — 37451462 Waiting Nov 26, 2026 by OtavioStasiak via Build iOS / Hold #8045
android_build — 37451462 Waiting Nov 26, 2026 by OtavioStasiak via Build Android / Hold #8045
approve_e2e_testing — 37451462 Waiting Nov 26, 2026 by OtavioStasiak via E2E Hold #8045
upload_android — 01323bd5 Deployed Oct 23, 2026 by OtavioStasiak via Build Android / Upload Hold #7493
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants