forked from temporalio/samples-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSagaWorkflow.cs
60 lines (51 loc) · 1.81 KB
/
SagaWorkflow.cs
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
using Microsoft.Extensions.Logging;
using Temporalio.Workflows;
namespace TemporalioSamples.Saga;
[Workflow]
public class SagaWorkflow
{
[WorkflowRun]
public async Task RunAsync(TransferDetails transfer)
{
List<Func<Task>> compensations = new();
var logger = Workflow.Logger;
var options = new ActivityOptions() { StartToCloseTimeout = TimeSpan.FromSeconds(90) };
try
{
await Workflow.ExecuteActivityAsync(() => Activities.Withdraw(transfer), options);
compensations.Add(async () => await Workflow.ExecuteActivityAsync(
() => Activities.WithdrawCompensation(transfer),
options));
await Workflow.ExecuteActivityAsync(() => Activities.Deposit(transfer), options);
compensations.Add(async () => await Workflow.ExecuteActivityAsync(
() => Activities.DepositCompensation(transfer),
options));
// throw new Exception
await Workflow.ExecuteActivityAsync(() => Activities.StepWithError(transfer), options);
}
catch (Exception)
{
logger.LogInformation("Exception caught. Initiating compensation...");
await CompensateAsync(compensations);
throw;
}
}
private async Task CompensateAsync(List<Func<Task>> compensations)
{
compensations.Reverse();
foreach (var comp in compensations)
{
#pragma warning disable CA1031
try
{
await comp.Invoke();
}
catch (Exception ex)
{
Workflow.Logger.LogError(ex, "Failed to compensate");
// swallow errors
}
#pragma warning restore CA1031
}
}
}