Skip to content

Commit

Permalink
Add Get-TaskResult CmdLet for DF (v3.x/ps7) (#798)
Browse files Browse the repository at this point in the history
Co-authored-by: Greg Roll <Greg.Roll@oobe.com.au>
  • Loading branch information
davidmrdavid and oobegreg authored Jun 20, 2022
1 parent e5bab3a commit dbc459f
Show file tree
Hide file tree
Showing 12 changed files with 146 additions and 15 deletions.
36 changes: 36 additions & 0 deletions src/Durable/Commands/GetDurableTaskResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

#pragma warning disable 1591 // Missing XML comment for publicly visible type or member 'member'

namespace Microsoft.Azure.Functions.PowerShellWorker.Durable.Commands
{
using System.Collections;
using System.Management.Automation;
using Microsoft.Azure.Functions.PowerShellWorker.Durable.Tasks;

[Cmdlet("Get", "DurableTaskResult")]
public class GetDurableTaskResultCommand : PSCmdlet
{
[Parameter(Mandatory = true)]
[ValidateNotNull]
public DurableTask[] Task { get; set; }

private readonly DurableTaskHandler _durableTaskHandler = new DurableTaskHandler();

protected override void EndProcessing()
{
var privateData = (Hashtable)MyInvocation.MyCommand.Module.PrivateData;
var context = (OrchestrationContext)privateData[SetFunctionInvocationContextCommand.ContextKey];

_durableTaskHandler.GetTaskResult(Task, context, WriteObject);
}

protected override void StopProcessing()
{
_durableTaskHandler.Stop();
}
}
}
15 changes: 15 additions & 0 deletions src/Durable/DurableTaskHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,21 @@ public void WaitAny(
}
}

public void GetTaskResult(
IReadOnlyCollection<DurableTask> tasksToQueryResultFor,
OrchestrationContext context,
Action<object> output)
{
foreach (var task in tasksToQueryResultFor) {
var scheduledHistoryEvent = task.GetScheduledHistoryEvent(context, true);
var processedHistoryEvent = task.GetCompletedHistoryEvent(context, scheduledHistoryEvent, true);
if (processedHistoryEvent != null)
{
output(GetEventResult(processedHistoryEvent));
}
}
}

public void Stop()
{
_waitForStop.Set();
Expand Down
6 changes: 3 additions & 3 deletions src/Durable/Tasks/ActivityInvocationTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ internal ActivityInvocationTask(string functionName, object functionInput)
{
}

internal override HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context)
internal override HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context, bool processed)
{
return context.History.FirstOrDefault(
e => e.EventType == HistoryEventType.TaskScheduled &&
e.Name == FunctionName &&
!e.IsProcessed);
e.IsProcessed == processed);
}

internal override HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent scheduledHistoryEvent)
internal override HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent scheduledHistoryEvent, bool processed)
{
return scheduledHistoryEvent == null
? null
Expand Down
4 changes: 2 additions & 2 deletions src/Durable/Tasks/DurableTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ namespace Microsoft.Azure.Functions.PowerShellWorker.Durable.Tasks

public abstract class DurableTask
{
internal abstract HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context);
internal abstract HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context, bool processed = false);

internal abstract HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent scheduledHistoryEvent);
internal abstract HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent scheduledHistoryEvent, bool processed = false);

internal abstract OrchestrationAction CreateOrchestrationAction();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Durable/Tasks/DurableTimerTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ internal DurableTimerTask(
Action = new CreateDurableTimerAction(FireAt);
}

internal override HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context)
internal override HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context, bool processed)
{
return context.History.FirstOrDefault(
e => e.EventType == HistoryEventType.TimerCreated &&
e.FireAt.Equals(FireAt) &&
!e.IsProcessed);
}

internal override HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent scheduledHistoryEvent)
internal override HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent scheduledHistoryEvent, bool processed)
{
return scheduledHistoryEvent == null
? null
Expand Down
6 changes: 3 additions & 3 deletions src/Durable/Tasks/ExternalEventTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ public ExternalEventTask(string externalEventName)
}

// There is no corresponding history event for an expected external event
internal override HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context)
internal override HistoryEvent GetScheduledHistoryEvent(OrchestrationContext context, bool processed)
{
return null;
}

internal override HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent taskScheduled)
internal override HistoryEvent GetCompletedHistoryEvent(OrchestrationContext context, HistoryEvent taskScheduled, bool processed)
{
return context.History.FirstOrDefault(
e => e.EventType == HistoryEventType.EventRaised &&
e.Name == ExternalEventName &&
!e.IsProcessed);
e.IsPlayed == processed);
}

