Skip to content

[ISSUE #2338]🤡Add RequestTask for rust🧑‍💻 #2406

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
Jan 25, 2025

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Jan 25, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #2338
closes #2335
closes #1917

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features
    • Added a new RequestTask module to support asynchronous task management
    • Introduced a flexible task execution framework with runtime control mechanisms
    • Implemented asynchronous task handling with stop/run capabilities

Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Walkthrough

A new module request_task has been added to the RocketMQ Remoting library in Rust. The module introduces a RequestTask struct designed to manage asynchronous tasks with capabilities for controlling execution, tracking creation timestamp, and providing a framework for future response handling. The implementation supports asynchronous execution through the Future trait, allowing flexible task management with built-in stop/run controls.

Changes

File Change Summary
rocketmq-remoting/src/base.rs Added public module declaration for request_task
rocketmq-remoting/src/base/request_task.rs Created new RequestTask struct with async execution methods, Future trait implementation

Assessment against linked issues

Objective Addressed Explanation
[#2338] Add RequestTask for Rust

Suggested Labels

feature🚀, approved, auto merge, AI review first

Suggested Reviewers

  • TeslaRustor
  • SpaceXCN
  • rocketmq-rust-bot

Poem

🚀 A task that runs with grace and might,
In RocketMQ's async delight,
With timestamps neat and stop-run smart,
A rabbit's code has found its art!
Async magic takes its flight! 🐰✨


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🔥!

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

codecov bot commented Jan 25, 2025

Codecov Report

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

Project coverage is 28.60%. Comparing base (4523086) to head (78c9d32).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-remoting/src/base/request_task.rs 0.00% 37 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2406      +/-   ##
==========================================
- Coverage   28.61%   28.60%   -0.02%     
==========================================
  Files         507      508       +1     
  Lines       73337    73374      +37     
==========================================
  Hits        20989    20989              
- Misses      52348    52385      +37     

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

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

🧹 Nitpick comments (1)
rocketmq-remoting/src/base/request_task.rs (1)

36-49: Enhance constructor with validation and error handling.

The constructor should validate inputs and handle potential error cases:

  1. Validate channel state
  2. Consider adding optional parameters for initial stop state
  3. Add builder pattern for better construction flexibility
 impl RequestTask {
+    /// Creates a new RequestTask with the given parameters.
+    ///
+    /// # Arguments
+    /// * `runnable` - The function to execute
+    /// * `channel` - Communication channel
+    /// * `request` - Original request command
+    ///
+    /// # Returns
+    /// Result<RequestTask, Error> indicating success or failure
     pub fn new(
         runnable: Arc<dyn Fn() + Send + Sync>,
         channel: Channel,
         request: RemotingCommand,
-    ) -> Self {
+    ) -> Result<Self, Box<dyn std::error::Error>> {
+        if !channel.is_active() {
+            return Err("Channel is not active".into());
+        }
+
         Self {
             runnable,
             create_timestamp: get_current_millis(),
             channel,
             request,
             stop_run: Arc::new(parking_lot::Mutex::new(false)),
-        }
+        }.into()
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4523086 and 78c9d32.

📒 Files selected for processing (2)
  • rocketmq-remoting/src/base.rs (1 hunks)
  • rocketmq-remoting/src/base/request_task.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • rocketmq-remoting/src/base.rs
⏰ 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, nightly)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: test
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: build
  • GitHub Check: auto-approve
  • GitHub Check: build (ubuntu-latest, stable)

Comment on lines +64 to +66
pub async fn return_response(&self, _code: i32, _remark: String) {
unimplemented!("return_response")
}
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

Implement return_response method.

The return_response method is currently unimplemented. This could lead to runtime panics.

-    pub async fn return_response(&self, _code: i32, _remark: String) {
-        unimplemented!("return_response")
+    pub async fn return_response(&self, code: i32, remark: String) -> Result<(), Box<dyn std::error::Error>> {
+        let response = RemotingCommand::create_response_command(code)?;
+        response.set_remark(remark);
+        self.channel.write_and_flush(response).await
     }
📝 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
pub async fn return_response(&self, _code: i32, _remark: String) {
unimplemented!("return_response")
}
pub async fn return_response(&self, code: i32, remark: String) -> Result<(), Box<dyn std::error::Error>> {
let response = RemotingCommand::create_response_command(code)?;
response.set_remark(remark);
self.channel.write_and_flush(response).await
}

Comment on lines +28 to +34
pub struct RequestTask {
runnable: Arc<dyn Fn() + Send + Sync>,
create_timestamp: u64,
channel: Channel,
request: RemotingCommand,
stop_run: Arc<parking_lot::Mutex<bool>>,
}
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 consider error handling improvements.

The RequestTask struct could benefit from the following improvements:

  1. Add documentation comments (///) explaining the purpose of the struct and each field
  2. Consider using Result type for the runnable to handle potential errors
  3. Consider using Arc<AsyncFn> instead of Arc<Fn> for better async support
+/// A task that can be executed asynchronously with built-in execution control.
 pub struct RequestTask {
+    /// The async function to be executed
-    runnable: Arc<dyn Fn() + Send + Sync>,
+    runnable: Arc<dyn Fn() -> Result<(), Box<dyn std::error::Error>> + Send + Sync>,
+    /// Timestamp when the task was created
     create_timestamp: u64,
+    /// Communication channel
     channel: Channel,
+    /// Original request command
     request: RemotingCommand,
+    /// Flag to control task execution
     stop_run: Arc<parking_lot::Mutex<bool>>,
 }
📝 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
pub struct RequestTask {
runnable: Arc<dyn Fn() + Send + Sync>,
create_timestamp: u64,
channel: Channel,
request: RemotingCommand,
stop_run: Arc<parking_lot::Mutex<bool>>,
}
/// A task that can be executed asynchronously with built-in execution control.
pub struct RequestTask {
/// The async function to be executed
runnable: Arc<dyn Fn() -> Result<(), Box<dyn std::error::Error>> + Send + Sync>,
/// Timestamp when the task was created
create_timestamp: u64,
/// Communication channel
channel: Channel,
/// Original request command
request: RemotingCommand,
/// Flag to control task execution
stop_run: Arc<parking_lot::Mutex<bool>>,
}

Comment on lines +77 to +87
impl Future for RequestTask {
type Output = ();

fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
if !self.is_stop_run() {
(self.runnable)();
return Poll::Ready(());
}
Poll::Pending
}
}
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

Improve Future implementation with proper error handling and waking mechanism.

The Future implementation needs several improvements:

  1. Handle errors from runnable
  2. Add waking mechanism when stop_run changes
  3. Prevent infinite pending state
  4. Consider using proper async execution
-impl Future for RequestTask {
+impl Future for RequestTask {
     type Output = ();

     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
         if !self.is_stop_run() {
-            (self.runnable)();
-            return Poll::Ready(());
+            match (self.runnable)() {
+                Ok(_) => Poll::Ready(()),
+                Err(e) => {
+                    log::error!("Task execution failed: {}", e);
+                    Poll::Ready(())
+                }
+            }
+        } else {
+            // Register waker to be notified when stop_run changes
+            let waker = cx.waker().clone();
+            let mut stop_run = self.stop_run.lock();
+            if *stop_run {
+                // Store waker to be called when stop_run is set to false
+                // This requires adding a waker field to the struct
+                Poll::Pending
+            } else {
+                Poll::Ready(())
+            }
         }
-        Poll::Pending
     }
 }

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

Comment on lines +51 to +62
pub fn set_stop_run(&self, stop_run: bool) {
let mut stop_run_lock = self.stop_run.lock();
*stop_run_lock = stop_run;
}

pub fn get_create_timestamp(&self) -> u64 {
self.create_timestamp
}

pub fn is_stop_run(&self) -> bool {
*self.stop_run.lock()
}
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 deadlock prevention and documentation to utility methods.

The state management methods need documentation and deadlock prevention:

  1. Consider using a timeout for lock acquisition
  2. Add documentation for public methods
  3. Consider using atomic types for simple boolean flags
 impl RequestTask {
+    /// Sets the stop flag to control task execution
+    /// 
+    /// # Arguments
+    /// * `stop_run` - New value for the stop flag
     pub fn set_stop_run(&self, stop_run: bool) {
-        let mut stop_run_lock = self.stop_run.lock();
+        if let Some(mut stop_run_lock) = self.stop_run.try_lock_for(std::time::Duration::from_secs(1)) {
+            *stop_run_lock = stop_run;
+        } else {
+            log::warn!("Failed to acquire lock for stop_run flag");
+        }
-        *stop_run_lock = stop_run;
     }

+    /// Returns the creation timestamp of the task
     pub fn get_create_timestamp(&self) -> u64 {
         self.create_timestamp
     }

+    /// Returns the current state of the stop flag
     pub fn is_stop_run(&self) -> bool {
-        *self.stop_run.lock()
+        self.stop_run.try_lock().map(|guard| *guard).unwrap_or(true)
     }

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

Comment on lines +69 to +75
impl RequestTask {
pub async fn run(&self) {
if !self.is_stop_run() {
(self.runnable)();
}
}
}
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 error handling and timeout to run method.

The run method needs better error handling and timeout mechanism:

  1. Handle potential errors from runnable
  2. Add timeout for long-running tasks
  3. Add logging for better observability
 impl RequestTask {
-    pub async fn run(&self) {
+    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
         if !self.is_stop_run() {
-            (self.runnable)();
+            tokio::select! {
+                result = tokio::task::spawn_blocking(|| (self.runnable)()) => {
+                    match result {
+                        Ok(Ok(_)) => Ok(()),
+                        Ok(Err(e)) => {
+                            log::error!("Task execution failed: {}", e);
+                            Err(e)
+                        },
+                        Err(e) => {
+                            log::error!("Task panicked: {}", e);
+                            Err("Task panicked".into())
+                        }
+                    }
+                }
+                _ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {
+                    log::warn!("Task timed out");
+                    Err("Task timed out".into())
+                }
+            }
+        } else {
+            Ok(())
         }
     }

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

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 7fbaf56 into main Jan 25, 2025
31 of 33 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 Jan 25, 2025
@mxsm mxsm deleted the feature-2338 branch January 29, 2025 07:20
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. rocketmq-broker crate
Projects
None yet
3 participants