Skip to content

Fixed the gateway's reconnection system#264

Merged
thewilloftheshadow merged 4 commits intobuape:mainfrom
real2two:real2two/fixed-gateway
Jun 10, 2025
Merged

Fixed the gateway's reconnection system#264
thewilloftheshadow merged 4 commits intobuape:mainfrom
real2two:real2two/fixed-gateway

Conversation

@real2two
Copy link
Copy Markdown
Contributor

@real2two real2two commented Jun 9, 2025

There's a major bug in all of the gateway plugins where it fails to reconnect properly.

This was really annoying to test because the steps to reproduce this was:

  1. Connect to the gateway.
  2. Wait until you get GatewayOpcodes.Reconnect. This could take up to multiple hours.
  3. The console starts to spam and never successfully reconnects to the gateway.

Here are all of the issues that were fixed:

  • When GatewayOpcodes.Reconnect is recieved, there's an issue where it tries to reconnect twice, because both this.handleReconnect() in line 207 and this.handleClose(code) in line 218 both run this.handleReconnectionAttempt(...). There are also few other places where something similar could happen as well.
  • When creating a new WebSocket connection, it didn't close the older one.
  • It always fails to resume to the gateway because the last sequence before disconnection wasn't sent. Instead, it was sending the latest sequence number that was given (aka from the new WebSocket).
  • On a reconnection, the WebSocket has to disconnect with a code other than 1000 and 1001, which I added.
  • Metrics stops working after one disconnection. I fixed this and also reset uptime when the gateway connection restarts now.
  • backoffTime was always two times the value the user set. This was fixed by setting this.reconnectAttempts++ after calculating the backoffTime.
  • Unknown events shouldn't crash the gateway process.

I tested these fixes with both the gateway forwarder and the sharded gateway forwarder! Since both the gateway forwarder and sharded gateway forwarder extend the gateway and sharded gateway plugin, everything should be functional (in theory)!

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Improved connection stability by preventing multiple reconnection attempts after a disconnection.
    • Enhanced handling of connection state to avoid errors during reconnect scenarios.
  • New Features

    • Added automatic reset of connection uptime tracking for more accurate monitoring.
  • Improvements

    • More consistent and reliable reconnection behavior for WebSocket connections.
    • Better management of connection metrics and error handling.

@real2two real2two requested a review from a team as a code owner June 9, 2025 15:33
@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Jun 9, 2025

🦋 Changeset detected

Latest commit: 67b5b42

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@buape/carbon Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 9, 2025

Walkthrough

The changes enhance WebSocket connection management within the gateway plugin by introducing stricter state tracking, preventing reconnections after closure, and ensuring consistent handling of sequence and session states. The connection monitor now supports uptime resets without full destruction, and new methods encapsulate interval logic for improved maintainability.

Changes

File(s) Change Summary
packages/carbon/src/plugins/gateway/GatewayPlugin.ts Refined connection logic: closes existing sockets before reconnecting, adds local closure flag, improves reconnection and state management, updates method signatures.
packages/carbon/src/plugins/gateway/utils/monitor.ts Refactored interval logic into a private method; added public uptime reset method for the connection monitor.
.changeset/lovely-apes-decide.md Added changeset documenting patch update fixing gateway reconnection system.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GatewayPlugin
    participant ConnectionMonitor
    participant WebSocket

    Client->>GatewayPlugin: connect()
    GatewayPlugin->>WebSocket: Close existing connection (if any)
    GatewayPlugin->>WebSocket: Create new connection
    WebSocket-->>GatewayPlugin: onOpen/onClose/onError/onMessage
    GatewayPlugin->>ConnectionMonitor: resetUptime()
    alt Reconnection needed
        GatewayPlugin->>GatewayPlugin: handleReconnectionAttempt()
        GatewayPlugin->>GatewayPlugin: disconnect()
        GatewayPlugin->>ConnectionMonitor: resetUptime()
        GatewayPlugin->>WebSocket: Close connection
        GatewayPlugin->>WebSocket: Attempt reconnection
        alt Max attempts or fatal error
            GatewayPlugin->>ConnectionMonitor: destroy()
        end
    end
Loading

Poem

In the warren of webs, connections renew,
Old sockets are closed, as fresh ones debut.
With uptime reset and a vigilant eye,
No more lost sequences slipping by.
The monitor ticks, the gateway’s aware—
A hop, a skip, robust as a hare!
🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7f59f8 and 67b5b42.

📒 Files selected for processing (1)
  • .changeset/lovely-apes-decide.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/lovely-apes-decide.md

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
🪧 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

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 added the package: carbon The carbon package label Jun 9, 2025
Copy link
Copy Markdown
Contributor

@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: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7681111 and 13102e1.

📒 Files selected for processing (2)
  • packages/carbon/src/plugins/gateway/GatewayPlugin.ts (11 hunks)
  • packages/carbon/src/plugins/gateway/utils/monitor.ts (2 hunks)
🔇 Additional comments (6)
packages/carbon/src/plugins/gateway/utils/monitor.ts (1)

42-43: Clean refactoring that improves maintainability.

The extraction of interval creation logic into createMetricsInterval() and the addition of resetUptime() method are well-implemented. This allows the monitor to reset its uptime tracking without losing its internal state, which aligns perfectly with the connection lifecycle improvements in the gateway plugin.

Also applies to: 45-65, 97-102

packages/carbon/src/plugins/gateway/GatewayPlugin.ts (5)

102-102: Good defensive programming to prevent duplicate connections.

Closing any existing WebSocket connection at the start of connect() ensures a clean state before establishing a new connection.


116-116: Correct usage of the new resetUptime() method.

This change properly maintains the monitor instance across reconnections while resetting its uptime tracking, which is essential for accurate metrics after disconnection.


188-190: Good defensive programming for event type validation.

Throwing an error for unknown event types helps catch integration issues early and prevents silent failures.


266-266: Correct implementation of reconnection logic improvements.

  • Calling disconnect() at the start ensures a clean state before reconnection
  • Moving the increment after backoff calculation fixes the doubled backoff time issue
  • Preserving the monitor except for terminal conditions maintains metrics continuity

Also applies to: 307-311


343-349: Correct fix for sequence number handling during resume.

Using state.sequence instead of this.sequence ensures the resume payload contains the last sequence number from before disconnection, which is the correct behavior for resuming a session.

@thewilloftheshadow thewilloftheshadow merged commit e2b2c69 into buape:main Jun 10, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

package: carbon The carbon package

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants