Skip to content

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Sep 22, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #4089

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Added support for broker synchronization information in the remoting protocol, enabling exchange of master address/HA address and flush offset data with JSON-compatible field names.
    • Improved human-readable formatting for this information to aid troubleshooting and monitoring.
  • Tests

    • Introduced comprehensive tests covering defaults, full initialization, JSON serialization/deserialization (including null fields), negative offset handling, cloning behavior, and display formatting to ensure reliability and correctness.

@Copilot Copilot AI review requested due to automatic review settings September 22, 2025 06:49
Copy link
Contributor

coderabbitai bot commented Sep 22, 2025

Walkthrough

Adds a new BrokerSyncInfo struct under protocol with serde support and Display, exposes the broker_sync_info module publicly, and includes unit tests for construction, serialization/deserialization, cloning, and formatting.

Changes

Cohort / File(s) Summary
Protocol module exports
rocketmq-remoting/src/protocol.rs
Publicly re-exports the new broker_sync_info module.
BrokerSyncInfo type and tests
rocketmq-remoting/src/protocol/broker_sync_info.rs
Introduces pub struct BrokerSyncInfo with serde camelCase, Display impl, Default, and comprehensive unit tests covering defaults, full init, JSON round-trip, null handling, negative offsets, cloning, and display formatting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I thump my paw—sync’s on the breeze,
A struct now hops through data trees.
CamelCase trails, offsets align,
Brokers chatter, “All is fine.”
I nose-twitch, test, then softly cheer—
New fields bloom; the code is clear. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "[ISSUE #4089]🚀Add BrokerSyncInfo struct" clearly identifies the primary change — adding the BrokerSyncInfo type — and is concise and specific enough for a teammate scanning history; the issue reference and emoji are minor noise but do not make it misleading.
Linked Issues Check ✅ Passed Linked issue #4089 requests adding a BrokerSyncInfo struct and this PR implements a public BrokerSyncInfo with the expected fields, serde camelCase renaming, Display/Default/Clone derives, and comprehensive unit tests for serialization, deserialization, defaults, and display, which fulfills the issue's stated objective; the issue contains no additional coded requirements to validate.
Out of Scope Changes Check ✅ Passed The changes are limited to adding a new protocol module file and exporting it from protocol.rs and do not modify other unrelated modules or functionality, so there are no detected out-of-scope edits relative to the linked issue.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature-4089

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@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 introduces a new BrokerSyncInfo struct to support broker synchronization functionality in the RocketMQ Rust implementation. The struct contains information needed for slave-master broker synchronization including HA addresses and flush offsets.

  • Adds a new BrokerSyncInfo struct with serialization/deserialization support
  • Implements Display trait for formatted output
  • Provides comprehensive test coverage for all functionality

Reviewed Changes

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

File Description
rocketmq-remoting/src/protocol/broker_sync_info.rs New file containing the complete BrokerSyncInfo struct implementation with serde support and Display trait
rocketmq-remoting/src/protocol.rs Adds module declaration to expose the new broker_sync_info module

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

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

🧹 Nitpick comments (4)
rocketmq-remoting/src/protocol/broker_sync_info.rs (3)

24-35: Make JSON more robust: add serde defaults, skip None, and derive Eq/PartialEq.

  • Forward/backward compat: without defaults, missing masterFlushOffset fails to deserialize.
  • Avoid writing nulls: skip serializing None for Option fields to reduce payload/noise.
  • Eq/PartialEq are handy for tests and API ergonomics.
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-#[serde(rename_all = "camelCase")]
+#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", default)]
 pub struct BrokerSyncInfo {
     /// For slave online sync, retrieve HA address before register
-    pub master_ha_address: Option<CheetahString>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub master_ha_address: Option<CheetahString>,

     /// Master flush offset
     pub master_flush_offset: i64,

     /// Master address
-    pub master_address: Option<CheetahString>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub master_address: Option<CheetahString>,
 }

37-54: Simplify Display and drop the line-continuation backslash.

Removes a stray space before the closing braces and reads clearer.

 impl Display for BrokerSyncInfo {
     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
-        write!(
-            f,
-            "BrokerSyncInfo {{ master_ha_address: {}, master_flush_offset: {}, master_address: {} \
-             }}",
-            match &self.master_ha_address {
-                Some(addr) => addr.as_str(),
-                None => "None",
-            },
-            self.master_flush_offset,
-            match &self.master_address {
-                Some(addr) => addr.as_str(),
-                None => "None",
-            }
-        )
+        write!(
+            f,
+            "BrokerSyncInfo {{ master_ha_address: {}, master_flush_offset: {}, master_address: {} }}",
+            self.master_ha_address.as_deref().unwrap_or("None"),
+            self.master_flush_offset,
+            self.master_address.as_deref().unwrap_or("None"),
+        )
     }
 }

84-97: Tighten JSON tests to assert exact structure, not substrings.

Substring checks can pass on malformed JSON. Validate full JSON keys/values.

-        let json = serde_json::to_string(&info).unwrap();
-
-        assert!(json.contains("masterHaAddress"));
-        assert!(json.contains("masterFlushOffset"));
-        assert!(json.contains("masterAddress"));
+        let json = serde_json::to_value(&info).unwrap();
+        assert_eq!(json["masterHaAddress"], "ha.address");
+        assert_eq!(json["masterFlushOffset"], 100);
+        assert_eq!(json["masterAddress"], "master.address");

Optionally, add a missing-field default test if you adopt #[serde(default)]:

+    #[test]
+    fn deserializes_with_missing_fields_defaults() {
+        // masterFlushOffset missing -> default(0); Option fields missing -> None
+        let json = r#"{}"#;
+        let info: BrokerSyncInfo = serde_json::from_str(json).unwrap();
+        assert!(info.master_ha_address.is_none());
+        assert_eq!(info.master_flush_offset, 0);
+        assert!(info.master_address.is_none());
+    }

Also applies to: 99-108

rocketmq-remoting/src/protocol.rs (1)

37-37: Ergonomics: re-export BrokerSyncInfo at protocol root.

Add a public re-export so callers can use protocol::BrokerSyncInfo. Verified: ripgrep shows only the type definition and tests in rocketmq-remoting/src/protocol/broker_sync_info.rs — no external references found.

 pub mod body;
 pub mod broker_sync_info;
+pub use broker_sync_info::BrokerSyncInfo;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c84503b and afaa482.

📒 Files selected for processing (2)
  • rocketmq-remoting/src/protocol.rs (1 hunks)
  • rocketmq-remoting/src/protocol/broker_sync_info.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: auto-approve
🔇 Additional comments (2)
rocketmq-remoting/src/protocol/broker_sync_info.rs (2)

121-130: Confirm offset domain; consider u64 if negatives are invalid.

If a flush offset cannot be negative in the protocol, switch to u64 and reject negatives at deserialization boundary. If negatives are allowed, keep i64.


160-170: Display tests look good.

Covers None paths and helps lock the printable contract.

Copy link

codecov bot commented Sep 22, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 26.57%. Comparing base (c84503b) to head (afaa482).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4090      +/-   ##
==========================================
+ Coverage   26.48%   26.57%   +0.09%     
==========================================
  Files         574      575       +1     
  Lines       81205    81308     +103     
==========================================
+ Hits        21507    21610     +103     
  Misses      59698    59698              

☔ 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 ed54eb9 into main Sep 22, 2025
25 of 27 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 Sep 22, 2025
@mxsm mxsm deleted the feature-4089 branch October 8, 2025 14:37
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 feature🚀 Suggest an idea for this project.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature🚀] Add BrokerSyncInfo struct

3 participants