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

SocketIO: Change isAlive to atomic update to solve the high concurrency problem #1165

Merged
merged 5 commits into from
Sep 2, 2024

Conversation

liaohongxing
Copy link
Contributor

@liaohongxing liaohongxing commented Aug 26, 2024

SocketIO: Change isAlive to atomic update to solve the high concurrency problem, It is found that in the disconnected method, the channel is closed repeatedly, which may be caused by concurrent execution of multiple coroutines

Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]: panic: close of closed channel
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]: goroutine 65402 [running]:
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]: github.com/gofiber/contrib/socketio.(*Websocket).disconnected(0xc0001df3b0, {0xedd9a0, 0xc000f1ce88})
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]:         /home/aoc/go/pkg/mod/github.com/gofiber/contrib/[email protected]/socketio.go:571 +0x5b
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]: github.com/gofiber/contrib/socketio.(*Websocket).read(0xc0001df3b0, {0xee7da0, 0xc001011130})
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]:         /home/aoc/go/pkg/mod/github.com/gofiber/contrib/[email protected]/socketio.go:553 +0x25f
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]: created by github.com/gofiber/contrib/socketio.(*Websocket).run in goroutine 65399
Aug 26 08:21:45 iZbp11svgbsui9avcnt22kZ chi-api[424959]:         /home/aoc/go/pkg/mod/github.com/gofiber/contrib/[email protected]/socketio.go:513 +0xec

@ReneWerner87 @antoniodipinto

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes
    • Improved the stability of the Websocket connection handling by ensuring thread-safe operations during disconnection, reducing the risk of crashes and inconsistent states.
    • Enhanced the logic for disconnecting by ensuring events are fired only when the connection is confirmed to be inactive, increasing overall reliability.

@liaohongxing liaohongxing requested a review from a team as a code owner August 26, 2024 03:44
@liaohongxing liaohongxing requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team August 26, 2024 03:44
Copy link
Contributor

coderabbitai bot commented Aug 26, 2024

Walkthrough

The changes involve modifying the disconnected method in the Websocket struct to enhance thread safety by adding mutex locking. Additionally, the control flow is adjusted to manage the connection's alive status more reliably before firing the disconnect event. The use of sync.Once further ensures that the alive status is set correctly.

Changes

File Change Summary
socketio/socketio.go Modified disconnected method in Websocket struct to add mutex locking and enhance control flow for connection management.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Websocket
    participant Mutex

    Client->>Websocket: Call disconnected(err)
    Websocket->>Mutex: Lock
    Mutex-->>Websocket: Lock acquired
    Websocket->>Websocket: Set alive status to false
    Websocket->>Websocket: Check if connection is alive
    alt Not alive
        Websocket->>Websocket: Close done channel
        Websocket->>Websocket: Fire disconnect event
    end
    Websocket->>Mutex: Unlock
    Mutex-->>Websocket: Lock released
Loading

Poem

In the world of webs we weave,
A mutex now helps us believe,
That threads can dance, not collide,
With safety as our joyful guide.
Hopping through code, we cheer and play,
For harmony in every way! 🐇✨


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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

Copy link
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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c62abb2 and e7bb3aa.

Files selected for processing (1)
  • socketio/socketio.go (1 hunks)

socketio/socketio.go Outdated Show resolved Hide resolved
Copy link
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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e7bb3aa and dee94a9.

Files selected for processing (1)
  • socketio/socketio.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • socketio/socketio.go

Copy link
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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between dee94a9 and 27e4c8d.

Files selected for processing (1)
  • socketio/socketio.go (1 hunks)
Additional comments not posted (2)
socketio/socketio.go (2)

569-569: Ensure atomicity of the isAlive update.

The isAlive status is set to false before checking it again. This ensures that the state is updated atomically and prevents race conditions.

The code changes are approved.


573-573: LGTM!

The disconnect event is fired correctly after ensuring the connection is inactive.

The code changes are approved.

Comment on lines 570 to 572
if !kws.IsAlive() {
close(kws.done)
}
Copy link
Contributor

@coderabbitai coderabbitai bot Aug 27, 2024

Choose a reason for hiding this comment

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

Improve readability and efficiency.

The check if !kws.IsAlive() is redundant after setting kws.setAlive(false). The close(kws.done) should be moved outside the if block for clarity.

Apply this diff to improve readability and efficiency:

- if !kws.IsAlive() {
-     close(kws.done)
- }
+ close(kws.done)
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if !kws.IsAlive() {
close(kws.done)
}
close(kws.done)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

setAlive then needs to check the status again, and isAlive may enter in parallel

Copy link
Contributor

Choose a reason for hiding this comment

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

@liaohongxing, you're absolutely right. Rechecking the status after calling setAlive(false) is crucial to avoid race conditions, especially in a highly concurrent environment where isAlive might be accessed by other goroutines in parallel. The current implementation ensures that the done channel is only closed when the connection is confirmed to be inactive, which is the correct approach. Thanks for the clarification!

Copy link
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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 27e4c8d and dadd0c8.

Files selected for processing (1)
  • socketio/socketio.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • socketio/socketio.go

@liaohongxing
Copy link
Contributor Author

@ReneWerner87
@gaby

Can you merge this patch? I have tested this patch in the production environment, and there is no problem

@ReneWerner87 ReneWerner87 merged commit 27e7861 into gofiber:main Sep 2, 2024
58 checks passed
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.

3 participants