forked from temporalio/samples-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorkflowMutex.cs
133 lines (108 loc) · 4.79 KB
/
WorkflowMutex.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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
namespace TemporalioSamples.Mutex.Impl;
using Temporalio.Workflows;
internal record AcquireLockInput(string ReleaseSignalName);
/// <summary>
/// Represents a mutual exclusion mechanism for Workflows.
/// This part contains API for acquiring locks.
/// </summary>
public static class WorkflowMutex
{
private const string MutexWorkflowIdPrefix = "__wm-lock:";
public static async Task<ILockHandle> LockAsync(string resourceId, TimeSpan? lockTimeout = null)
{
if (!Workflow.InWorkflow)
{
throw new InvalidOperationException("Cannot acquire a lock outside of a workflow.");
}
var initiatorId = Workflow.Info.WorkflowId;
var lockStarted = Workflow.UtcNow;
string? releaseSignalName = null;
var acquireLockSignalName = Workflow.NewGuid().ToString();
var signalDefinition = WorkflowSignalDefinition.CreateWithoutAttribute(acquireLockSignalName, (AcquireLockInput input) =>
{
releaseSignalName = input.ReleaseSignalName;
return Task.CompletedTask;
});
Workflow.Signals[acquireLockSignalName] = signalDefinition;
try
{
var startMutexWorkflowInput = new SignalWithStartMutexWorkflowInput($"{MutexWorkflowIdPrefix}{resourceId}", resourceId, acquireLockSignalName, lockTimeout);
await Workflow.ExecuteActivityAsync<MutexActivities>(
act => act.SignalWithStartMutexWorkflowAsync(startMutexWorkflowInput),
new ActivityOptions { StartToCloseTimeout = TimeSpan.FromMinutes(1), });
await Workflow.WaitConditionAsync(() => releaseSignalName != null);
var elapsed = Workflow.UtcNow - lockStarted;
Workflow.Logger.LogInformation(
"Lock for resource '{ResourceId}' acquired in {AcquireTime}ms by '{LockInitiatorId}', release signal name '{ReleaseSignalName}'",
resourceId,
(int)elapsed.TotalMilliseconds,
initiatorId,
releaseSignalName);
return new LockHandle(initiatorId, startMutexWorkflowInput.MutexWorkflowId, resourceId, releaseSignalName!);
}
finally
{
Workflow.Signals.Remove(acquireLockSignalName);
}
}
internal static ILockHandler CreateLockHandler()
{
if (!Workflow.InWorkflow)
{
throw new InvalidOperationException("Cannot acquire a lock outside of a workflow.");
}
return new LockHandler();
}
internal sealed class LockHandle : ILockHandle
{
private readonly string mutexWorkflowId;
public LockHandle(string lockInitiatorId, string mutexWorkflowId, string resourceId, string releaseSignalId)
{
LockInitiatorId = lockInitiatorId;
this.mutexWorkflowId = mutexWorkflowId;
ResourceId = resourceId;
ReleaseSignalName = releaseSignalId;
}
/// <inheritdoc />
public string LockInitiatorId { get; }
/// <inheritdoc />
public string ResourceId { get; }
/// <inheritdoc />
public string ReleaseSignalName { get; }
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
var mutexHandle = Workflow.GetExternalWorkflowHandle(mutexWorkflowId);
await mutexHandle.SignalAsync(ReleaseSignalName, Array.Empty<object?>());
}
}
internal sealed class LockHandler : ILockHandler
{
/// <inheritdoc />
public string? CurrentOwnerId { get; private set; }
/// <inheritdoc />
public async Task HandleAsync(LockRequest lockRequest)
{
var releaseSignalName = Workflow.NewGuid().ToString();
var initiator = Workflow.GetExternalWorkflowHandle(lockRequest.InitiatorId);
await initiator.SignalAsync(lockRequest.AcquireLockSignalName, new[] { new AcquireLockInput(releaseSignalName) });
var released = false;
Workflow.Signals[releaseSignalName] = WorkflowSignalDefinition.CreateWithoutAttribute(releaseSignalName, () =>
{
released = true;
return Task.CompletedTask;
});
CurrentOwnerId = lockRequest.InitiatorId;
if (!await Workflow.WaitConditionAsync(() => released, lockRequest.Timeout ?? Timeout.InfiniteTimeSpan))
{
Workflow.Logger.LogWarning(
"Lock for resource '{ResourceId}' has been timed out after '{Timeout}'. (LockInitiatorId='{LockInitiatorId}')",
Workflow.Info.WorkflowId[MutexWorkflowIdPrefix.Length..],
lockRequest.Timeout,
lockRequest.InitiatorId);
}
CurrentOwnerId = null;
Workflow.Signals.Remove(releaseSignalName);
}
}
}