Skip to content

[ISSUE #1254]🚀RocketMQRuntime add schedule_at_fixed_rate_mut method #1255

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
Nov 21, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Nov 21, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1254

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features
    • Introduced a new method for scheduling tasks at a fixed rate, allowing for mutable task closures, enhancing flexibility in task execution.

Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes introduce a new method, schedule_at_fixed_rate_mut, to the RocketMQRuntime enum in the rocketmq-runtime/src/lib.rs file. This method allows for scheduling tasks at a fixed rate using a mutable closure, enhancing the existing functionality of the schedule_at_fixed_rate method. The new method retains the same parameters and implementation structure, focusing on the ability to modify the task closure during execution while utilizing the Tokio runtime for asynchronous operations.

Changes

File Path Change Summary
rocketmq-runtime/src/lib.rs Added method pub fn schedule_at_fixed_rate_mut<F>(&self, mut task: F, ...) to RocketMQRuntime enum for scheduling tasks with mutable closures.

Assessment against linked issues

Objective Addressed Explanation
Add schedule_at_fixed_rate_mut method (1254)

Suggested labels

approved, auto merge

Suggested reviewers

  • SpaceXCN
  • TeslaRustor

Poem

In the meadow where tasks do play,
A new method hops in, hip-hip-hooray!
With mutable joy, it dances around,
Scheduling tasks where fun can be found!
So let’s cheer for the code, bright and neat,
A leap for RocketMQ, oh what a treat! 🐇✨


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-bot rocketmq-rust-bot added AI review first Ai review pr first ready to review waiting-review waiting review this PR labels Nov 21, 2024
@rocketmq-rust-bot rocketmq-rust-bot added this to the v0.4.0 milestone Nov 21, 2024
@rocketmq-rust-bot rocketmq-rust-bot added the feature🚀 Suggest an idea for this project. label Nov 21, 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: 1

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

96-128: Consider adding timing drift compensation.

For better timing accuracy over long periods, consider compensating for task execution time:

                     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;
+                        let execution_duration = current_execution_time.elapsed();
+                        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());
+                            .saturating_duration_since(tokio::time::Instant::now())
+                            .saturating_sub(execution_duration);
                         tokio::time::sleep(delay).await;
                     }

96-128: Consider enhancing the scheduler architecture.

The current implementation could benefit from some architectural improvements:

  1. Task metrics collection (execution time, success/failure counts)
  2. Rate limiting or backoff strategies for failing tasks
  3. Task coordination and graceful shutdown

Consider introducing a ScheduledTask trait or struct to encapsulate these concerns:

pub struct ScheduledTask<F> {
    task: F,
    period: Duration,
    metrics: TaskMetrics,
    last_execution: Option<Instant>,
}

impl<F> ScheduledTask<F> {
    pub fn new(task: F, period: Duration) -> Self {
        // Implementation details
    }
    
    pub fn with_backoff(mut self, strategy: BackoffStrategy) -> Self {
        // Implementation details
    }
    
    pub fn metrics(&self) -> &TaskMetrics {
        // Implementation details
    }
}

This would provide a more maintainable and feature-rich foundation for scheduled tasks.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e9dcd9e and a85fa0d.

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

96-128: Implementation looks correct but could be enhanced.

The new schedule_at_fixed_rate_mut method correctly implements mutable task scheduling with fixed rate execution.

Comment on lines +96 to +128
pub fn schedule_at_fixed_rate_mut<F>(
&self,
mut task: F,
initial_delay: Option<Duration>,
period: Duration,
) 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;
}
});
}
}
}
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 adding error handling and task cancellation.

The current implementation could be more robust:

  1. Task panics aren't handled and could crash the runtime
  2. No mechanism to stop/cancel the scheduled task
  3. Potential for timing drift over long periods

Consider this enhanced implementation:

     pub fn schedule_at_fixed_rate_mut<F>(
         &self,
         mut task: F,
         initial_delay: Option<Duration>,
         period: Duration,
     ) where
-        F: FnMut() + Send + 'static,
+        F: FnMut() -> Result<(), Box<dyn std::error::Error>> + Send + 'static,
     {
         match self {
             RocketMQRuntime::Multi(runtime) => {
-                runtime.handle().spawn(async move {
+                let handle = 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();
+                        if let Err(e) = task() {
+                            log::error!("Scheduled task failed: {}", e);
+                            break;
+                        }
                         // 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;
                     }
                 });
+                Ok(handle)
             }
         }
     }

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

Copy link

codecov bot commented Nov 21, 2024

Codecov Report

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

Project coverage is 18.25%. Comparing base (e9dcd9e) to head (a85fa0d).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-runtime/src/lib.rs 0.00% 28 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1255      +/-   ##
==========================================
- Coverage   18.26%   18.25%   -0.01%     
==========================================
  Files         428      428              
  Lines       53581    53609      +28     
==========================================
  Hits         9789     9789              
- Misses      43792    43820      +28     

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


🚨 Try these New Features:

@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved auto merge and removed ready to review waiting-review waiting review this PR labels Nov 21, 2024
@rocketmq-rust-bot rocketmq-rust-bot merged commit 8a65b09 into main Nov 21, 2024
28 of 30 checks passed
@mxsm mxsm deleted the feature-1254 branch November 21, 2024 13:59
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🚀] RocketMQRuntime add schedule_at_fixed_rate_mut method
3 participants