Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jul 8, 2025

Link issues

fixes #6378

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Refine ThrottleDispatcher to simplify its implementation and improve readability by removing unnecessary locks and flags, unify sync/async paths with async/await, and update tests to align with corrected reset-on-exception and cancellation behaviors

Bug Fixes:

  • Fix reset-interval-on-exception behavior to allow immediate reruns
  • Ensure cancellation tokens are correctly honored in throttle methods

Enhancements:

  • Remove internal locking and busy flags, simplifying state management
  • Consolidate sync and async throttle logic using async/await
  • Simplify ShouldWait logic to base solely on invoke timestamp
  • Streamline exception handling and delay-after-execution flow

Tests:

  • Update existing tests to match new throttle behavior and remove obsolete mock tests
  • Add concurrency test for multiple parallel ThrottleAsync calls

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jul 8, 2025

Reviewer's Guide

Refines the ThrottleDispatcher implementation by removing redundant synchronization fields, unifying and simplifying throttling logic with async/await and timestamp updates, streamlining the synchronous Throttle method’s flow, and updating unit tests to align with the new behavior.

Class diagram for updated ThrottleDispatcher

classDiagram
    class ThrottleDispatcher {
        - DateTime? _invokeTime
        + ThrottleDispatcher(ThrottleOptions options)
        + bool ShouldWait()
        + void Throttle(Action action, CancellationToken token = default)
        - async Task InternalThrottleAsync(Func<Task> function, CancellationToken cancellationToken = default)
    }
    class ThrottleOptions {
        + TimeSpan Interval
        + bool DelayAfterExecution
        + bool ResetIntervalOnException
    }
    ThrottleDispatcher --> ThrottleOptions
Loading

File-Level Changes

Change Details Files
Clean up internal state and simplify asynchronous throttling logic
  • Remove _locker, _busy flag, and _lastTask tracking
  • Refactor InternalThrottleAsync to async/await and eliminate lock
  • Update invokeTime before execution and optionally after or reset on exception
  • Simplify ShouldWait to rely solely on timestamp comparison
src/BootstrapBlazor/Services/ThrottleDispatcher.cs
Streamline the synchronous Throttle method
  • Rename cancellation token parameter and use CancellationToken.None for the inner Task.Run
  • Eliminate nested Wait helper and consolidate exception propagation in a try/catch
  • Invoke InternalThrottleAsync directly and wait on returned Task
src/BootstrapBlazor/Services/ThrottleDispatcher.cs
Revise unit tests to reflect the updated throttling behavior
  • Remove mock dispatcher and LastTask–based tests
  • Adjust exception types and assertion patterns for sync and async methods
  • Update ShouldWait test to reflect new invocation count
  • Add a multi-threaded ThrottleAsync test to verify concurrent behavior
test/UnitTest/Services/ThrottleTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6378 Refactor the code to improve its readability.
#6378 Fix throttle reset behavior after exceptions to allow immediate retries.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto bot added the enhancement New feature or request label Jul 8, 2025
@bb-auto bb-auto bot added this to the 9.8.0 milestone Jul 8, 2025
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @ArgoZhang - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Services/ThrottleDispatcher.cs:19` </location>
<code_context>
     /// </summary>
     /// <returns></returns>
-    protected virtual bool ShouldWait() => _busy || _invokeTime.HasValue && (DateTime.UtcNow - _invokeTime.Value) < options.Interval;
+    protected virtual bool ShouldWait() => _invokeTime.HasValue && (DateTime.UtcNow - _invokeTime.Value) < options.Interval;

     /// <summary>
</code_context>

<issue_to_address>
Removal of the _busy flag may introduce concurrency issues.

Without the _busy flag and lock, concurrent calls may bypass throttling. If thread safety is required, add appropriate synchronization to avoid race conditions.
</issue_to_address>

### Comment 2
<location> `src/BootstrapBlazor/Services/ThrottleDispatcher.cs:63` </location>
<code_context>
         }

-        lock (_locker)
+        _invokeTime = DateTime.UtcNow;
+
+        try
         {
-            if (ShouldWait())
+            await function();
+            if (options.DelayAfterExecution)
             {
-                return LastTask;
+                _invokeTime = DateTime.UtcNow;
             }
-
</code_context>

<issue_to_address>
Setting _invokeTime before and after function execution may not be necessary.

Clarify whether throttling should be based on the start or end of execution, and update _invokeTime in only one place to reflect that.
</issue_to_address>

### Comment 3
<location> `test/UnitTest/Services/ThrottleTest.cs:91` </location>
<code_context>
+        Assert.Equal(1, count);

-        Assert.ThrowsAny<InvalidOperationException>(() => dispatcher.Throttle(() => throw new InvalidOperationException()));
+        dispatcher.Throttle(() => throw new InvalidOperationException());

         // 发生错误后可以立即执行下一次任务,不限流
</code_context>

<issue_to_address>
Missing assertion for expected exception in sync Throttle after async exception.

Please reintroduce an assertion (e.g., Assert.Throws) to verify that the sync Throttle call throws as expected, or clarify if this change is intentional.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        dispatcher.Throttle(() => throw new InvalidOperationException());

        // 发生错误后可以立即执行下一次任务,不限流
=======
        Assert.ThrowsAny<InvalidOperationException>(() => dispatcher.Throttle(() => throw new InvalidOperationException()));

        // 发生错误后可以立即执行下一次任务,不限流
>>>>>>> REPLACE

</suggested_fix>

### Comment 4
<location> `test/UnitTest/Services/ThrottleTest.cs:120` </location>
<code_context>

         cts = new CancellationTokenSource(100);
-        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => dispatcher.ThrottleAsync(async () =>
+        await dispatcher.ThrottleAsync(async () =>
         {
             await Task.Delay(300);
-        }, cts.Token));
+        }, cts.Token);
     }

</code_context>

<issue_to_address>
Missing assertion for OperationCanceledException in ThrottleAsync with cancellation.

Restoring the assertion ensures that cancellation is properly handled and exceptions are surfaced as expected.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@ArgoZhang ArgoZhang merged commit 1ae8579 into main Jul 8, 2025
3 of 5 checks passed
@ArgoZhang ArgoZhang deleted the feat-ThrottleDispatcher branch July 8, 2025 08:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(ThrottleDispatcher): refine code improve readability

2 participants