internal override OrchestrationAction CreateOrchestrationAction()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ FunctionsToExport = @(
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @(
'Get-OutputBinding',
'Get-DurableTaskResult'
'Invoke-DurableActivity',
'Push-OutputBinding',
'Set-DurableCustomStatus',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ function New-DurableOrchestrationCheckStatusResponse {
The TaskHubName of the orchestration instance that will handle the external event.
.PARAMETER ConnectionName
The name of the connection string associated with TaskHubName
.PARAMETER AppCode
The Azure Functions system key
#>
function Send-DurableExternalEvent {
[CmdletBinding()]
Expand Down Expand Up @@ -271,12 +273,16 @@ function Send-DurableExternalEvent {

[Parameter(
ValueFromPipelineByPropertyName=$true)]
[string] $ConnectionName
[string] $ConnectionName,

[Parameter(
ValueFromPipelineByPropertyName=$true)]
[string] $AppCode
)

$DurableClient = GetDurableClientFromModulePrivateData

$RequestUrl = GetRaiseEventUrl -DurableClient $DurableClient -InstanceId $InstanceId -EventName $EventName -TaskHubName $TaskHubName -ConnectionName $ConnectionName
$RequestUrl = GetRaiseEventUrl -DurableClient $DurableClient -InstanceId $InstanceId -EventName $EventName -TaskHubName $TaskHubName -ConnectionName $ConnectionName -AppCode $AppCode

$Body = $EventData | ConvertTo-Json -Compress

Expand All @@ -288,7 +294,8 @@ function GetRaiseEventUrl(
[string] $InstanceId,
[string] $EventName,
[string] $TaskHubName,
[string] $ConnectionName) {
[string] $ConnectionName,
[string] $AppCode) {

$RequestUrl = $DurableClient.BaseUrl + "/instances/$InstanceId/raiseEvent/$EventName"

Expand All @@ -299,6 +306,9 @@ function GetRaiseEventUrl(
if ($null -eq $ConnectionName) {
$query += "connection=$ConnectionName"
}
if ($null -eq $AppCode) {
$query += "code=$AppCode"
}
if ($query.Count -gt 0) {
$RequestUrl += "?" + [string]::Join("&", $query)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,58 @@ public async Task ExternalEventReturnsData()
}
}

[Fact]
public async Task OrchestratationCanAlwaysObtainTaskResult()
{
var initialResponse = await Utilities.GetHttpTriggerResponse("DurableClient", queryString: "?FunctionName=DurableOrchestratorGetTaskResult");
Assert.Equal(HttpStatusCode.Accepted, initialResponse.StatusCode);

var initialResponseBody = await initialResponse.Content.ReadAsStringAsync();
dynamic initialResponseBodyObject = JsonConvert.DeserializeObject(initialResponseBody);
var statusQueryGetUri = (string)initialResponseBodyObject.statusQueryGetUri;

var startTime = DateTime.UtcNow;

using (var httpClient = new HttpClient())
{
while (true)
{
var statusResponse = await httpClient.GetAsync(statusQueryGetUri);
switch (statusResponse.StatusCode)
{
case HttpStatusCode.Accepted:
{
var statusResponseBody = await GetResponseBodyAsync(statusResponse);
var runtimeStatus = (string)statusResponseBody.runtimeStatus;
Assert.True(
runtimeStatus == "Running" || runtimeStatus == "Pending",
$"Unexpected runtime status: {runtimeStatus}");

if (DateTime.UtcNow > startTime + _orchestrationCompletionTimeout)
{
Assert.True(false, $"The orchestration has not completed after {_orchestrationCompletionTimeout}");
}

await Task.Delay(TimeSpan.FromSeconds(2));
break;
}

case HttpStatusCode.OK:
{
var statusResponseBody = await GetResponseBodyAsync(statusResponse);
Assert.Equal("Completed", (string)statusResponseBody.runtimeStatus);
Assert.Equal("Hello world", statusResponseBody.output.ToString());
return;
}

default:
Assert.True(false, $"Unexpected orchestration status code: {statusResponse.StatusCode}");
break;
}
}
}
}

[Fact]
public async Task ActivityCanHaveQueueBinding()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bindings": [
{
"name": "Context",
"type": "orchestrationTrigger",
"direction": "in"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
param($Context)

$output = @()

$task = Invoke-DurableActivity -FunctionName 'DurableActivity' -Input "world" -NoWait
$firstTask = Wait-DurableTask -Task @($task) -Any
$output += Get-DurableTaskResult -Task @($firstTask)
$output
4 changes: 2 additions & 2 deletions test/Unit/Durable/ActivityInvocationTaskTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,8 @@ public void GetCompletedHistoryEvent_ReturnsTaskCompletedOrTaskFailed(bool succe
var orchestrationContext = new OrchestrationContext { History = history };

var task = new ActivityInvocationTask(FunctionName, FunctionInput);
var scheduledEvent = task.GetScheduledHistoryEvent(orchestrationContext);
var completedEvent = task.GetCompletedHistoryEvent(orchestrationContext, scheduledEvent);
var scheduledEvent = task.GetScheduledHistoryEvent(orchestrationContext, false);
var completedEvent = task.GetCompletedHistoryEvent(orchestrationContext, scheduledEvent, false);

Assert.Equal(scheduledEvent.EventId, completedEvent.TaskScheduledId);
}
Expand Down

0 comments on commit dbc459f

Please sign in to comment.