-
-
Notifications
You must be signed in to change notification settings - Fork 128
fix(aspnetcore): guard hosted-service stop against concurrent double Host.StopAsync #6397
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
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
6a37fe9
fix(aspnetcore): guard hosted-service stop against concurrent double …
thomhurst f1ac3c7
fix(aspnetcore): preserve stop cancellation
thomhurst dfd6df6
fix(aspnetcore): start stop outside lock
thomhurst ccaf841
fix(aspnetcore): preserve owning stop wait
thomhurst File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
| using TUnit.AspNetCore; | ||
|
|
||
| namespace TUnit.AspNetCore.Tests; | ||
|
|
||
| /// <summary> | ||
| /// End-to-end regression test for https://github.com/thomhurst/TUnit/issues/6339. | ||
| /// <para> | ||
| /// With a minimal-hosting SUT, disposing the per-test factory races the SUT's own | ||
| /// <c>app.Run()</c> shutdown path: <c>WebApplicationFactory.DisposeAsync</c> calls | ||
| /// <c>Host.StopAsync</c>, whose <c>ApplicationStopping</c> signal wakes the app's parked | ||
| /// <c>WaitForShutdownAsync</c>, which calls <c>Host.StopAsync</c> again — concurrently. | ||
| /// Before the stop-once guard in <see cref="FlowSuppressingHostedService"/>, each hosted | ||
| /// service's <c>StopAsync</c> ran twice in parallel (observed here as 4–8 failures per | ||
| /// 50 tests), which is how Rebus' non-thread-safe bus dispose produced the reporter's | ||
| /// <see cref="ObjectDisposedException"/>. | ||
| /// </para> | ||
| /// <para> | ||
| /// The probe throws — with both stack traces — if it ever observes a second | ||
| /// <c>StopAsync</c> entry, so a regression surfaces as loud test failures. | ||
| /// </para> | ||
| /// </summary> | ||
| public class HostStopExactlyOnceProbeTests : WebApplicationTest<TestWebAppFactory, Program> | ||
| { | ||
| protected override void ConfigureTestServices(IServiceCollection services) | ||
| { | ||
| services.AddSingleton<IHostedService, StopProbeHostedService>(); | ||
| } | ||
|
|
||
| [Test] | ||
| [Repeat(50)] | ||
| public async Task Host_Hosted_Service_Stops_Exactly_Once_Under_Parallel_Churn() | ||
| { | ||
| var client = Factory.CreateClient(); | ||
| using var response = await client.GetAsync("/"); | ||
|
|
||
| // Small jitter so test completions (and After-hook disposals) overlap heavily. | ||
| await Task.Delay(Random.Shared.Next(0, 20)); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Throws on a second StopAsync entry — sequential re-stop or concurrent overlap — so the | ||
| /// offending call site's stack appears in the test output alongside the first stop's stack. | ||
| /// </summary> | ||
| internal sealed class StopProbeHostedService : IHostedService | ||
| { | ||
| private int _stopEntries; | ||
| private volatile string? _firstStopStack; | ||
|
|
||
| public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; | ||
|
|
||
| public async Task StopAsync(CancellationToken cancellationToken) | ||
| { | ||
| var entry = Interlocked.Increment(ref _stopEntries); | ||
|
|
||
| if (entry > 1) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"StopAsync entered {entry} times on probe {GetHashCode():x8}.\n" + | ||
| $"--- first stop stack ---\n{_firstStopStack}\n" + | ||
| $"--- this stop stack ---\n{Environment.StackTrace}"); | ||
| } | ||
|
|
||
| _firstStopStack = Environment.StackTrace; | ||
|
|
||
| // Widen the window like a real bus shutdown (Rebus stops workers, waits on its | ||
| // cleanup task for up to 5s). A concurrent second stop lands inside this delay. | ||
| await Task.Delay(100, CancellationToken.None); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When this is the first caller,
taskis the placeholder for the actual inner stop, but returning it throughWaitWithCancellationmeansHost.StopAsync's shutdown-timeout token can cancel the wrapper whileExecuteAndCompleteAsynccontinues running the innerStopAsyncin the background. For services that ignore the token or take longer than the timeout, the factory/host can proceed to dispose the service provider concurrently with stop cleanup, whereas hosted-service shutdown normally still awaits the returned tasks after cancellation is requested (docs). Apply the per-callerWaitAsynconly to duplicate callers, and let the owning invocation return the cached stop task.Useful? React with 👍 / 👎.