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 #2419] Adding #[inline] for RocketMQRuntime method #2420

Merged
merged 1 commit into from
Jan 27, 2025

Conversation

nakul-py
Copy link
Contributor

@nakul-py nakul-py commented Jan 27, 2025

Which Issue(s) This PR Fixes(Closes)

Add #[inline] for RocketMQRuntime methods.

Fixes #2419

Summary by CodeRabbit

  • New Features
    • Added runtime management methods for scheduling tasks and controlling runtime lifecycle
    • Introduced methods to retrieve runtime, shutdown runtime, and schedule tasks at fixed rates
    • Supports optional initial delay and configurable task scheduling periods

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

Walkthrough

The pull request introduces several new methods to the RocketMQRuntime enum in the rocketmq-runtime/src/lib.rs file. These methods are specifically designed for the Multi variant and are marked with the #[inline] attribute. The additions include runtime management methods such as get_runtime(), shutdown(), shutdown_timeout(), and two variants of schedule_at_fixed_rate() for scheduling tasks with optional initial delays and periodic execution.

Changes

File Changes
rocketmq-runtime/src/lib.rs - Added get_runtime() method to retrieve runtime reference
- Added shutdown() method to shut down runtime
- Added shutdown_timeout() method to shut down runtime with timeout
- Added schedule_at_fixed_rate() methods for task scheduling

Assessment against linked issues

Objective Addressed Explanation
Add #[inline] for RocketMQRuntime methods [#2419]

Possibly related PRs

Suggested labels

enhancement⚡️, approved, auto merge, AI review first

Suggested reviewers

  • TeslaRustor
  • rocketmq-rust-bot
  • mxsm

Poem

🚀 Runtime dancing, methods so bright,
Inline and swift, taking coding flight!
Schedules and shutdowns, with tokio's might,
RocketMQ's runtime, a programmer's delight!
Hop hop hooray, efficiency is here! 🐰✨


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-robot rocketmq-rust-robot added this to the v0.4.0 milestone Jan 27, 2025
@rocketmq-rust-robot rocketmq-rust-robot added the enhancement⚡️ New feature or request label Jan 27, 2025
@rocketmq-rust-bot
Copy link
Collaborator

🔊@nakul-py 🚀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

@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 comments (2)
rocketmq-runtime/src/lib.rs (2)

Line range hint 67-100: Consider improvements to the task scheduling implementation

Several concerns with the current implementation:

  1. The #[inline] attribute might not be beneficial for this large method
  2. The scheduling logic doesn't account for task execution time, which could lead to drift
  3. No mechanism to cancel scheduled tasks
  4. No error handling for task panics

