Skip to content

[ISSUE #3481]⚡️Enhancement DefaultHAConnection to simplify socket stream handling and improve readability✨ #3482

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

Merged
merged 1 commit into from
Jun 18, 2025

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Jun 18, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #3481

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • Refactor
    • Improved internal handling of network connections for more efficient and simplified resource management.
  • Chores
    • Updated placeholder methods with clearer messages for unimplemented functionality.
    • Added a new placeholder method for future transfer notification support.

@Copilot Copilot AI review requested due to automatic review settings June 18, 2025 15:46
Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

Walkthrough

The changes refactor the socket handling in DefaultHAConnection and its read/write services by replacing shared, lock-protected TcpStream usage with direct ownership of split OwnedReadHalf and OwnedWriteHalf. This simplifies concurrency control and access patterns. Additionally, a stub method notify_transfer_some is added to DefaultHAService.

Changes

File(s) Change Summary
rocketmq-store/src/ha/default_ha_connection.rs Refactored to replace shared, lock-protected TcpStream with owned OwnedReadHalf/OwnedWriteHalf in services; updated buffer and socket access logic; commented out close implementation.
rocketmq-store/src/ha/default_ha_service.rs Added async stub method notify_transfer_some; updated get_default_message_store to include a message in unimplemented!().

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DefaultHAConnection
    participant ReadSocketService
    participant WriteSocketService

    Client->>DefaultHAConnection: new(TcpStream)
    DefaultHAConnection->>DefaultHAConnection: split TcpStream into OwnedReadHalf/OwnedWriteHalf
    DefaultHAConnection->>ReadSocketService: pass OwnedReadHalf
    DefaultHAConnection->>WriteSocketService: pass OwnedWriteHalf
    ReadSocketService->>ReadSocketService: read loop (no locking)
    WriteSocketService->>WriteSocketService: write loop (no locking)
Loading

Assessment against linked issues

Objective Addressed Explanation
Simplify socket stream handling and improve readability in DefaultHAConnection (#3481)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Added async stub method notify_transfer_some to DefaultHAService (rocketmq-store/src/ha/default_ha_service.rs) This addition is unrelated to socket stream handling simplification or readability in DefaultHAConnection.

Poem

In tunnels of code where sockets once hid,
Now split halves scurry—no locks on the grid!
Read and write, each with their own,
Simpler paths are clearly shown.
A hop, a leap, a bug-free cheer—
The rabbit approves: the code is clear! 🐇✨

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

@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💥.

Copy link
Contributor

@Copilot 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 enhances the DefaultHAConnection by simplifying socket stream handling and improving readability, as well as adding a new placeholder method to the DefaultHAService interface.

  • Replace shared RwLock-wrapped TcpStream with an Option and split it into OwnedReadHalf/OwnedWriteHalf for read and write services
  • Add a new async method notify_transfer_some in DefaultHAService with an explicit unimplemented message
  • Update the socket stream handling in both ReadSocketService and WriteSocketService to pass ownership via Option

Reviewed Changes

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

File Description
rocketmq-store/src/ha/default_ha_service.rs Added a more descriptive unimplemented message and a new notify_transfer_some async method
rocketmq-store/src/ha/default_ha_connection.rs Refactored socket_stream handling by removing RwLock, using Option, and updating service creation with OwnedReadHalf/OwnedWriteHalf

@@ -104,9 +107,12 @@ impl DefaultHAConnection {
// Start flow monitor
self.flow_monitor.start().await;

let socket_stream = self.socket_stream.take().unwrap();
Copy link
Preview

Copilot AI Jun 18, 2025

Choose a reason for hiding this comment

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

Using unwrap() here can lead to a panic if start() is called more than once or if socket_stream is unexpectedly None. It is recommended to handle this case with proper error handling.

Suggested change
let socket_stream = self.socket_stream.take().unwrap();
let socket_stream = match self.socket_stream.take() {
Some(stream) => stream,
None => {
return Err(HAConnectionError::SocketStreamUnavailable(
"Socket stream is already taken or not initialized".to_string(),
));
}
};

Copilot uses AI. Check for mistakes.

Comment on lines +175 to +180
/*let mut socket_guard = self.socket_stream.write().await;
if let Some(mut socket) = socket_guard.take() {
if let Err(e) = socket.shutdown().await {
error!("Error closing socket: {}", e);
}
}
}*/
Copy link
Preview

Copilot AI Jun 18, 2025

Choose a reason for hiding this comment

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

The socket closing logic is commented out, which could lead to resource leaks if the connection is not properly closed. It is recommended to either remove the commented-out code or implement the socket shutdown logic.

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: 3

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

352-353: Call into unimplemented notify_transfer_some()

This awaits a function that panics; the read task will terminate immediately.
Defer the call behind a feature flag or finish the implementation before merging.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 391b824 and 7d75eb6.

📒 Files selected for processing (2)
  • rocketmq-store/src/ha/default_ha_connection.rs (20 hunks)
  • rocketmq-store/src/ha/default_ha_service.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: auto-approve
  • GitHub Check: build
  • GitHub Check: test

Comment on lines +58 to 65
unimplemented!(" get_default_message_store method is not implemented");
}

pub async fn notify_transfer_some(&self, _offset: i64) {
// This method is a placeholder for notifying transfer operations.
// The actual implementation would depend on the specific requirements of the HA service.
unimplemented!(" notify_transfer_some method is not implemented");
}
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

Unimplemented methods are already invoked – will panic at runtime

notify_transfer_some() and get_default_message_store() are called by the connection logic added in this PR, but both are still unimplemented!().
The first read from a slave will therefore abort the whole HA connection with a panic.

Either wire these methods up now or gate their callers behind a feature-flag / TODO path so the new code can run without crashing.

🤖 Prompt for AI Agents
In rocketmq-store/src/ha/default_ha_service.rs around lines 58 to 65, the
methods notify_transfer_some() and get_default_message_store() are currently
unimplemented but are called by the connection logic, causing runtime panics. To
fix this, either implement the actual logic for these methods now or modify the
callers to conditionally invoke these methods only when a feature flag is
enabled or during a TODO phase, preventing the panic and allowing the code to
run safely without crashing.

Comment on lines +110 to +112
let socket_stream = self.socket_stream.take().unwrap();
let (reader, writer) = socket_stream.into_split();

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

unwrap() introduces start-time panic on second call

self.socket_stream.take().unwrap() will panic if start() is invoked twice (or after a previous failed start).
Return a proper error instead of unwrapping.

-let socket_stream = self.socket_stream.take().unwrap();
+let socket_stream = self
+    .socket_stream
+    .take()
+    .ok_or_else(|| HAConnectionError::Connection("socket already taken".into()))?;
📝 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
let socket_stream = self.socket_stream.take().unwrap();
let (reader, writer) = socket_stream.into_split();
let socket_stream = self
.socket_stream
.take()
.ok_or_else(|| HAConnectionError::Connection("socket already taken".into()))?;
let (reader, writer) = socket_stream.into_split();
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/default_ha_connection.rs around lines 110 to 112,
replace the use of unwrap() on self.socket_stream.take() with proper error
handling to avoid panics if start() is called multiple times or after a failure.
Check if socket_stream is Some before taking it, and return an appropriate error
if it is None instead of unwrapping.

Comment on lines +315 to +346
if buffer.has_remaining_mut() {
buffer.clear();
process_position = 0;
}
match timeout(
Duration::from_secs(1),
socket.read(&mut buffer[process_position..]),
)
.await
{
Ok(Ok(bytes_read)) => {
if bytes_read > 0 {
last_read_timestamp = Instant::now();
// Process the read data
if buffer.len() - process_position >= REPORT_HEADER_SIZE {
//In general, pos is equal to buffer.len(), mainly to handle
// the alignment issue of the buffer.
let pos = buffer.len() - (buffer.len() % REPORT_HEADER_SIZE);
let read_offset = i64::from_be_bytes([
buffer[pos - 8],
buffer[pos - 7],
buffer[pos - 6],
buffer[pos - 5],
buffer[pos - 4],
buffer[pos - 3],
buffer[pos - 2],
buffer[pos - 1],
]);
process_position = pos;
slave_ack_offset.store(read_offset, Ordering::SeqCst);
if slave_request_offset.load(Ordering::SeqCst) < 0 {
slave_request_offset.store(read_offset, Ordering::SeqCst);
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

Compile-time blocker: invalid buffer handling

Problems inside the read loop:

  1. has_remaining_mut() does not exist for Vec<u8> – compilation fails.
  2. Calling buffer.clear() shrinks len to 0, yet the subsequent slice buffer[process_position..] assumes a non-zero length → panic if it compiled.
  3. Re-parsing logic relies on buffer.len() after it was just cleared.

Consider replacing the whole buffer with bytes::BytesMut and use its API, or keep a fixed-size Vec without clearing len.

Quick minimal fix:

- if buffer.has_remaining_mut() {
-     buffer.clear();
-     process_position = 0;
- }
+if process_position >= buffer.len() - REPORT_HEADER_SIZE {
+    process_position = 0;
+}

…but switching to BytesMut is cleaner.

📝 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 buffer.has_remaining_mut() {
buffer.clear();
process_position = 0;
}
match timeout(
Duration::from_secs(1),
socket.read(&mut buffer[process_position..]),
)
.await
{
Ok(Ok(bytes_read)) => {
if bytes_read > 0 {
last_read_timestamp = Instant::now();
// Process the read data
if buffer.len() - process_position >= REPORT_HEADER_SIZE {
//In general, pos is equal to buffer.len(), mainly to handle
// the alignment issue of the buffer.
let pos = buffer.len() - (buffer.len() % REPORT_HEADER_SIZE);
let read_offset = i64::from_be_bytes([
buffer[pos - 8],
buffer[pos - 7],
buffer[pos - 6],
buffer[pos - 5],
buffer[pos - 4],
buffer[pos - 3],
buffer[pos - 2],
buffer[pos - 1],
]);
process_position = pos;
slave_ack_offset.store(read_offset, Ordering::SeqCst);
if slave_request_offset.load(Ordering::SeqCst) < 0 {
slave_request_offset.store(read_offset, Ordering::SeqCst);
// Minimal fix: reset position instead of clearing the Vec
- if buffer.has_remaining_mut() {
- buffer.clear();
- process_position = 0;
- }
+ if process_position >= buffer.len() - REPORT_HEADER_SIZE {
+ process_position = 0;
+ }
match timeout(
Duration::from_secs(1),
socket.read(&mut buffer[process_position..]),
)
.await
{
Ok(Ok(bytes_read)) => {
if bytes_read > 0 {
last_read_timestamp = Instant::now();
// Process the read data
if buffer.len() - process_position >= REPORT_HEADER_SIZE {
//In general, pos is equal to buffer.len(), mainly to handle
// the alignment issue of the buffer.
let pos = buffer.len() - (buffer.len() % REPORT_HEADER_SIZE);
let read_offset = i64::from_be_bytes([
buffer[pos - 8],
buffer[pos - 7],
buffer[pos - 6],
buffer[pos - 5],
buffer[pos - 4],
buffer[pos - 3],
buffer[pos - 2],
buffer[pos - 1],
]);
process_position = pos;
slave_ack_offset.store(read_offset, Ordering::SeqCst);
if slave_request_offset.load(Ordering::SeqCst) < 0 {
slave_request_offset.store(read_offset, Ordering::SeqCst);
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/default_ha_connection.rs around lines 315 to 346, the
code incorrectly uses has_remaining_mut() on a Vec<u8> which does not exist,
clears the buffer causing its length to become zero, and then slices it assuming
a non-zero length, leading to potential panics and compilation errors. To fix
this, replace the Vec<u8> buffer with a bytes::BytesMut buffer to properly
manage capacity and length, use BytesMut's API for checking remaining capacity
and clearing, and adjust the slicing and parsing logic accordingly to avoid
invalid indexing after clearing.

Copy link

codecov bot commented Jun 18, 2025

Codecov Report

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

Project coverage is 26.35%. Comparing base (2a65fd0) to head (7d75eb6).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-store/src/ha/default_ha_connection.rs 0.00% 60 Missing ⚠️
rocketmq-store/src/ha/default_ha_service.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3482      +/-   ##
==========================================
- Coverage   26.40%   26.35%   -0.06%     
==========================================
  Files         547      547              
  Lines       78063    77900     -163     
==========================================
- Hits        20616    20532      -84     
+ Misses      57447    57368      -79     

☔ 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 eb1649a into main Jun 18, 2025
22 of 24 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 18, 2025
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 enhancement⚡️ New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Enhancement DefaultHAConnection to simplify socket stream handling and improve readability
3 participants