Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions Test/DurableTask.AzureStorage.Tests/ActivityWorkItemTests.cs
Original file line number Diff line number Diff line change
@@ -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
Comment thread
sophiatev marked this conversation as resolved.
Resolved
{
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
Comment thread
sophiatev marked this conversation as resolved.
Resolved
{
[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();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1607,6 +1607,7 @@ public async Task<TaskActivityWorkItem> LockNextTaskActivityWorkItem(
Id = message.Id,
TaskMessage = session.MessageData.TaskMessage,
LockedUntilUtc = message.OriginalQueueMessage.NextVisibleOn.Value.UtcDateTime,
DeliveryAttempt = message.OriginalQueueMessage.DequeueCount,
Comment thread
sophiatev marked this conversation as resolved.
Resolved

TraceContextBase = requestTraceContext
};
Expand Down
10 changes: 9 additions & 1 deletion src/DurableTask.Core/TaskActivityDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;

Expand Down
10 changes: 10 additions & 0 deletions src/DurableTask.Core/TaskActivityWorkItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ public class TaskActivityWorkItem
/// </summary>
public TaskMessage TaskMessage;

/// <summary>
/// Gets or sets the one-based delivery attempt number for the current activity work item.
/// </summary>
/// <remarks>
/// 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 <c>null</c> indicates that the delivery attempt number is not available.
/// </remarks>
public long? DeliveryAttempt { get; set; }
Comment thread
sophiatev marked this conversation as resolved.
Resolved

/// <summary>
/// The TraceContext which is included on the queue.
/// </summary>
Expand Down
11 changes: 11 additions & 0 deletions src/DurableTask.Core/TaskContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ public TaskContext(OrchestrationInstance orchestrationInstance, string name, str
/// </summary>
public int TaskId { get; }

/// <summary>
/// Gets or sets the one-based delivery attempt number for the current activity work item, see
/// <see cref="TaskActivityWorkItem.DeliveryAttempt"/>
/// </summary>
/// <remarks>
/// 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 <c>null</c> indicates that the delivery attempt number is not available.
/// </remarks>
public long? DeliveryAttempt { get; internal set; }

/// <summary>
/// Gets or sets a value indicating how to propagate unhandled exception metadata.
/// </summary>
Expand Down
16 changes: 16 additions & 0 deletions src/DurableTask.Core/WorkItemMetadata.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/// <summary>
Expand All @@ -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.
/// </summary>
public bool IncludeState { get; private set; }

/// <summary>
/// Gets or sets the one-based delivery attempt number for the current work item.
/// </summary>
/// <remarks>
/// 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 <c>null</c> indicates that the delivery attempt number is not available.
/// </remarks>
public long? DeliveryAttempt { get; private set; }
}
}
13 changes: 12 additions & 1 deletion test/DurableTask.AzureStorage.Tests/AzureStorageScenarioTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2645,7 +2645,8 @@ private static async Task ValidateLargeMessageBlobUrlAsync(string taskHubName, s
}

/// <summary>
/// Tests the behavior of <see cref="SessionAbortedException"/> from orchestrations and activities.
/// Tests the behavior of <see cref="SessionAbortedException"/> from orchestrations and activities,
/// including the delivery attempt of the redelivered activity message.
/// </summary>
[DataTestMethod]
[DataRow(true)]
Expand All @@ -2654,6 +2655,13 @@ public async Task AbortOrchestrationAndActivity(bool enableExtendedSessions)
{
using (TestOrchestrationHost host = TestHelpers.GetTestOrchestrationHost(enableExtendedSessions))
{
var deliveryAttempts = new List<long?>();
host.AddActivityDispatcherMiddleware(async (context, next) =>
{
deliveryAttempts.Add(context.GetProperty<WorkItemMetadata>().DeliveryAttempt);
await next();
});

await host.StartAsync();

string input = Guid.NewGuid().ToString();
Expand All @@ -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();
}
}
Expand Down Expand Up @@ -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;
}
}
Expand Down
6 changes: 6 additions & 0 deletions test/DurableTask.AzureStorage.Tests/TestOrchestrationHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -65,6 +66,11 @@ public Task StopAsync()
return this.worker.StopAsync(isForced: true);
}

public void AddActivityDispatcherMiddleware(Func<DispatchMiddlewareContext, Func<Task>, 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.
Expand Down
114 changes: 110 additions & 4 deletions test/DurableTask.Core.Tests/DispatcherMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public class DispatcherMiddlewareTests
{
TaskHubWorker worker = null!;
TaskHubClient client = null!;
DeliveryAttemptOrchestrationService service = null!;
DeliveryAttemptActivity deliveryAttemptActivity = null!;

[TestInitialize]
public void InitializeTests()
Expand All @@ -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."
Expand All @@ -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]
Expand Down Expand Up @@ -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<WorkItemMetadata>().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<WorkItemMetadata>();
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()
{
Expand Down Expand Up @@ -537,6 +604,45 @@ protected override string Execute(TaskContext context, string input)
return input ?? "ok";
}
}

private sealed class DeliveryAttemptOrchestration : TaskOrchestration<string, string>
{
public override Task<string> RunTask(OrchestrationContext context, string input)
{
return context.ScheduleTask<string>(typeof(DeliveryAttemptActivity), input);
}
}

private sealed class DeliveryAttemptActivity : TaskActivity<string, string>
{
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<TaskActivityWorkItem> LockNextTaskActivityWorkItem(
TimeSpan receiveTimeout,
System.Threading.CancellationToken cancellationToken)
{
TaskActivityWorkItem workItem =
await base.LockNextTaskActivityWorkItem(receiveTimeout, cancellationToken);

if (workItem != null)
{
workItem.DeliveryAttempt = this.ActivityDeliveryAttempt;
}

return workItem!;
}
}
}
}
#endif
Loading