Skip to content
Open
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
292 changes: 115 additions & 177 deletions workflows/csharp/sdk/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ internal sealed partial class RequestApprovalActivity(ILogger<RequestApprovalAct
{
public override async Task<object?> RunAsync(WorkflowActivityContext context, ApprovalRequest approvalRequest)
{
LogRequestApproval(logger, approvalRequest);

// Simulate slow processing & sending the approval to the recipient
await Task.Delay(TimeSpan.FromSeconds(2));

LogRequestApproval(logger, approvalRequest.RequestId);

return Task.FromResult<object?>(null);
}

[LoggerMessage(LogLevel.Information, "Approval Request {approvalRequest}")]
static partial void LogRequestApproval(ILogger logger, ApprovalRequest approvalRequest);
[LoggerMessage(LogLevel.Information, "Approval requested for order {orderId}. Waiting for approval.")]
static partial void LogRequestApproval(ILogger logger, string orderId);
}
46 changes: 44 additions & 2 deletions workflows/csharp/sdk/order-processor/Models.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,51 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace WorkflowConsoleApp.Models;

internal sealed record OrderPayload(string Name, double TotalCost, int Quantity = 1);
internal sealed record InventoryRequest(string RequestId, string ItemName, int Quantity);
internal sealed record InventoryResult(bool Success, OrderPayload? OrderPayload);
internal sealed record ApprovalRequest(string RequestId, string ItemBeingPurchased, int Quantity, double Amount);
internal sealed record ApprovalResponse(string RequestId, bool IsApproved);
[JsonConverter(typeof(ApprovalResponseConverter))]
internal sealed record ApprovalResponse(bool Approved);
internal sealed record PaymentRequest(string RequestId, string ItemBeingPurchased, int Amount, double Currency);
internal sealed record OrderResult(bool Processed);
internal sealed record OrderResult(bool Processed);

// The Dapr CLI can send the event payload as a JSON object or as a JSON string that holds the object.
// This converter reads both: {"approved": true} and "{\"approved\": true}".
internal sealed class ApprovalResponseConverter : JsonConverter<ApprovalResponse>
{
public override ApprovalResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var document = JsonDocument.ParseValue(ref reader);
var element = document.RootElement;
if (element.ValueKind == JsonValueKind.String)
{
using var inner = JsonDocument.Parse(element.GetString()!);
return new ApprovalResponse(ReadApproved(inner.RootElement));
}

return new ApprovalResponse(ReadApproved(element));
}

private static bool ReadApproved(JsonElement element)
{
foreach (var property in element.EnumerateObject())
{
if (string.Equals(property.Name, "approved", StringComparison.OrdinalIgnoreCase))
{
return property.Value.ValueKind == JsonValueKind.True;
}
}

return false;
}

public override void Write(Utf8JsonWriter writer, ApprovalResponse value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteBoolean("approved", value.Approved);
writer.WriteEndObject();
}
}
104 changes: 75 additions & 29 deletions workflows/csharp/sdk/order-processor/Program.cs
Original file line number Diff line number Diff line change
@@ -1,52 +1,98 @@
using Dapr.StateManagement.Extensions;
using Dapr.StateManagement.Extensions;
using Dapr.Workflow;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using WorkflowConsoleApp.Models;
using WorkflowConsoleApp.Models.State;
using WorkflowConsoleApp.Workflows;

// The workflow host is a background service that connects to the sidecar over gRPC
using var host = Host.CreateDefaultBuilder(args).ConfigureServices(services =>
{
services.AddDaprStateManagementClient()
.WithInventoryStore();
services.AddDaprWorkflow();
}).Build();
using var host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging => logging
// Keep the console to the order lines: hide the SDK, HTTP client and gRPC client info lines
.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning)
.AddFilter("Grpc.Net.Client", LogLevel.Critical)
.AddFilter("Dapr.Workflow", LogLevel.Warning)
// Ctrl+C closes the sidecar connection, and the worker logs that as an error with a stack trace
.AddFilter("Dapr.Workflow.Worker", LogLevel.Critical)
.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning))
.ConfigureServices(services =>
{
services.AddDaprStateManagementClient()
.WithInventoryStore();
services.AddDaprWorkflow();
}).Build();

// Start the app - this is the point where we connect to the Dapr sidecar
host.Start();

// Ctrl+C cancels this token, so the app stops while it waits for the workflow
var stopping = host.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStopping;
var workflowClient = host.Services.GetRequiredService<DaprWorkflowClient>();

