Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[ISSUE #1830]🐰Add BatchAck struct for rust🚀 #1831

Merged
merged 2 commits into from
Dec 17, 2024
Merged

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Dec 17, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1830

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Added new dependencies to enhance functionality: bit-vec and serde_with.
    • Introduced a new module batch_ack for internal use.
    • Defined a public struct BatchAck for serialization and deserialization, with associated test cases to ensure functionality.
  • Bug Fixes

    • Implemented tests for the BatchAck struct to validate serialization, default values, and edge cases, ensuring robust error handling.

Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

This pull request introduces a new BatchAck struct in the RocketMQ Rust remoting module. The changes include adding two new dependencies (bit-vec and serde_with) in the Cargo.toml file and creating a new module batch_ack in the protocol body. The new BatchAck struct is designed for serialization and deserialization, with comprehensive test cases to validate its functionality.

Changes

File Change Summary
rocketmq-remoting/Cargo.toml Added dependencies: bit-vec (v0.8.0) with serde feature and serde_with (v3.11.0)
rocketmq-remoting/src/protocol/body.rs Added private module declaration for batch_ack
rocketmq-remoting/src/protocol/body/batch_ack.rs Created new file with BatchAck struct and unit tests

Assessment against linked issues

Objective Addressed Explanation
Add BatchAck struct for Rust [#1830]

Possibly related issues

  • [ISSUE #1725]🚀Add BatchAckMsg struct for rust✨ #1726: The addition of the BatchAckMsg struct in rocketmq-store/src/pop/batch_ack_msg.rs is related to the BatchAck struct introduced in the main PR, as both are part of the batch acknowledgment functionality in the messaging system and utilize Serde for serialization.

Poem

🚀 In the realm of Rust, a new struct takes flight,
BatchAck emerges, serialization's delight!
Bits and bytes dance with Serde's embrace,
A message of progress, with elegance and grace.
RocketMQ's journey continues bright! 🐰


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>, please review it.
    • 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 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 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 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. (Beta)
  • @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 🔥

@rocketmq-rust-bot rocketmq-rust-bot added the AI review first Ai review pr first label Dec 17, 2024
@rocketmq-rust-robot rocketmq-rust-robot added this to the v0.4.0 milestone Dec 17, 2024
@rocketmq-rust-robot rocketmq-rust-robot added the feature🚀 Suggest an idea for this project. label Dec 17, 2024
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: 2

🧹 Nitpick comments (2)
rocketmq-remoting/src/protocol/body/batch_ack.rs (2)

57-82: Enhance serialization test coverage.

The test should verify the exact JSON structure to ensure field renaming works as expected.

Add JSON structure verification:

     let serialized = serde_json::to_string(&batch_ack).unwrap();
+    // Verify JSON structure with renamed fields
+    let expected_json = r#"{"c":"group1","t":"topic1","r":"1","so":100,"q":1,"rq":2,"pt":123456789,"it":987654321,"b":[true,true,true,true,true,true,true,true]}"#;
+    assert_eq!(serialized, expected_json);
     let deserialized: BatchAck = serde_json::from_str(&serialized).unwrap();

21-49: Add validation and implement common traits.

Consider adding validation and implementing additional traits for better usability.

Add validation and traits:

-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
 pub struct BatchAck {
     // ... existing fields ...
 }

+impl BatchAck {
+    /// Validates the batch acknowledgment fields
+    pub fn validate(&self) -> Result<(), String> {
+        if self.consumer_group.is_empty() {
+            return Err("consumer_group cannot be empty".to_string());
+        }
+        if self.topic.is_empty() {
+            return Err("topic cannot be empty".to_string());
+        }
+        if self.queue_id < 0 {
+            return Err("queue_id cannot be negative".to_string());
+        }
+        if self.revive_queue_id < 0 {
+            return Err("revive_queue_id cannot be negative".to_string());
+        }
+        Ok(())
+    }
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0044912 and 11bd4e4.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • rocketmq-remoting/Cargo.toml (1 hunks)
  • rocketmq-remoting/src/protocol/body.rs (1 hunks)
  • rocketmq-remoting/src/protocol/body/batch_ack.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • rocketmq-remoting/src/protocol/body.rs
🔇 Additional comments (1)
rocketmq-remoting/Cargo.toml (1)

54-55: 🛠️ Refactor suggestion

Remove unused dependency and verify versions.

The serde_with dependency appears to be unused in the current implementation. Additionally, let's verify if these are the latest stable versions.

Consider removing the unused serde_with dependency:

 bit-vec = { version = "0.8.0", features = ["serde"] }
-serde_with = "3.11.0"

Comment on lines +21 to +49
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchAck {
#[serde(rename = "c", alias = "consumerGroup")]
pub consumer_group: String,

#[serde(rename = "t", alias = "topic")]
pub topic: String,

#[serde(rename = "r", alias = "retry")]
pub retry: String, // "1" if it's retry topic

#[serde(rename = "so", alias = "startOffset")]
pub start_offset: i64,

#[serde(rename = "q", alias = "queueId")]
pub queue_id: i32,

#[serde(rename = "rq", alias = "reviveQueueId")]
pub revive_queue_id: i32,

#[serde(rename = "pt", alias = "popTime")]
pub pop_time: i64,

#[serde(rename = "it", alias = "invisibleTime")]
pub invisible_time: i64,

#[serde(rename = "b", alias = "bitSet")]
pub bit_set: BitVec,
}
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

Add documentation and optimize field types.

The struct lacks documentation explaining its purpose and field descriptions. Additionally, the retry field could be optimized.

Consider these improvements:

 #[derive(Debug, Serialize, Deserialize)]
+/// Represents a batch acknowledgment for message processing in RocketMQ.
+/// Used to track the status of multiple messages in a single batch operation.
 pub struct BatchAck {
     #[serde(rename = "c", alias = "consumerGroup")]
+    /// The consumer group that processed the messages
     pub consumer_group: String,
 
     #[serde(rename = "t", alias = "topic")]
+    /// The topic from which messages were consumed
     pub topic: String,
 
     #[serde(rename = "r", alias = "retry")]
-    pub retry: String, // "1" if it's retry topic
+    #[serde(serialize_with = "serialize_retry", deserialize_with = "deserialize_retry")]
+    /// Indicates if this is a retry topic
+    pub retry: bool,

Add these helper functions for retry serialization:

fn serialize_retry<S>(retry: &bool, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(if *retry { "1" } else { "0" })
}

fn deserialize_retry<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    Ok(s == "1")
}

Copy link

codecov bot commented Dec 17, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 28.35%. Comparing base (0044912) to head (4136cc5).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1831      +/-   ##
==========================================
+ Coverage   28.26%   28.35%   +0.09%     
==========================================
  Files         473      474       +1     
  Lines       65871    65957      +86     
==========================================
+ Hits        18617    18703      +86     
  Misses      47254    47254              

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

@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution 🎉. CodeRabbit(AI) will review your code first 🔥

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 (2)
rocketmq-remoting/src/protocol/body/batch_ack.rs (2)

58-82: Enhance tests with varied BitVec patterns

In the batch_ack_serialization test, the bit_set is initialized with all true values of length 8. Consider adding tests with BitVecs of different lengths and mixed true and false values to ensure that serialization and deserialization handle various bit_set scenarios correctly.


71-72: Add assertion to verify serialized JSON output

Currently, the test serializes the BatchAck instance but does not verify the serialized JSON string's content. Adding an assertion to check the serialized output can help ensure that the serialization process produces the expected JSON structure.

You can modify the test as follows:

let serialized = serde_json::to_string(&batch_ack).unwrap();
// Add this assertion
assert!(serialized.contains("\"c\":\"group1\""));

Or compare the entire serialized string if the order of fields is consistent.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 11bd4e4 and 4136cc5.

📒 Files selected for processing (1)
  • rocketmq-remoting/src/protocol/body/batch_ack.rs (1 hunks)
🔇 Additional comments (1)
rocketmq-remoting/src/protocol/body/batch_ack.rs (1)

21-49: Add documentation comments and optimize retry field type

The BatchAck struct lacks documentation comments explaining its purpose and the role of each field. Additionally, the retry field is of type String, but it represents a boolean value ("1" if it's a retry topic). Changing the retry field to a bool type with custom serialization can improve code clarity and type safety.

* See the License for the specific language governing permissions and
* limitations under the License.
*/
use bit_vec::BitVec;
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

Consider replacing bit-vec crate with bitvec

The bit-vec crate is deprecated in favor of the bitvec crate, which is more actively maintained and offers additional features. Updating to bitvec can ensure better future support and performance enhancements.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
AI review first Ai review pr first approved PR has approved auto merge feature🚀 Suggest an idea for this project.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature🚀] Add BatchAck struct for rust
3 participants