-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathProgram.cs
More file actions
113 lines (99 loc) · 3.74 KB
/
Program.cs
File metadata and controls
113 lines (99 loc) · 3.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System.Globalization;
using Microsoft.Extensions.Logging;
using Temporalio.Client;
using Temporalio.Common.EnvConfig;
using Temporalio.Exceptions;
using Temporalio.Worker;
using TemporalioSamples.UpdateWithStartLazyInit;
// Create a client to localhost on default namespace
var connectOptions = ClientEnvConfig.LoadClientConnectOptions();
connectOptions.TargetHost ??= "localhost:7233";
connectOptions.LoggerFactory = LoggerFactory.Create(builder =>
builder.
AddSimpleConsole(options => options.TimestampFormat = "[HH:mm:ss] ").
SetMinimumLevel(LogLevel.Information));
var client = await TemporalClient.ConnectAsync(connectOptions);
const string TaskQueue = "update-with-start-lazy-init";
async Task RunWorkerAsync()
{
// Cancellation token cancelled on ctrl+c
using var tokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (_, eventArgs) =>
{
tokenSource.Cancel();
eventArgs.Cancel = true;
};
// Run worker until cancelled
Console.WriteLine("Running worker");
using var worker = new TemporalWorker(
client,
new TemporalWorkerOptions(TaskQueue).
AddAllActivities(typeof(Activities), null).
AddWorkflow<ShoppingCartWorkflow>());
try
{
await worker.ExecuteAsync(tokenSource.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Worker cancelled");
}
}
async Task ExecuteWorkflowAsync()
{
Console.WriteLine("Starting to shop...");
// Add 3 of an item
var addResult = await AddCartItemAsync("session-777", new(Sku: "sku-123", 3));
Console.WriteLine($"Subtotal after item 1: {addResult.SubtotalString}");
// Add 2 of another (that is not found)
addResult = await AddCartItemAsync("session-777", new(Sku: "sku-456", 2));
Console.WriteLine($"Subtotal after item 2: {addResult.SubtotalString}");
// Checkout and display final order
await addResult.WorkflowHandle.SignalAsync(wf => wf.CheckoutAsync());
var finalOrder = await addResult.WorkflowHandle.GetResultAsync();
Console.WriteLine($"Final order: {finalOrder}");
}
async Task<AddCartItemResult> AddCartItemAsync(string sessionId, ShoppingCartItem item)
{
// Issue an update-with-start that will create the workflow if it does not
// exist before attempting the update
// Create the start operation
var startOperation = WithStartWorkflowOperation.Create(
(ShoppingCartWorkflow wf) => wf.RunAsync(),
new(id: $"cart-{sessionId}", taskQueue: TaskQueue)
{
IdConflictPolicy = Temporalio.Api.Enums.V1.WorkflowIdConflictPolicy.UseExisting,
});
// Issue the update-with-start, swallowing item-unavailable failure
decimal? subtotal;
try
{
subtotal = await client.ExecuteUpdateWithStartWorkflowAsync(
(ShoppingCartWorkflow wf) => wf.AddItemAsync(item),
new(startOperation));
}
catch (WorkflowUpdateFailedException e) when (
e.InnerException is ApplicationFailureException appErr && appErr.ErrorType == "ItemUnavailable")
{
// Set subtotal to null if item was not found
subtotal = null;
}
return new(await startOperation.GetHandleAsync(), subtotal);
}
switch (args.ElementAtOrDefault(0))
{
case "worker":
await RunWorkerAsync();
break;
case "workflow":
await ExecuteWorkflowAsync();
break;
default:
throw new ArgumentException("Must pass 'worker' or 'workflow' as the single argument");
}
public record AddCartItemResult(
WorkflowHandle<ShoppingCartWorkflow, ShoppingCartWorkflow.FinalizedOrder> WorkflowHandle,
decimal? Subtotal)
{
public string SubtotalString => Subtotal?.ToString(CultureInfo.CurrentCulture) ?? "<item not found>";
}