// Generate a unique ID for the workflow
var orderId = Guid.NewGuid().ToString()[..8];
// The workflow instance ID is the order ID. Set ORDER_ID to use the same instance again after a restart
var orderId = Environment.GetEnvironmentVariable("ORDER_ID");
if (string.IsNullOrWhiteSpace(orderId))
{
orderId = $"order-{DateTime.Now:yyyyMMdd-HHmmss}";
}

const string itemToPurchase = "Cars";
const int amountToPurchase = 1;
const int amountToPurchase = 2;
const double pricePerItem = 5000;

// Populate the store with items
var stateStore = host.Services.GetRequiredService<IInventoryStore>();
await stateStore.SaveStateAsync(itemToPurchase, new OrderPayload(Name: itemToPurchase, TotalCost: 50000, Quantity: 10));
Console.WriteLine($"Order ID: {orderId}");

// Construct the order
var orderInfo = new OrderPayload(itemToPurchase, 5000, amountToPurchase);
try
{
// Populate the store with items only when the inventory is not there yet, so a restart does not restock
var stateStore = host.Services.GetRequiredService<IInventoryStore>();
var (inventory, _) = await stateStore.GetStateAndETagAsync<OrderPayload>(itemToPurchase, cancellationToken: stopping);
if (inventory is null)
{
await stateStore.SaveStateAsync(itemToPurchase, new OrderPayload(Name: itemToPurchase, TotalCost: 50000, Quantity: 10), cancellationToken: stopping);
}

// Start the workflow
Console.WriteLine($"Starting workflow {orderId} purchasing {amountToPurchase} {itemToPurchase}");
// Check if the workflow instance exists already
var existing = await workflowClient.GetWorkflowStateAsync(orderId, getInputsAndOutputs: false, cancellation: stopping);
if (existing is { Exists: true })
{
if (existing.RuntimeStatus is WorkflowRuntimeStatus.Completed or WorkflowRuntimeStatus.Failed or WorkflowRuntimeStatus.Terminated)
{
// The workflow ended already, so there is nothing to wait for
Console.WriteLine($"Workflow completed: {existing.RuntimeStatus.ToString().ToUpperInvariant()}");
return;
}

await workflowClient.ScheduleNewWorkflowAsync(
name: nameof(OrderProcessingWorkflow),
instanceId: orderId,
input: orderInfo);
Console.WriteLine($"Order {orderId} is already running. Waiting for it to finish.");
}
else
{
// Construct the order: 2 cars at 5000 each. A total over 5000 needs an approval
var orderInfo = new OrderPayload(itemToPurchase, pricePerItem * amountToPurchase, amountToPurchase);

// Wait for the workflow to start and confirm the input
var state = await workflowClient.WaitForWorkflowStartAsync(
instanceId: orderId);
await workflowClient.ScheduleNewWorkflowAsync(
name: nameof(OrderProcessingWorkflow),
instanceId: orderId,
input: orderInfo,
startTime: null,
cancellation: stopping);

Console.WriteLine($"Your workflow has started. Here is the status of the workflow: {Enum.GetName(typeof(WorkflowRuntimeStatus), state.RuntimeStatus)}");
Console.WriteLine($"Started order {orderId}.");
}

// Wait for the workflow to complete
state = await workflowClient.WaitForWorkflowCompletionAsync(
instanceId: orderId);
// Wait for the workflow to finish. The approval timeout is 10 minutes, so wait longer than that
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stopping);
timeout.CancelAfter(TimeSpan.FromMinutes(15));
var state = await workflowClient.WaitForWorkflowCompletionAsync(
instanceId: orderId,
getInputsAndOutputs: false,
cancellation: timeout.Token);

