diff --git a/Test/DurableTask.AzureStorage.Tests/ActivityWorkItemTests.cs b/Test/DurableTask.AzureStorage.Tests/ActivityWorkItemTests.cs new file mode 100644 index 000000000..dc894b000 --- /dev/null +++ b/Test/DurableTask.AzureStorage.Tests/ActivityWorkItemTests.cs @@ -0,0 +1,72 @@ +// ---------------------------------------------------------------------------------- +// 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 +namespace DurableTask.AzureStorage.Tests +{ + using System; + using System.Threading; + using System.Threading.Tasks; + using DurableTask.Core; + using DurableTask.Core.History; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ActivityWorkItemTests + { + [TestMethod] + public async Task DeliveryAttemptComesFromDequeuedQueueMessage() + { + AzureStorageOrchestrationServiceSettings settings = + TestHelpers.GetTestAzureStorageOrchestrationServiceSettings(enableExtendedSessions: false); + settings.TaskHubName = $"deliveryattempt{Guid.NewGuid():N}"; + + var service = new AzureStorageOrchestrationService(settings); + await service.CreateIfNotExistsAsync(); + await service.StartAsync(); + + try + { + var instance = new OrchestrationInstance + { + InstanceId = Guid.NewGuid().ToString("N"), + ExecutionId = Guid.NewGuid().ToString("N"), + }; + var message = new TaskMessage + { + OrchestrationInstance = instance, + Event = new TaskScheduledEvent(0, "TestActivity"), + }; + + await service.WorkItemQueue.AddMessageAsync(message, instance); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + TaskActivityWorkItem firstDelivery = + await service.LockNextTaskActivityWorkItem(TimeSpan.FromSeconds(10), cancellation.Token); + + Assert.AreEqual(1L, firstDelivery.DeliveryAttempt); + + await service.AbandonTaskActivityWorkItemAsync(firstDelivery); + + TaskActivityWorkItem secondDelivery = + await service.LockNextTaskActivityWorkItem(TimeSpan.FromSeconds(10), cancellation.Token); + + Assert.AreEqual(2L, secondDelivery.DeliveryAttempt); + } + finally + { + await service.StopAsync(); + await service.DeleteAsync(); + } + } + } +} diff --git a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs index ad41c1f3f..8a283d22c 100644 --- a/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs +++ b/src/DurableTask.AzureStorage/AzureStorageOrchestrationService.cs @@ -1607,6 +1607,7 @@ public async Task LockNextTaskActivityWorkItem( Id = message.Id, TaskMessage = session.MessageData.TaskMessage, LockedUntilUtc = message.OriginalQueueMessage.NextVisibleOn.Value.UtcDateTime, + DeliveryAttempt = message.OriginalQueueMessage.DequeueCount, TraceContextBase = requestTraceContext }; diff --git a/src/DurableTask.Core/TaskActivityDispatcher.cs b/src/DurableTask.Core/TaskActivityDispatcher.cs index 8f4c24dca..6494b59ac 100644 --- a/src/DurableTask.Core/TaskActivityDispatcher.cs +++ b/src/DurableTask.Core/TaskActivityDispatcher.cs @@ -164,10 +164,15 @@ async Task OnProcessWorkItemAsync(TaskActivityWorkItem workItem) renewCancellationTokenSource.Token); } + long? deliveryAttempt = workItem.DeliveryAttempt; var dispatchContext = new DispatchMiddlewareContext(); dispatchContext.SetProperty(taskMessage.OrchestrationInstance); dispatchContext.SetProperty(taskActivity); dispatchContext.SetProperty(scheduledEvent); + dispatchContext.SetProperty(new WorkItemMetadata( + isExtendedSession: false, + includeState: true, + deliveryAttempt: deliveryAttempt)); // In transitionary phase (activity queued from old code, accessed in new code) context can be null. if (taskMessage.OrchestrationExecutionContext != null) @@ -200,7 +205,10 @@ await this.dispatchPipeline.RunAsync(dispatchContext, async _ => taskMessage.OrchestrationInstance, scheduledEvent.Name, scheduledEvent.Version, - scheduledEvent.EventId); + scheduledEvent.EventId) + { + DeliveryAttempt = deliveryAttempt, + }; context.ErrorPropagationMode = this.errorPropagationMode; context.ExceptionPropertiesProvider = this.exceptionPropertiesProvider; diff --git a/src/DurableTask.Core/TaskActivityWorkItem.cs b/src/DurableTask.Core/TaskActivityWorkItem.cs index b73d55d53..30d5c53f9 100644 --- a/src/DurableTask.Core/TaskActivityWorkItem.cs +++ b/src/DurableTask.Core/TaskActivityWorkItem.cs @@ -36,6 +36,16 @@ public class TaskActivityWorkItem /// public TaskMessage TaskMessage; + /// + /// Gets or sets the one-based delivery attempt number for the current activity work item. + /// + /// + /// This value does not represent the Activity attempt number of a Durable Task retry policy, and + /// does not necessarily reflect the amount of times user code has been executed. + /// A value of null indicates that the delivery attempt number is not available. + /// + public long? DeliveryAttempt { get; set; } + /// /// The TraceContext which is included on the queue. /// diff --git a/src/DurableTask.Core/TaskContext.cs b/src/DurableTask.Core/TaskContext.cs index 4fe4322f0..975e05327 100644 --- a/src/DurableTask.Core/TaskContext.cs +++ b/src/DurableTask.Core/TaskContext.cs @@ -58,6 +58,17 @@ public TaskContext(OrchestrationInstance orchestrationInstance, string name, str /// public int TaskId { get; } + /// + /// Gets or sets the one-based delivery attempt number for the current activity work item, see + /// + /// + /// + /// This value does not represent the Activity attempt number of a Durable Task retry policy, and + /// does not necessarily reflect the amount of times user code has been executed. + /// A value of null indicates that the delivery attempt number is not available. + /// + public long? DeliveryAttempt { get; internal set; } + /// /// Gets or sets a value indicating how to propagate unhandled exception metadata. /// diff --git a/src/DurableTask.Core/WorkItemMetadata.cs b/src/DurableTask.Core/WorkItemMetadata.cs index c2e908f48..d430f3934 100644 --- a/src/DurableTask.Core/WorkItemMetadata.cs +++ b/src/DurableTask.Core/WorkItemMetadata.cs @@ -19,9 +19,15 @@ namespace DurableTask.Core public class WorkItemMetadata { internal WorkItemMetadata(bool isExtendedSession, bool includeState) + : this(isExtendedSession, includeState, deliveryAttempt: null) + { + } + + internal WorkItemMetadata(bool isExtendedSession, bool includeState, long? deliveryAttempt) { this.IsExtendedSession = isExtendedSession; this.IncludeState = includeState; + this.DeliveryAttempt = deliveryAttempt; } /// @@ -35,5 +41,15 @@ internal WorkItemMetadata(bool isExtendedSession, bool includeState) /// the instance state from a previous execution, so it does not need to be included again. /// public bool IncludeState { get; private set; } + + /// + /// Gets or sets the one-based delivery attempt number for the current work item. + /// + /// + /// This value does not represent the attempt number of a Durable Task retry policy, and + /// does not necessarily reflect the amount of times user code has been executed. + /// A value of null indicates that the delivery attempt number is not available. + /// + public long? DeliveryAttempt { get; private set; } } } diff --git a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs index d07babea9..3f3be98cc 100644 --- a/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs +++ b/test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs @@ -2645,7 +2645,8 @@ private static async Task ValidateLargeMessageBlobUrlAsync(string taskHubName, s } /// - /// Tests the behavior of from orchestrations and activities. + /// Tests the behavior of from orchestrations and activities, + /// including the delivery attempt of the redelivered activity message. /// [DataTestMethod] [DataRow(true)] @@ -2654,6 +2655,13 @@ public async Task AbortOrchestrationAndActivity(bool enableExtendedSessions) { using (TestOrchestrationHost host = TestHelpers.GetTestOrchestrationHost(enableExtendedSessions)) { + var deliveryAttempts = new List(); + host.AddActivityDispatcherMiddleware(async (context, next) => + { + deliveryAttempts.Add(context.GetProperty().DeliveryAttempt); + await next(); + }); + await host.StartAsync(); string input = Guid.NewGuid().ToString(); @@ -2663,6 +2671,7 @@ public async Task AbortOrchestrationAndActivity(bool enableExtendedSessions) Assert.AreEqual(OrchestrationStatus.Completed, status?.OrchestrationStatus); Assert.IsNotNull(status.Output); Assert.AreEqual("True", JToken.Parse(status.Output)); + CollectionAssert.AreEqual(new long?[] { 1, 2 }, deliveryAttempts); await host.StopAsync(); } } @@ -5840,10 +5849,12 @@ protected override string Execute(TaskContext context, string input) { if (!abortedActivity) { + Assert.AreEqual(1L, context.DeliveryAttempt); abortedActivity = true; throw new SessionAbortedException(); } + Assert.AreEqual(2L, context.DeliveryAttempt); return input; } } diff --git a/test/DurableTask.AzureStorage.Tests/TestOrchestrationHost.cs b/test/DurableTask.AzureStorage.Tests/TestOrchestrationHost.cs index 34210c00f..5badb974d 100644 --- a/test/DurableTask.AzureStorage.Tests/TestOrchestrationHost.cs +++ b/test/DurableTask.AzureStorage.Tests/TestOrchestrationHost.cs @@ -14,6 +14,7 @@ namespace DurableTask.AzureStorage.Tests { using DurableTask.Core; + using DurableTask.Core.Middleware; using DurableTask.Core.Settings; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -65,6 +66,11 @@ public Task StopAsync() return this.worker.StopAsync(isForced: true); } + public void AddActivityDispatcherMiddleware(Func, Task> middleware) + { + this.worker.AddActivityDispatcherMiddleware(middleware); + } + public async Task UpdateWorkerVersion(VersioningSettings versioningSettings) { // Stop the current worker and create a new one with the new versioning settings. diff --git a/test/DurableTask.Core.Tests/DispatcherMiddlewareTests.cs b/test/DurableTask.Core.Tests/DispatcherMiddlewareTests.cs index e91b7ef84..cf05a71f4 100644 --- a/test/DurableTask.Core.Tests/DispatcherMiddlewareTests.cs +++ b/test/DurableTask.Core.Tests/DispatcherMiddlewareTests.cs @@ -40,6 +40,8 @@ public class DispatcherMiddlewareTests { TaskHubWorker worker = null!; TaskHubClient client = null!; + DeliveryAttemptOrchestrationService service = null!; + DeliveryAttemptActivity deliveryAttemptActivity = null!; [TestInitialize] public void InitializeTests() @@ -50,8 +52,9 @@ public void InitializeTests() { builder.AddConsole().SetMinimumLevel(LogLevel.Trace); }); - var service = new LocalOrchestrationService(); - this.worker = new TaskHubWorker(service, loggerFactory); + this.service = new DeliveryAttemptOrchestrationService(); + this.deliveryAttemptActivity = new DeliveryAttemptActivity(); + this.worker = new TaskHubWorker(this.service, loggerFactory); // We use `GetAwaiter().GetResult()` because otherwise this method will fail with: // "X has wrong signature. The method must be non-static, public, does not return a value and should not take any parameter." @@ -60,14 +63,16 @@ public void InitializeTests() typeof(SimplestGreetingsOrchestration), typeof(ParentWorkflow), typeof(ChildWorkflow), - typeof(ActivityStatusResetOrchestration)) + typeof(ActivityStatusResetOrchestration), + typeof(DeliveryAttemptOrchestration)) .AddTaskActivities( typeof(SimplestGetUserTask), typeof(SimplestSendGreetingTask), typeof(ActivityStatusResetActivity)) + .AddTaskActivities(this.deliveryAttemptActivity) .StartAsync().GetAwaiter().GetResult(); - this.client = new TaskHubClient(service); + this.client = new TaskHubClient(this.service); } [TestCleanup] @@ -130,6 +135,68 @@ public async Task DispatchMiddlewareContextBuiltInProperties() Assert.AreEqual(instance1!.InstanceId, instance2!.InstanceId); } + [TestMethod] + public void TaskActivityDeliveryAttemptDefaultsToNull() + { + var workItem = new TaskActivityWorkItem(); + var context = new TaskContext(new OrchestrationInstance()); + var metadata = new WorkItemMetadata( + isExtendedSession: false, + includeState: true); + + Assert.IsNull(workItem.DeliveryAttempt); + Assert.IsNull(context.DeliveryAttempt); + Assert.IsNull(metadata.DeliveryAttempt); + } + + [TestMethod] + public async Task TaskActivityDeliveryAttemptFlowsToTaskContextAndMiddleware() + { + const long deliveryAttempt = 42; + long? middlewareDeliveryAttempt = null; + this.service.ActivityDeliveryAttempt = deliveryAttempt; + + this.worker.AddActivityDispatcherMiddleware((context, next) => + { + middlewareDeliveryAttempt = context.GetProperty().DeliveryAttempt; + return next(); + }); + + OrchestrationInstance instance = await this.client.CreateOrchestrationInstanceAsync( + typeof(DeliveryAttemptOrchestration), + null); + + TimeSpan timeout = TimeSpan.FromSeconds(Debugger.IsAttached ? 1000 : 10); + await this.client.WaitForOrchestrationAsync(instance, timeout); + + Assert.AreEqual(deliveryAttempt, middlewareDeliveryAttempt); + Assert.AreEqual(deliveryAttempt, this.deliveryAttemptActivity.DeliveryAttempt); + } + + [TestMethod] + public async Task TaskActivityMiddlewareAlwaysReceivesWorkItemMetadata() + { + WorkItemMetadata? middlewareMetadata = null; + + this.worker.AddActivityDispatcherMiddleware((context, next) => + { + middlewareMetadata = context.GetProperty(); + return next(); + }); + + OrchestrationInstance instance = await this.client.CreateOrchestrationInstanceAsync( + typeof(DeliveryAttemptOrchestration), + null); + + TimeSpan timeout = TimeSpan.FromSeconds(Debugger.IsAttached ? 1000 : 10); + await this.client.WaitForOrchestrationAsync(instance, timeout); + + Assert.IsNotNull(middlewareMetadata); + Assert.IsFalse(middlewareMetadata.IsExtendedSession); + Assert.IsTrue(middlewareMetadata.IncludeState); + Assert.IsNull(middlewareMetadata.DeliveryAttempt); + } + [TestMethod] public async Task OrchestrationDispatcherMiddlewareContextFlow() { @@ -537,6 +604,45 @@ protected override string Execute(TaskContext context, string input) return input ?? "ok"; } } + + private sealed class DeliveryAttemptOrchestration : TaskOrchestration + { + public override Task RunTask(OrchestrationContext context, string input) + { + return context.ScheduleTask(typeof(DeliveryAttemptActivity), input); + } + } + + private sealed class DeliveryAttemptActivity : TaskActivity + { + public long? DeliveryAttempt { get; private set; } + + protected override string Execute(TaskContext context, string input) + { + this.DeliveryAttempt = context.DeliveryAttempt; + return input; + } + } + + private sealed class DeliveryAttemptOrchestrationService : LocalOrchestrationService, IOrchestrationService + { + public long? ActivityDeliveryAttempt { get; set; } + + public new async Task LockNextTaskActivityWorkItem( + TimeSpan receiveTimeout, + System.Threading.CancellationToken cancellationToken) + { + TaskActivityWorkItem workItem = + await base.LockNextTaskActivityWorkItem(receiveTimeout, cancellationToken); + + if (workItem != null) + { + workItem.DeliveryAttempt = this.ActivityDeliveryAttempt; + } + + return workItem!; + } + } } } #endif \ No newline at end of file