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

[ISSUE #1474]⚡Optimize derive RequestHeaderCodec and add required attribute🚀 #1475

Merged
merged 2 commits into from
Dec 1, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Dec 1, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1474

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Introduced a new required attribute for the RequestHeaderCodec macro, enhancing its functionality.
    • Improved error handling for required fields during serialization and deserialization processes.
  • Bug Fixes

    • Enhanced robustness by raising errors for missing required fields, ensuring clearer error messages.

Copy link
Contributor

coderabbitai bot commented Dec 1, 2024

Walkthrough

The changes introduced in this pull request enhance the RequestHeaderCodec procedural macro by allowing it to accept an additional required attribute. This modification affects how struct fields are processed within the macro, specifically in the request_header_codec_inner function. The new logic enforces checks for required fields during serialization and deserialization, raising errors when required fields are missing or incorrectly parsed.

Changes

File Change Summary
rocketmq-macros/src/lib.rs Updated #[proc_macro_derive(RequestHeaderCodec)] to #[proc_macro_derive(RequestHeaderCodec, attributes(required))].
rocketmq-macros/src/request_header_custom.rs Enhanced request_header_codec_inner to handle required attribute for struct fields, including error handling for missing required fields.

Assessment against linked issues

Objective Addressed Explanation
Optimize derive RequestHeaderCodec and add required attribute (#1474)

🐇 In the meadow, fields do bloom,
With required checks, there's less room for gloom.
If a field is missing, an error will say,
"Fill me with value, don't let me decay!"
Hops and skips, the code is bright,
With attributes added, it feels just right! 🌼


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 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-robot rocketmq-rust-robot added enhancement⚡️ New feature or request feature🚀 Suggest an idea for this project. labels Dec 1, 2024
@rocketmq-rust-robot rocketmq-rust-robot added this to the v0.4.0 milestone Dec 1, 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: 0

🧹 Outside diff range and nitpick comments (1)
rocketmq-macros/src/request_header_custom.rs (1)

132-196: Refactor to reduce code duplication in 'FromMap' implementation

The handling of required fields introduces repetitive code blocks for different data types and conditions. Consider refactoring to abstract common logic into helper functions or use macros to eliminate duplication, which will improve maintainability and readability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8c653e8 and a218af5.

📒 Files selected for processing (2)
  • rocketmq-macros/src/lib.rs (1 hunks)
  • rocketmq-macros/src/request_header_custom.rs (2 hunks)
🔇 Additional comments (3)
rocketmq-macros/src/lib.rs (1)

29-29: Correctly added 'required' attribute to 'RequestHeaderCodec' macro

The addition allows the macro to accept the required attribute on struct fields, enabling enhanced control over serialization and deserialization of required fields.

rocketmq-macros/src/request_header_custom.rs (2)

50-59: Properly implemented detection of 'required' attribute on struct fields

The code correctly checks for the presence of the required attribute and sets the required flag accordingly.


132-196: Ensure thorough testing of 'required' attribute handling

Verify that the macro correctly enforces required fields during deserialization and that appropriate errors are raised when required fields are missing or invalid.

Copy link

codecov bot commented Dec 1, 2024

Codecov Report

Attention: Patch coverage is 54.87805% with 37 lines in your changes missing coverage. Please review.

Project coverage is 22.31%. Comparing base (8c653e8) to head (cfd33b3).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-macros/src/request_header_custom.rs 54.87% 37 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1475      +/-   ##
==========================================
- Coverage   22.32%   22.31%   -0.01%     
==========================================
  Files         450      450              
  Lines       58248    58289      +41     
==========================================
+ Hits        13003    13007       +4     
- Misses      45245    45282      +37     

☔ 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: 2

🧹 Outside diff range and nitpick comments (2)
rocketmq-macros/src/request_header_custom.rs (2)

129-162: Reduce code duplication in Option type deserialization

The error handling logic is duplicated between String and non-String types. Consider extracting the common error handling into a helper macro or function.

Example approach:

macro_rules! handle_required_field {
    ($map:expr, $field:expr, $parser:expr) => {
        if required {
            Some($map.get(&cheetah_string::CheetahString::from_static_str(Self::#static_name))
                .ok_or(Self::Error::RemotingCommandError(
                    format!("Missing {} field", Self::#static_name),
                ))?
                .and_then($parser)
                .ok_or(Self::Error::RemotingCommandError(
                    format!("Parse {} field error", Self::#static_name)
                ))?)
        } else {
            $map.get(&cheetah_string::CheetahString::from_static_str(Self::#static_name))
                .and_then($parser)
        }
    };
}
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 133-141: rocketmq-macros/src/request_header_custom.rs#L133-L141
Added lines #L133 - L141 were not covered by tests


[warning] 148-155: rocketmq-macros/src/request_header_custom.rs#L148-L155
Added lines #L148 - L155 were not covered by tests


Line range hint 1-227: Improve documentation and error handling

While the implementation is functionally correct, consider these improvements:

  1. Add documentation explaining the required attribute usage and behavior
  2. Consider including the field type in error messages to aid debugging
  3. Add examples in doc comments showing common use cases

Example documentation:

/// Derives RequestHeaderCodec for a struct
/// 
/// # Attributes
/// - `required`: Mark a field as required. Missing or unparseable required fields
///   will result in an error during deserialization.
/// 
/// # Example
/// ```
/// #[derive(RequestHeaderCodec)]
/// struct MyHeader {
///     #[required]
///     id: String,
///     optional_field: Option<i32>,
/// }
/// ```
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 53-57: rocketmq-macros/src/request_header_custom.rs#L53-L57
Added lines #L53 - L57 were not covered by tests


[warning] 85-85: rocketmq-macros/src/request_header_custom.rs#L85
Added line #L85 was not covered by tests


[warning] 113-113: rocketmq-macros/src/request_header_custom.rs#L113
Added line #L113 was not covered by tests


[warning] 133-141: rocketmq-macros/src/request_header_custom.rs#L133-L141
Added lines #L133 - L141 were not covered by tests


[warning] 148-155: rocketmq-macros/src/request_header_custom.rs#L148-L155
Added lines #L148 - L155 were not covered by tests


[warning] 167-172: rocketmq-macros/src/request_header_custom.rs#L167-L172
Added lines #L167 - L172 were not covered by tests


[warning] 180-186: rocketmq-macros/src/request_header_custom.rs#L180-L186
Added lines #L180 - L186 were not covered by tests

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a218af5 and cfd33b3.

📒 Files selected for processing (1)
  • rocketmq-macros/src/request_header_custom.rs (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
rocketmq-macros/src/request_header_custom.rs

[warning] 53-57: rocketmq-macros/src/request_header_custom.rs#L53-L57
Added lines #L53 - L57 were not covered by tests


[warning] 85-85: rocketmq-macros/src/request_header_custom.rs#L85
Added line #L85 was not covered by tests


[warning] 113-113: rocketmq-macros/src/request_header_custom.rs#L113
Added line #L113 was not covered by tests


[warning] 133-141: rocketmq-macros/src/request_header_custom.rs#L133-L141
Added lines #L133 - L141 were not covered by tests


[warning] 148-155: rocketmq-macros/src/request_header_custom.rs#L148-L155
Added lines #L148 - L155 were not covered by tests


[warning] 167-172: rocketmq-macros/src/request_header_custom.rs#L167-L172
Added lines #L167 - L172 were not covered by tests


[warning] 180-186: rocketmq-macros/src/request_header_custom.rs#L180-L186
Added lines #L180 - L186 were not covered by tests

🔇 Additional comments (1)
rocketmq-macros/src/request_header_custom.rs (1)

163-192: Add test coverage for all deserialization paths

The deserialization logic for non-Option types needs test coverage for:

  • Required fields with valid/invalid/missing values
  • Non-required fields with default values
  • Different field types (String, CheetahString, numeric types)

Consider adding tests for:

  1. Required fields that are missing
  2. Required fields with invalid values
  3. Non-required fields defaulting correctly
  4. String vs numeric type parsing

Would you like me to help generate comprehensive test cases?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 167-172: rocketmq-macros/src/request_header_custom.rs#L167-L172
Added lines #L167 - L172 were not covered by tests


[warning] 180-186: rocketmq-macros/src/request_header_custom.rs#L180-L186
Added lines #L180 - L186 were not covered by tests

Comment on lines +73 to +127
if let Some(value) = has_option {
let type_name = get_type_name(value);
if type_name == "CheetahString" {
quote! {
if let Some(ref value) = self.#field_name {
map.insert (
cheetah_string::CheetahString::from_static_str(Self::#static_name),
value.clone()
);
}
}
} else if type_name == "String" {
quote! {
} else if type_name == "String" {
quote! {
if let Some(ref value) = self.#field_name {
map.insert (
cheetah_string::CheetahString::from_static_str(Self::#static_name),
cheetah_string::CheetahString::from_string(value.clone())
);
}
}
} else {
quote! {
} else {
quote! {
if let Some(value) = self.#field_name {
map.insert (
cheetah_string::CheetahString::from_static_str(Self::#static_name),
cheetah_string::CheetahString::from_string(value.to_string())
);
}
}
}
} else {
let type_name = get_type_name(&field.ty);
if type_name == "CheetahString" {
quote! {
}
} else {
let type_name = get_type_name(&field.ty);
if type_name == "CheetahString" {
quote! {
map.insert (
cheetah_string::CheetahString::from_static_str(Self::#static_name),
self.#field_name.clone()
);
}
} else if type_name == "String" {
quote! {
} else if type_name == "String" {
quote! {
map.insert (
cheetah_string::CheetahString::from_static_str(Self::#static_name),
cheetah_string::CheetahString::from_string(self.#field_name.clone())
);
}
} else {
quote! {
} else {
quote! {
map.insert (
cheetah_string::CheetahString::from_static_str(Self::#static_name),
cheetah_string::CheetahString::from_string(self.#field_name.to_string())
);
}
}
},
// build FromMap impl
if let Some(value) = has_option {
let type_name = get_type_name(value);
if type_name == "CheetahString" || type_name == "String" {
quote! {
}
},
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

Add validation for required fields during serialization

The serialization logic doesn't enforce the required attribute constraints. For Option types, if a field is marked as required and contains None, it should return an error instead of silently skipping the field.

Consider adding validation like this:

 if let Some(ref value) = self.#field_name {
     map.insert(/*...*/);
+} else if required {
+    return None; // or consider returning Result instead of Option
 }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 85-85: rocketmq-macros/src/request_header_custom.rs#L85
Added line #L85 was not covered by tests


[warning] 113-113: rocketmq-macros/src/request_header_custom.rs#L113
Added line #L113 was not covered by tests

Comment on lines +47 to +62
.iter()
.map(|field| {
let field_name = field.ident.as_ref().unwrap();
let mut required = false;

for attr in &field.attrs {
if let Some(ident) = attr.path().get_ident() {
if ident == "required" {
required = true;
}
}
}

//Determining whether it is an Option type or a direct data type
//This will lead to different ways of processing in the future.
let has_option = is_option_type(&field.ty);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing test coverage for required attribute processing

The codebase lacks test coverage for the new required attribute processing in the RequestHeaderCodec derive macro. This could lead to potential issues with:

  • Validation of required fields during serialization/deserialization
  • Edge cases in attribute parsing
  • Interaction with Option types

Please add test cases to cover:

  1. Struct fields with required attribute
  2. Fields without the attribute
  3. Required fields with Option types
  4. Required fields with non-Option types

Note: The verification revealed no existing tests in the rocketmq-macros crate, making this a critical gap in test coverage for the new functionality.

🔗 Analysis chain

Add test coverage for required attribute processing

The new attribute processing logic needs test coverage to ensure correct behavior with:

  • Fields marked with required
  • Fields without the attribute
  • Invalid attribute usage scenarios

Would you like me to help generate comprehensive test cases for the attribute processing?

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check existing test coverage for attribute processing
fd -e rs . tests/ -x rg -l "required"

Length of output: 131


Script:

#!/bin/bash
# First, let's find all test files in the repository
fd -e rs . -x rg -l "required"

# Then, let's check the macro usage in tests
rg "#\[derive\(.*RequestHeaderCodec.*\)\]" -A 10

# Finally, let's check if there are any test modules or integration tests
rg "mod tests" -A 10

Length of output: 66341


Script:

#!/bin/bash
# Let's check for test files in the macros crate specifically
fd -e rs . rocketmq-macros/tests/

# Let's also check for any test modules within the macro implementation file
rg "^mod tests" rocketmq-macros/src/request_header_custom.rs -A 10

# And check for any test attributes in the macro crate
rg "#\[test\]" rocketmq-macros/src/

Length of output: 252

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 53-57: rocketmq-macros/src/request_header_custom.rs#L53-L57
Added lines #L53 - L57 were not covered by tests

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 feature🚀 Suggest an idea for this project.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Optimize derive RequestHeaderCodec and add required attribute
4 participants