Console.WriteLine("Workflow Status: {0}", Enum.GetName(typeof(WorkflowRuntimeStatus), state.RuntimeStatus));
Console.WriteLine($"Workflow completed: {state.RuntimeStatus.ToString().ToUpperInvariant()}");
}
catch (OperationCanceledException)
{
// Ctrl+C or the 15 minute wait ended. The workflow keeps its state in the state store
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ await context.CallActivityAsync(nameof(RequestApprovalActivity),

var approvalResponse = await context.WaitForExternalEventAsync<ApprovalResponse>(
eventName: "ApprovalEvent",
timeout: TimeSpan.FromSeconds(30));
if (!approvalResponse.IsApproved)
timeout: TimeSpan.FromMinutes(10));
if (!approvalResponse.Approved)
{
await context.CallActivityAsync(nameof(NotifyActivity),
new Notification($"Order {orderId} was not approved"));
Expand Down
139 changes: 96 additions & 43 deletions workflows/go/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,38 @@ inventory, their payment couldn't be processed, and more.

### Run the order processor workflow

The app starts one order for 2 cars at 5000 each. The total is 10000, which is over 5000, so the workflow waits for an approval. In these steps you stop the app while it waits, start it again, and then approve the order.

1. Open a new terminal window in this quickstart directory.
2. Run the console app with Dapr:
2. Set an order ID. The app uses it as the workflow instance ID.

Linux and macOS:

```sh
export ORDER_ID=order-$(date +%Y%m%d-%H%M%S)
```

Windows (PowerShell):

```powershell
$env:ORDER_ID = "order-$(Get-Date -Format yyyyMMdd-HHmmss)"
```

3. Run the console app with Dapr:

<!-- STEP
name: Running this example
name: Run the order processor
expected_stdout_lines:
- "for 1 cars - $5000"
- "There are 10 cars available for purchase"
- "There are now 9 cars left in stock"
- "workflow status: COMPLETED"
- "Order ID: order-validate"
- "Started order order-validate."
- "Approval requested for order order-validate. Waiting for approval."
- "Workflow completed: COMPLETED"
output_match_mode: substring
background: false
env:
ORDER_ID: order-validate
background: true
sleep: 40
timeout_seconds: 120
sleep: 30
-->

```sh
Expand All @@ -41,36 +60,67 @@ dapr run -f .

<!-- END_STEP -->

3. Expected output
The log shows the order ID, `Started order <id>.`, the steps before the approval, and then the approval request:

```
*** Welcome to the Dapr Workflow console app sample!
*** Using this app, you can place orders that start workflows.
dapr client initializing for: 127.0.0.1:46533
INFO: 2025/02/13 13:18:33 connecting work item listener stream
2025/02/13 13:18:33 work item listener started
INFO: 2025/02/13 13:18:33 starting background processor
adding base stock item: paperclip
adding base stock item: cars
adding base stock item: computers
==========Begin the purchase of item:==========
NotifyActivity: Received order b4cb2687-1af0-4f8d-9659-eb6389c07ade for 1 cars - $5000
VerifyInventoryActivity: Verifying inventory for order b4cb2687-1af0-4f8d-9659-eb6389c07ade of 1 cars
VerifyInventoryActivity: There are 10 cars available for purchase
ProcessPaymentActivity: b4cb2687-1af0-4f8d-9659-eb6389c07ade for 1 - cars (5000USD)
UpdateInventoryActivity: Checking Inventory for order b4cb2687-1af0-4f8d-9659-eb6389c07ade for 1 * cars
UpdateInventoryActivity: There are now 9 cars left in stock
NotifyActivity: Order b4cb2687-1af0-4f8d-9659-eb6389c07ade has completed!
workflow status: COMPLETED
Purchase of item is complete
```
```
Order ID: order-20261024-101500
adding base stock item: paperclip
adding base stock item: cars
adding base stock item: computers
Started order order-20261024-101500.
NotifyActivity: Received order order-20261024-101500 for 2 cars - $10000
VerifyInventoryActivity: Verifying inventory for order order-20261024-101500 of 2 cars
VerifyInventoryActivity: There are 10 cars available for purchase
Approval requested for order order-20261024-101500. Waiting for approval.
```

4. Stop the app with CTRL+C. The order is not finished. Its state is in the state store.
5. Start the app again in the same terminal. `ORDER_ID` is still set.

4. Stop Dapr workflow with CTRL-C or:
```sh
dapr run -f .
```

The log shows that the order exists:

```
Order ID: order-20261024-101500
Order order-20261024-101500 is already running. Waiting for it to finish.
```

The steps before the approval do not run again.

6. Open a second terminal. Set `ORDER_ID` to the order ID that the app printed (`export ORDER_ID=<id>`, or `$env:ORDER_ID = "<id>"` in PowerShell). Then approve the order:

<!-- STEP
name: Approve the order
env:
ORDER_ID: order-validate
expected_stdout_lines:
- "raised event"
output_match_mode: substring
timeout_seconds: 30
-->

```sh
dapr stop -f .
dapr workflow raise-event $ORDER_ID/ApprovalEvent --app-id order-processor --input '{"approved": true}'
```

<!-- END_STEP -->

In the first terminal, the workflow continues with the payment and the inventory update. The app ends:

```
NotifyActivity: Payment for order order-20261024-101500 has been approved!
ProcessPaymentActivity: order-20261024-101500 for 2 - cars (10000USD)
UpdateInventoryActivity: Checking Inventory for order order-20261024-101500 for 2 * cars
UpdateInventoryActivity: There are now 8 cars left in stock
NotifyActivity: Order order-20261024-101500 has completed!
Workflow completed: COMPLETED
```

In the second run, the `Received order`, the inventory check and the approval request lines did not appear again. The workflow continued from its history. A step that was running at the moment of the stop can run again. If you wait longer than 10 minutes for the approval, the workflow cancels the order.

### Run without Docker

By default, the quickstart uses Redis in Docker as the workflow state store, and the Dapr Placement and Scheduler services in Docker. You can run the quickstart without Docker and Redis and instead run the Dapr binaries as processes, and use an SQLite file to keep the workflow state.
Expand Down Expand Up @@ -129,6 +179,8 @@ The commands are for Linux and macOS, and for Windows (PowerShell).
dapr run -f dapr-sqlite.yaml
```

Then follow steps 2 to 6 above, with `dapr run -f dapr-sqlite.yaml` as the run command. Set `ORDER_ID` in this terminal before you start the app.

`dapr-sqlite.yaml` is the same as `dapr.yaml`, but its `resourcesPath` points to the [`components-sqlite`](../../components-sqlite/) folder. That folder has a SQLite state store with `actorStateStore` set to `"true"`. The expected output is the same as in the steps above.

To start again with no workflow state, stop all processes and delete the `scheduler-data` folder and the `workflows.db` file in the `order-processor` folder.
Expand Down Expand Up @@ -164,14 +216,15 @@ launched on running `dapr init`.

When you ran the above commands:

1. An OrderPayload is made containing one car.
2. A unique order ID for the workflow is generated (in the above example, `b4cb2687-1af0-4f8d-9659-eb6389c07ade`) and the workflow is scheduled.
3. The `NotifyActivity` workflow activity sends a notification saying an order for 1 car has been received.
4. The `VerifyInventoryActivity` workflow activity checks the inventory data, determines if you can supply the ordered item, and responds with the number of cars in stock.
5. The total cost of the order is 5000, so the workflow will not call the `RequestApprovalActivity` activity.
6. The `ProcessPaymentActivity` workflow activity begins processing payment for order `b4cb2687-1af0-4f8d-9659-eb6389c07ade` and confirms if successful.
7. The `UpdateInventoryActivity` workflow activity updates the inventory with the current available cars after the order has been processed.
8. The `NotifyActivity` workflow activity sends a notification saying that order `b4cb2687-1af0-4f8d-9659-eb6389c07ade` has completed.
9. The workflow terminates as completed and the OrderResult is set to processed.

> **Note:** This quickstart uses an OrderPayload of one car with a total cost of $5000. Since the total order cost is not over 5000, the workflow will not call the `RequestApprovalActivity` activity nor wait for an approval event. Since the quickstart is a console application, it can't accept incoming events easily. If you want to test this scenario, convert the console app to a service and use the [raise event API](https://docs.dapr.io/reference/api/workflow_api/#raise-event-request) via HTTP/gRPC or via the Dapr Workflow client to send an event to the workflow instance.
1. An OrderPayload is made containing two cars.
2. The app reads the order ID from `ORDER_ID` (for example `order-20261024-101500`). It uses the ID as the workflow instance ID. If the instance does not exist, the app schedules the workflow. If it exists and is not finished, the app waits for it.
3. The app writes the starting inventory to the state store only when the inventory is not there yet. A restart does not reset the stock.
4. The `NotifyActivity` workflow activity sends a notification saying an order for 2 cars has been received.
5. The `VerifyInventoryActivity` workflow activity checks the inventory data, determines if you can supply the ordered item, and responds with the number of cars in stock.
6. The total cost of the order is 10000, so the workflow calls the `RequestApprovalActivity` activity and waits up to 10 minutes for the `ApprovalEvent` event.
7. When you raise `ApprovalEvent` with `{"approved": true}`, the `ProcessPaymentActivity` workflow activity processes the payment.
8. The `UpdateInventoryActivity` workflow activity updates the inventory with the current available cars after the order has been processed.
9. The `NotifyActivity` workflow activity sends a notification saying that the order has completed.
10. The workflow terminates as completed and the OrderResult is set to processed.

> **Note:** If you set `approved` to `false`, the workflow sends a rejection notification and ends without a payment. To skip the approval, change the order in `main.go` to 1 car (total 5000).
Loading
Loading