Skip to content

[ISSUE #3519]⚡️Async socket handling migration using tokio-util for HA connection layer#3520

Merged
rocketmq-rust-bot merged 1 commit intomainfrom
op-3519
Jun 24, 2025
Merged

[ISSUE #3519]⚡️Async socket handling migration using tokio-util for HA connection layer#3520
rocketmq-rust-bot merged 1 commit intomainfrom
op-3519

Conversation

@mxsm
Copy link
Owner

@mxsm mxsm commented Jun 24, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #3519

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • Refactor
    • Updated socket handling to use a framed stream approach for improved data management.
    • Changed how data is sent over connections, now using a stream and sink interface.
    • The read service is temporarily disabled and will be re-implemented in a future update.

Copilot AI review requested due to automatic review settings June 24, 2025 16:04
@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution🎉!

💡CodeRabbit(AI) will review your code first🔥!

Note

🚨The code review suggestions from CodeRabbit are to be used as a reference only, and the PR submitter can decide whether to make changes based on their own judgment. Ultimately, the project management personnel will conduct the final code review💥.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

Walkthrough

The changes migrate the HA connection layer from using raw Tokio socket read/write halves to a framed stream abstraction with tokio_util::codec::Framed and BytesCodec. The code now uses split stream and sink interfaces for async socket handling, updating type signatures and logic accordingly. The read service is currently unimplemented.

Changes

File(s) Change Summary
rocketmq-store/Cargo.toml Added tokio-util as a workspace dependency.
rocketmq-store/src/ha/default_ha_connection.rs Refactored HA connection to use Framed<TcpStream, BytesCodec> with SplitStream/SplitSink for IO; updated type signatures and logic; commented out read service implementation.

Sequence Diagram(s)

sequenceDiagram
    participant TcpStream
    participant Framed
    participant SplitSink
    participant SplitStream
    participant WriteSocketService
    participant ReadSocketService

    TcpStream->>Framed: Wrap with BytesCodec (Framed::with_capacity)
    Framed->>SplitSink: split() -> writer (SplitSink)
    Framed->>SplitStream: split() -> reader (SplitStream)
    WriteSocketService->>SplitSink: send(Bytes)
    ReadSocketService->>SplitStream: next() (currently unimplemented)
Loading

Assessment against linked issues

Objective Addressed Explanation
Migrate HA connection layer from raw Tokio socket APIs to tokio-util's Framed/BytesCodec/SinkExt/StreamExt (#3519)
Update type signatures and logic to use SplitSink/SplitStream with Framed<TcpStream, BytesCodec> (#3519)
Add tokio-util dependency to workspace for codec support (#3519)
Remove direct use of tokio::io async read/write traits in HA connection (#3519)

Poem

In tunnels of bytes where the data streams flow,
A rabbit refactors, letting old sockets go.
With Framed and with Bytes, the code hops anew,
Async and tidy, connections run true.
The HA now sparkles—oh, what a view!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR migrates the HA connection layer to use tokio-util’s framed streams for asynchronous socket handling.

  • Introduces Framed with BytesCodec and replaces manual split/read/write halves.
  • Updates ReadSocketService and WriteSocketService to use SplitStream/SplitSink.
  • Stubs out the read service implementation and adds tokio-util workspace override in Cargo.toml.

Reviewed Changes

Copilot reviewed 2 out of 3 changed files in this pull request and generated 4 comments.

File Description
rocketmq-store/src/ha/default_ha_connection.rs Refactor socket splitting to use tokio_util::codec::Framed, change reader/writer types, and stub out ReadSocketService.
rocketmq-store/Cargo.toml Add tokio-util.workspace = true under workspace overrides.

// ha_service.remove_connection(&client_address).await;
info!("ReadSocketService ended for client: {}", client_address);
info!("ReadSocketService ended for client: {}", client_address);*/
unimplemented!("ReadSocketService is not implemented yet");
Copy link

Copilot AI Jun 24, 2025

Choose a reason for hiding this comment

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

The run_service method for ReadSocketService is currently unimplemented and will panic at runtime; consider implementing or removing this stub to restore read functionality.

Copilot uses AI. Check for mistakes.
message_store_config: Arc<MessageStoreConfig>,
) {
info!("ReadSocketService started for client: {}", client_address);
/* info!("ReadSocketService started for client: {}", client_address);
Copy link

Copilot AI Jun 24, 2025

Choose a reason for hiding this comment

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

[nitpick] Large commented-out sections reduce readability; consider removing or isolating dead code.

Copilot uses AI. Check for mistakes.
let socket_stream = self.socket_stream.take().unwrap();
let (reader, writer) = socket_stream.into_split();
let tcp_stream = self.socket_stream.take().unwrap();
let framed = Framed::with_capacity(tcp_stream, BytesCodec::new(), 1024 * 4);
Copy link

Copilot AI Jun 24, 2025

Choose a reason for hiding this comment

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

[nitpick] The buffer capacity 4096 is a magic number; consider defining a named constant for clarity.

Suggested change
let framed = Framed::with_capacity(tcp_stream, BytesCodec::new(), 1024 * 4);
let framed = Framed::with_capacity(tcp_stream, BytesCodec::new(), BUFFER_CAPACITY);

Copilot uses AI. Check for mistakes.
Comment on lines +594 to +595
let len = buffer_header.len();
let result = match socket.send(buffer_header).await {
Copy link

Copilot AI Jun 24, 2025

Choose a reason for hiding this comment

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

[nitpick] Sending header and data in separate calls increases syscall overhead; consider combining them into one buffer or using a batch send to improve throughput.

Suggested change
let len = buffer_header.len();
let result = match socket.send(buffer_header).await {
let mut combined_buffer = BytesMut::new();
combined_buffer.put(buffer_header);
if let Some(data) = select_mapped_buffer {
combined_buffer.put(data);
}
let len = combined_buffer.len();
match socket.send(combined_buffer.freeze()).await {

Copilot uses AI. Check for mistakes.
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

🧹 Nitpick comments (1)
rocketmq-store/src/ha/default_ha_connection.rs (1)

116-118: Consider making the buffer size configurable.

The framed approach with BytesCodec is appropriate for this use case. However, the hardcoded buffer size of 4KB might benefit from being configurable via MessageStoreConfig to allow tuning based on deployment requirements.

-        let framed = Framed::with_capacity(tcp_stream, BytesCodec::new(), 1024 * 4);
+        let buffer_size = self.message_store_config.ha_socket_buffer_size.unwrap_or(1024 * 4);
+        let framed = Framed::with_capacity(tcp_stream, BytesCodec::new(), buffer_size);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8711443 and 4966a75.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • rocketmq-store/Cargo.toml (1 hunks)
  • rocketmq-store/src/ha/default_ha_connection.rs (15 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: auto-approve
  • GitHub Check: test
  • GitHub Check: build
🔇 Additional comments (5)
rocketmq-store/Cargo.toml (1)

34-34: LGTM! Necessary dependency for the HA connection refactoring.

The addition of tokio-util dependency supports the migration to framed stream handling in the HA connection layer.

rocketmq-store/src/ha/default_ha_connection.rs (4)

27-30: LGTM! Necessary imports for framed socket handling.

The added imports support the migration from raw socket operations to the framed codec approach using tokio_util and futures_util.

Also applies to: 36-37


234-234: LGTM! Type signatures correctly updated for framed streams.

The type changes from OwnedReadHalf to SplitStream<Framed<TcpStream, BytesCodec>> are consistent with the new framed codec approach.

Also applies to: 247-247, 297-297


412-412: LGTM! WriteSocketService types correctly updated.

The type changes to use SplitSink<Framed<TcpStream, BytesCodec>, Bytes> and the addition of mut keyword are appropriate for the new sink-based approach.

Also applies to: 425-425, 475-475


587-624: LGTM! Properly adapted for sink-based data transfer.

The changes correctly adapt the data transfer logic:

  • Method signature updated to use Bytes instead of byte slices
  • send() operations replace write_all() for sink interface
  • Flow monitoring correctly updated for new data types

The error handling and logic flow remain consistent with the original implementation.

// ha_service.remove_connection(&client_address).await;
info!("ReadSocketService ended for client: {}", client_address);
info!("ReadSocketService ended for client: {}", client_address);*/
unimplemented!("ReadSocketService is not implemented yet");
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: ReadSocketService is completely disabled.

The read service implementation has been replaced with unimplemented!(), which means:

  • Slave requests cannot be processed
  • Slave acknowledgment offsets won't be updated
  • HA replication functionality is broken

This change would cause runtime panics when the read service is called.

Either:

  1. Complete the implementation for the new framed approach, or
  2. Revert to the previous working implementation until the migration is complete

Would you like me to help implement the read service using the new framed stream approach based on the commented code?

🤖 Prompt for AI Agents
In rocketmq-store/src/ha/default_ha_connection.rs at line 399, the
ReadSocketService is currently disabled with unimplemented!(), causing runtime
panics and breaking HA replication. To fix this, either fully implement the read
service using the new framed stream approach as indicated by the commented code
or revert to the previous working implementation until the migration is complete
to ensure slave requests and acknowledgments function correctly.

@codecov
Copy link

codecov bot commented Jun 24, 2025

Codecov Report

Attention: Patch coverage is 0% with 18 lines in your changes missing coverage. Please review.

Project coverage is 26.20%. Comparing base (8711443) to head (4966a75).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-store/src/ha/default_ha_connection.rs 0.00% 18 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3520      +/-   ##
==========================================
+ Coverage   26.18%   26.20%   +0.01%     
==========================================
  Files         555      555              
  Lines       78648    78594      -54     
==========================================
  Hits        20593    20593              
+ Misses      58055    58001      -54     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Collaborator

@rocketmq-rust-bot rocketmq-rust-bot left a comment

Choose a reason for hiding this comment

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

LGTM

@rocketmq-rust-bot rocketmq-rust-bot merged commit 39397bd into main Jun 24, 2025
22 of 23 checks passed
@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved and removed ready to review waiting-review waiting review this PR labels Jun 24, 2025
@mxsm mxsm deleted the op-3519 branch July 3, 2025 13:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI review first Ai review pr first approved PR has approved auto merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Async socket handling migration using tokio-util for HA connection layer

3 participants