Repository navigation
Add CancellationToken overloads to TaskHubWorker.StartAsync and StopAsync #1446
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -284,11 +284,27 @@ public void AddActivityDispatcherMiddleware(Func<DispatchMiddlewareContext, Func | |
| /// Starts the TaskHubWorker so it begins processing orchestrations and activities | ||
| /// </summary> | ||
| /// <returns></returns> | ||
| public async Task<TaskHubWorker> StartAsync() | ||
| public Task<TaskHubWorker> StartAsync() | ||
| { | ||
| await this.slimLock.WaitAsync(); | ||
| return this.StartAsync(CancellationToken.None); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Starts the TaskHubWorker so it begins processing orchestrations and activities | ||
| /// </summary> | ||
| /// <param name="cancellationToken"> | ||
| /// Token that cancels the start request, for example from a hosted service. It is observed before startup begins; | ||
| /// once the worker has started to start, the startup runs to completion. | ||
| /// </param> | ||
| /// <returns></returns> | ||
| /// <exception cref="OperationCanceledException">The token was canceled before the worker began to start.</exception> | ||
| public async Task<TaskHubWorker> StartAsync(CancellationToken cancellationToken) | ||
| { | ||
| await this.slimLock.WaitAsync(cancellationToken); | ||
| try | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (this.isStarted) | ||
| { | ||
| throw new InvalidOperationException("Worker is already started"); | ||
|
|
@@ -351,6 +367,19 @@ public async Task StopAsync() | |
| await this.StopAsync(false); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gracefully stops the TaskHubWorker, unless the token is already canceled. | ||
| /// </summary> | ||
| /// <param name="cancellationToken"> | ||
| /// Token that signals the graceful shutdown period is over, for example from a hosted service. | ||
| /// When it is already canceled on entry, the worker is stopped as with <c>StopAsync(true)</c>. | ||
| /// The call never skips the stop because of the token, so the worker is not left running. | ||
| /// </param> | ||
| public async Task StopAsync(CancellationToken cancellationToken) | ||
| { | ||
| await this.StopAsync(cancellationToken.IsCancellationRequested); | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fair point, the idle emulator would have hidden a wrong flag. 3124536 adds
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. One correction to my reply above, and the one on the start-lock thread: I wrote that CI is green on 3124536, but only license/cla has run there. The CodeQL run is waiting for a maintainer to approve workflows, so no build or test workflow has run on this head yet. I have now run TaskHubWorkerCancellationTests locally on net8.0: 5 passed. Reverting the token to |
||
| } | ||
|
|
||
| /// <summary> | ||
| /// Stops the TaskHubWorker | ||
| /// </summary> | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| // ---------------------------------------------------------------------------------- | ||
| // Copyright Microsoft Corporation | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // ---------------------------------------------------------------------------------- | ||
| #nullable enable | ||
| #if !NET48 // same reason as DispatcherMiddlewareTests: tests that use the emulator are not discoverable on 1ES for net48 | ||
| namespace DurableTask.Core.Tests | ||
| { | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Reflection; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using DurableTask.Emulator; | ||
| using DurableTask.Test.Orchestrations; | ||
| using Microsoft.VisualStudio.TestTools.UnitTesting; | ||
|
|
||
| [TestClass] | ||
| public class TaskHubWorkerCancellationTests | ||
|
Copilot marked this conversation as resolved.
Resolved
|
||
| { | ||
| static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); | ||
|
|
||
| static TaskHubWorker CreateWorker(LocalOrchestrationService service) | ||
| { | ||
| var worker = new TaskHubWorker(service); | ||
| worker | ||
| .AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration)) | ||
| .AddTaskActivities(typeof(SimplestGetUserTask), typeof(SimplestSendGreetingTask)); | ||
| return worker; | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task StartAsyncWithToken_RunsOrchestration_AndStopAsyncWithTokenStopsWorker() | ||
| { | ||
| var service = new LocalOrchestrationService(); | ||
| TaskHubWorker worker = CreateWorker(service); | ||
| var client = new TaskHubClient(service); | ||
|
|
||
| using var cts = new CancellationTokenSource(); | ||
| TaskHubWorker started = await worker.StartAsync(cts.Token); | ||
| Assert.AreSame(worker, started); | ||
|
|
||
| OrchestrationInstance instance = await client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), null); | ||
| OrchestrationState state = await client.WaitForOrchestrationAsync(instance, Timeout); | ||
| Assert.AreEqual(OrchestrationStatus.Completed, state.OrchestrationStatus); | ||
|
|
||
| await worker.StopAsync(cts.Token); | ||
|
|
||
| // A stopped worker can be started again, which shows the stop took effect. | ||
| await worker.StartAsync(); | ||
| await worker.StopAsync(true); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task StartAsyncWithCanceledToken_ThrowsAndLeavesWorkerNotStarted() | ||
| { | ||
| var service = new LocalOrchestrationService(); | ||
| TaskHubWorker worker = CreateWorker(service); | ||
|
|
||
| using var cts = new CancellationTokenSource(); | ||
| cts.Cancel(); | ||
| try | ||
| { | ||
| await worker.StartAsync(cts.Token); | ||
| Assert.Fail("StartAsync should not succeed with a canceled token."); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| // Expected. The wait on the start lock may surface it as a TaskCanceledException. | ||
| } | ||
|
|
||
| // Nothing was started, so a plain start succeeds instead of reporting "already started". | ||
| await worker.StartAsync(); | ||
| await worker.StopAsync(true); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task StopAsyncWithCanceledToken_StillStopsTheWorker() | ||
| { | ||
| var service = new LocalOrchestrationService(); | ||
| TaskHubWorker worker = CreateWorker(service); | ||
| await worker.StartAsync(); | ||
|
|
||
| using var cts = new CancellationTokenSource(); | ||
| cts.Cancel(); | ||
| await worker.StopAsync(cts.Token); | ||
|
|
||
| // Starting again would throw "Worker is already started" if the stop had been skipped. | ||
| await worker.StartAsync(); | ||
| await worker.StopAsync(true); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Forwards every call to the emulator and records StopAsync(bool) arguments. | ||
| /// When StartGate is set, StartAsync() does not complete until the gate is opened. | ||
| /// </summary> | ||
| public class ServiceSpy : DispatchProxy | ||
| { | ||
| public IOrchestrationService? Inner { get; set; } | ||
| public List<bool> StopCalls { get; } = new List<bool>(); | ||
| public TaskCompletionSource<bool>? StartGate { get; set; } | ||
| public TaskCompletionSource<bool> StartEntered { get; } = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
|
|
||
| protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) | ||
| { | ||
| if (targetMethod!.Name == nameof(IOrchestrationService.StopAsync) && args?.Length == 1 && args[0] is bool forced) | ||
| { | ||
| lock (this.StopCalls) | ||
| { | ||
| this.StopCalls.Add(forced); | ||
| } | ||
| } | ||
|
|
||
| if (targetMethod.Name == nameof(IOrchestrationService.StartAsync) && this.StartGate != null) | ||
| { | ||
| this.StartEntered.TrySetResult(true); | ||
| return this.StartGate.Task; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| return targetMethod.Invoke(this.Inner, args); | ||
| } | ||
| catch (TargetInvocationException e) when (e.InnerException != null) | ||
| { | ||
| throw e.InnerException; | ||
| } | ||
| } | ||
|
|
||
| public static (IOrchestrationService Service, ServiceSpy Spy) Create(LocalOrchestrationService inner) | ||
| { | ||
| IOrchestrationService proxy = Create<IOrchestrationService, ServiceSpy>(); | ||
| var spy = (ServiceSpy)(object)proxy; | ||
| spy.Inner = inner; | ||
| return (proxy, spy); | ||
| } | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task StopAsyncWithToken_ForwardsForcedFlagFromToken() | ||
| { | ||
| var (service, spy) = ServiceSpy.Create(new LocalOrchestrationService()); | ||
| var worker = new TaskHubWorker(service); | ||
| worker.AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration)); | ||
|
|
||
| using var live = new CancellationTokenSource(); | ||
| await worker.StartAsync(); | ||
| await worker.StopAsync(live.Token); | ||
|
|
||
| using var canceled = new CancellationTokenSource(); | ||
| canceled.Cancel(); | ||
| await worker.StartAsync(); | ||
| await worker.StopAsync(canceled.Token); | ||
|
|
||
| CollectionAssert.AreEqual(new[] { false, true }, spy.StopCalls); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task StartAsyncWithToken_CanceledWhileWaitingForStartLock_ThrowsBeforeFirstStartCompletes() | ||
| { | ||
| var (service, spy) = ServiceSpy.Create(new LocalOrchestrationService()); | ||
| spy.StartGate = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); | ||
| var worker = new TaskHubWorker(service); | ||
| worker.AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration)); | ||
|
|
||
| // The first start holds the start lock while it waits inside the service's StartAsync. | ||
| Task<TaskHubWorker> first = worker.StartAsync(); | ||
| await spy.StartEntered.Task.WaitAsync(Timeout); | ||
|
|
||
| using var cts = new CancellationTokenSource(); | ||
| Task<TaskHubWorker> second = worker.StartAsync(cts.Token); | ||
| Assert.IsFalse(second.IsCompleted, "The second start should be waiting for the lock."); | ||
|
|
||
| cts.Cancel(); | ||
| try | ||
| { | ||
| await second.WaitAsync(Timeout); | ||
| Assert.Fail("The queued start should be canceled."); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| // Expected. TaskCanceledException derives from it. | ||
| } | ||
|
|
||
| Assert.IsFalse(first.IsCompleted, "The second start must fail while the first still holds the lock."); | ||
|
|
||
| spy.StartGate.SetResult(true); | ||
| await first.WaitAsync(Timeout); | ||
| await worker.StopAsync(true); | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
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.
Thanks, that test was missing. 3124536 adds
StartAsyncWithToken_CanceledWhileWaitingForStartLock_ThrowsBeforeFirstStartCompletes: it blocks a first start inside the service'sStartAsync, queues a second start, cancels it, and asserts the second call throws while the first is still pending. I haven't run it locally; CI is green on this head.