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
7 changes: 7 additions & 0 deletions all.sln
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dapr.IntegrationTest.Workfl
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dapr.Workflow.Versioning.Runtime.Test", "test\Dapr.Workflow.Versioning.Runtime.Test\Dapr.Workflow.Versioning.Runtime.Test.csproj", "{4FF7F075-2818-41E4-A88F-743417EA0A99}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkflowVersioning", "examples\Workflow\WorkflowVersioning\WorkflowVersioning.csproj", "{837E02A5-D1C0-4F60-AF93-71117BF3B6DC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -645,6 +647,10 @@ Global
{4FF7F075-2818-41E4-A88F-743417EA0A99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4FF7F075-2818-41E4-A88F-743417EA0A99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4FF7F075-2818-41E4-A88F-743417EA0A99}.Release|Any CPU.Build.0 = Release|Any CPU
{837E02A5-D1C0-4F60-AF93-71117BF3B6DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{837E02A5-D1C0-4F60-AF93-71117BF3B6DC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{837E02A5-D1C0-4F60-AF93-71117BF3B6DC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{837E02A5-D1C0-4F60-AF93-71117BF3B6DC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -763,6 +769,7 @@ Global
{CB619F1E-B90C-4BCB-9DDA-A5A4F5967661} = {27C5D71D-0721-4221-9286-B94AB07B58CF}
{1AD32297-630E-4DFB-B3E4-CAFCE993F27F} = {8462B106-175A-423A-BA94-BE0D39D0BD8E}
{4FF7F075-2818-41E4-A88F-743417EA0A99} = {0AF0FE8D-C234-4F04-8514-32206ACE01BD}
{837E02A5-D1C0-4F60-AF93-71117BF3B6DC} = {BF3ED6BF-ADF3-4D25-8E89-02FB8D945CA9}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {65220BF2-EAE1-4CB2-AA58-EBE80768CB40}
Expand Down
48 changes: 48 additions & 0 deletions examples/Workflow/WorkflowVersioning/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Dapr.Workflow;
using Dapr.Workflow.Versioning;
using WorkflowVersioning.Services;
using WorkflowVersioning.Workflows.VacationApproval.Activities;
using WorkflowVersioning.Workflows.VacationApproval.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IEmailService, EmailService>();

builder.Services.AddDaprWorkflowVersioning();

// By default, it registers a numerical versioning strategy - let's demonstrate overriding this with a date-based approach
// and non-standard options
const string optionsName = "workflow-defaults";
builder.Services.UseDefaultWorkflowStrategy<NumericVersionStrategy>(optionsName);
builder.Services.ConfigureStrategyOptions<NumericVersionStrategyOptions>(optionsName, o =>
{
o.SuffixPrefix = "V";
});

builder.Services.AddDaprWorkflow(w =>
{
w.RegisterActivity<SendEmailActivity>();
});

var app = builder.Build();

app.MapGet("/start/{workflowId}",
async (DaprWorkflowClient workflowClient, [AsParameters] VacationRequest request, string workflowId) =>
{
await workflowClient.ScheduleNewWorkflowAsync("VacationApprovalWorkflow", workflowId, request);
var a = 0;
a++;

});

app.MapGet("/approve/{workflowId}", async (DaprWorkflowClient workflowClient, string workflowId) =>
{
await workflowClient.RaiseEventAsync(workflowId, "Approval", true);
});

app.MapGet("/reject/{workflowId}", async (DaprWorkflowClient workflowClient, string workflowId) =>
{
await workflowClient.RaiseEventAsync(workflowId, "Approval", false);
});

await app.RunAsync();
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5228",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7035;http://localhost:5228",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
10 changes: 10 additions & 0 deletions examples/Workflow/WorkflowVersioning/Services/EmailService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace WorkflowVersioning.Services;

public sealed class EmailService : IEmailService
{
public Task SendEmailAsync(string to, string body)
{
// No-op
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace WorkflowVersioning.Services;

public interface IEmailService
{
Task SendEmailAsync(string to, string body);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Globalization;
using Dapr.Workflow.Versioning;

namespace WorkflowVersioning.Versioning;

public sealed class NumericalStrategy : IWorkflowVersionStrategy
{
public bool TryParse(string typeName, out string canonicalName, out string version)
{
canonicalName = string.Empty;
version = string.Empty;

if (string.IsNullOrWhiteSpace(typeName))
return false;

// Extract trailing digits as the version
int i = typeName.Length - 1;
while (i >= 0 && char.IsDigit(typeName[i]))
i--;

if (i < typeName.Length - 1)
{
canonicalName = typeName[..(i + 1)];
version = typeName[(i + 1)..];
}
else
{
canonicalName = typeName;
version = "0";
}

return true;
}

public int Compare(string? v1, string? v2)
{
var left = int.Parse(v1 ?? "0", CultureInfo.InvariantCulture);
var right = int.Parse(v2 ?? "0", CultureInfo.InvariantCulture);

return left.CompareTo(right);
}
}
21 changes: 21 additions & 0 deletions examples/Workflow/WorkflowVersioning/WorkflowVersioning.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>

<!-- Added for demonstration purposes - emit generated source files to disk for inspection -->
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\Dapr.Workflow.Versioning.Abstractions\Dapr.Workflow.Versioning.Abstractions.csproj" />
<ProjectReference Include="..\..\..\src\Dapr.Workflow.Versioning.Runtime\Dapr.Workflow.Versioning.Runtime.csproj" />
<ProjectReference Include="..\..\..\src\Dapr.Workflow.Versioning.Generators\Dapr.Workflow.Versioning.Generators.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Dapr.Workflow;
using WorkflowVersioning.Services;

namespace WorkflowVersioning.Workflows.VacationApproval.Activities;

public sealed class SendEmailActivity(IEmailService emailSvc) : WorkflowActivity<EmailActivityInput, object?>
{
public override async Task<object?> RunAsync(WorkflowActivityContext context, EmailActivityInput input)
{
await emailSvc.SendEmailAsync(input.To, input.Message);
return null;
}
}

public sealed record EmailActivityInput(string To, string Message);
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Mvc;

namespace WorkflowVersioning.Workflows.VacationApproval.Models;

public sealed record VacationRequest(
[FromQuery(Name = "name")] string EmployeeName,
[FromQuery(Name = "start")] DateOnly StartDate,
[FromQuery(Name = "end")] DateOnly EndDate);
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Dapr.Workflow;
using WorkflowVersioning.Workflows.VacationApproval.Activities;
using WorkflowVersioning.Workflows.VacationApproval.Models;

namespace WorkflowVersioning.Workflows.VacationApproval;

public sealed class VacationApprovalWorkflow : Workflow<VacationRequest, bool>
{
public override async Task<bool> RunAsync(WorkflowContext context, VacationRequest input)
{
// Oops - only send the approval if this is at least two weeks out
if (context.IsPatched("needs-two-weeks-notice"))
{
var now = context.CurrentUtcDateTime;
if (input.StartDate < new DateOnly(now.Year, now.Month, now.Day).AddDays(14))
{
// Need at least two weeks of notice
return false;
}
}

// Send approval email to the manager
await context.CallActivityAsync(nameof(SendEmailActivity),
new EmailActivityInput("manager@localhost",
$"Vacation request '{context.InstanceId}' from {input.EmployeeName} from {input.StartDate:d} to {input.EndDate:d}"));

// Wait for approval
try
{
await context.WaitForExternalEventAsync<bool>("Approval", timeout: TimeSpan.FromSeconds(120));
}
catch (TaskCanceledException)
{
await context.CallActivityAsync(nameof(SendEmailActivity),
new EmailActivityInput($"{input.EmployeeName}@localhost",
$"Vacation request '{context.InstanceId}' denied from {input.StartDate:d} to {input.EndDate:d}"));
return false;
}

await context.CallActivityAsync(nameof(SendEmailActivity),
new EmailActivityInput($"{input.EmployeeName}@localhost",
$"Vacation request '{context.InstanceId}' approved from {input.StartDate:d} to {input.EndDate:d}"));
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using Dapr.Workflow;
using WorkflowVersioning.Workflows.VacationApproval.Activities;
using WorkflowVersioning.Workflows.VacationApproval.Models;

namespace WorkflowVersioning.Workflows.VacationApproval;

public sealed class VacationApprovalWorkflowV2 : Workflow<VacationRequest, bool>
{
public override async Task<bool> RunAsync(WorkflowContext context, VacationRequest input)
{
var logger = context.CreateReplaySafeLogger<VacationApprovalWorkflowV2>();

// Only send the approval if this is at least two weeks out
var now = context.CurrentUtcDateTime;
if (input.StartDate < new DateOnly(now.Year, now.Month, now.Day).AddDays(14))
{
// Need at least two weeks of notice
return false;
}

// Send approval email to the manager
logger.LogInformation("Sending approval email to manager for workflow '{workflowId}'", context.InstanceId);
await context.CallActivityAsync(nameof(SendEmailActivity),
new EmailActivityInput("manager@localhost",
$"Vacation request '{context.InstanceId}' from {input.EmployeeName} from {input.StartDate:d} to {input.EndDate:d}"));

// Refactored the following and fixed a bug:
// 1) If the approval is rejected, still approves if the external event doesn't time out

// Wait for approval and respond accordingly
bool approvalResponse;
var denialMessage =
$"Vacation request '{context.InstanceId}' denied from {input.StartDate:d} to {input.EndDate:d}";
try
{
logger.LogInformation("Waiting for approval for workflow '{workflowId}'", context.InstanceId);
approvalResponse = await context.WaitForExternalEventAsync<bool>("Approval", timeout: TimeSpan.FromSeconds(120));
}
catch (TaskCanceledException)
{
logger.LogWarning("Approval timeout for workflow '{workflowId}'", context.InstanceId);
await context.CallActivityAsync(nameof(SendEmailActivity),
new EmailActivityInput($"{input.EmployeeName}@localhost", denialMessage));
return false;
}

var approvalMessage =
$"Vacation request '{context.InstanceId}' approved from {input.StartDate:d} to {input.EndDate:d}";
logger.LogInformation("Received approval decision for workflow '{workflowId}', status: '{status}'", context.InstanceId, approvalResponse ? "Approved" : "Denied");
var emailInput = new EmailActivityInput($"{input.EmployeeName}@localhost", approvalResponse ? approvalMessage : denialMessage);
await context.CallActivityAsync(nameof(SendEmailActivity), emailInput);

return approvalResponse;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions examples/Workflow/WorkflowVersioning/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Loading
Loading