Consider implementing a more robust solution:

     pub fn schedule_at_fixed_rate<F>(
         &self,
         task: F,
         initial_delay: Option<Duration>,
         period: Duration,
-    ) where
-        F: Fn() + Send + 'static,
+    ) -> tokio::task::JoinHandle<()> where
+        F: Fn() + Send + Sync + 'static,
     {
         match self {
             RocketMQRuntime::Multi(runtime) => {
-                runtime.handle().spawn(async move {
+                runtime.handle().spawn(async move {
+                    let mut interval = match initial_delay {
+                        Some(delay) => {
+                            tokio::time::sleep(delay).await;
+                            tokio::time::interval(period)
+                        }
+                        None => tokio::time::interval(period),
+                    };
+
                     // initial delay
                     if let Some(initial_delay_inner) = initial_delay {
                         tokio::time::sleep(initial_delay_inner).await;
                     }

                     loop {
-                        // record current execution time
-                        let current_execution_time = tokio::time::Instant::now();
-                        // execute task
-                        task();
-                        // Calculate the time of the next execution
-                        let next_execution_time = current_execution_time + period;
-
-                        // Wait until the next execution
-                        let delay = next_execution_time
-                            .saturating_duration_since(tokio::time::Instant::now());
-                        tokio::time::sleep(delay).await;
+                        interval.tick().await;
+                        if let Err(e) = std::panic::catch_unwind(|| task()) {
+                            eprintln!("Scheduled task panicked: {:?}", e);
+                            // Optionally break the loop or implement retry logic
+                        }
                     }
                 });
             }
         }
     }

This improvement:

  1. Uses tokio's built-in interval timing to prevent drift
  2. Returns a JoinHandle for cancellation
  3. Adds basic error handling for panics
  4. Removes the #[inline] attribute as it's unlikely to be beneficial for this size

Line range hint 102-137: Reduce code duplication with the non-mut version

This method is almost identical to schedule_at_fixed_rate, leading to unnecessary code duplication. Consider implementing a common internal method that both public methods can use.

-    #[inline]
-    pub fn schedule_at_fixed_rate_mut<F>(
+    pub fn schedule_at_fixed_rate_mut<F>(
         &self,
         mut task: F,
         initial_delay: Option<Duration>,
         period: Duration,
-    ) where
-        F: FnMut() + Send + 'static,
+    ) -> tokio::task::JoinHandle<()> where
+        F: FnMut() + Send + 'static,
     {
-        match self {
-            RocketMQRuntime::Multi(runtime) => {
-                runtime.handle().spawn(async move {
-                    // initial delay
-                    if let Some(initial_delay_inner) = initial_delay {
-                        tokio::time::sleep(initial_delay_inner).await;
-                    }
-
-                    loop {
-                        // record current execution time
-                        let current_execution_time = tokio::time::Instant::now();
-                        // execute task
-                        task();
-                        // Calculate the time of the next execution
-                        let next_execution_time = current_execution_time + period;
-
-                        // Wait until the next execution
-                        let delay = next_execution_time
-                            .saturating_duration_since(tokio::time::Instant::now());
-                        tokio::time::sleep(delay).await;
-                    }
-                });
-            }
-        }
+        // Convert FnMut to Fn by moving it into a RefCell
+        let task = std::cell::RefCell::new(task);
+        self.schedule_at_fixed_rate(move || task.borrow_mut()(), initial_delay, period)
     }
🧹 Nitpick comments (3)
rocketmq-runtime/src/lib.rs (3)

Line range hint 25-35: Consider implementing proper error handling instead of using unwrap()

The unwrap() call could cause a panic if the runtime creation fails. Consider propagating the error using Result.

-    pub fn new_multi(threads: usize, name: &str) -> Self {
+    pub fn new_multi(threads: usize, name: &str) -> std::io::Result<Self> {
         Self::Multi(
             tokio::runtime::Builder::new_multi_thread()
                 .worker_threads(threads)
                 .thread_name(name)
                 .enable_all()
-                .build()
-                .unwrap(),
+                .build()?,
         )
     }

53-58: Consider adding documentation for shutdown behavior

While the implementation is correct, it would be helpful to add documentation explaining:

  • What happens to running tasks
  • Whether it's a blocking or non-blocking operation
  • Any potential side effects
+    /// Initiates a non-blocking shutdown of the runtime.
+    /// This method drops the runtime, causing any unfinished tasks to be dropped.
+    /// For a graceful shutdown with timeout, use `shutdown_timeout` instead.
     #[inline]
     pub fn shutdown(self) {

60-65: Add documentation and consider validating the timeout value

The implementation would benefit from:

  1. Documentation explaining the shutdown behavior
  2. Validation of the timeout value to prevent unreasonable values
+    /// Initiates a graceful shutdown of the runtime with a timeout.
+    /// - Waits for up to `timeout` duration for all tasks to complete
+    /// - Returns immediately if timeout is zero
+    /// - Tasks that don't complete within the timeout will be dropped
     #[inline]
     pub fn shutdown_timeout(self, timeout: Duration) {
+        if timeout.is_zero() {
+            return self.shutdown();
+        }
         match self {
             Self::Multi(runtime) => runtime.shutdown_timeout(timeout),
         }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb5227f and 9d8f26c.

📒 Files selected for processing (1)
  • rocketmq-runtime/src/lib.rs (3 hunks)
⏰ 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 (ubuntu-latest, stable)
  • GitHub Check: build
  • GitHub Check: auto-approve
🔇 Additional comments (2)
rocketmq-runtime/src/lib.rs (2)

39-44: LGTM! Appropriate use of #[inline] for this getter method

The implementation is correct and the #[inline] attribute is well-suited for this simple getter method.


46-51: LGTM! Appropriate use of #[inline] for this getter method

The implementation is correct and the #[inline] attribute is well-suited for this simple getter method.

Copy link

codecov bot commented Jan 27, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 28.59%. Comparing base (fb5227f) to head (9d8f26c).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2420   +/-   ##
=======================================
  Coverage   28.59%   28.59%           
=======================================
  Files         508      508           
  Lines       73450    73450           
=======================================
  Hits        21005    21005           
  Misses      52445    52445           

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

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

Copy link
Owner

@mxsm mxsm left a comment

Choose a reason for hiding this comment

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

LGTM

@mxsm mxsm merged commit 7e6c826 into mxsm:main Jan 27, 2025
24 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 Jan 27, 2025
# 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 enhancement⚡️ New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Add #[inline] for RocketMQRuntime methods.
4 participants