-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInMemoryLeaseManager.cs
More file actions
63 lines (50 loc) · 2.14 KB
/
InMemoryLeaseManager.cs
File metadata and controls
63 lines (50 loc) · 2.14 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
using Microsoft.Extensions.Options;
namespace Nhs.Appointments.Core.Concurrency;
internal class InMemoryLeaseManager : ILeaseManager
{
private readonly Dictionary<string, SemaphoreSlim> _locks;
private readonly LeaseManagerOptions _defaultOptions;
public InMemoryLeaseManager(IOptions<LeaseManagerOptions> options)
{
_locks = new Dictionary<string, SemaphoreSlim>();
_defaultOptions = options.Value;
}
public string Mode => LeaseManagerMode.InMemory;
public ILeaseContext Acquire(string leaseKey, LeaseManagerOptions options = null)
{
var inMemoryLeaseKey = BuildInMemoryKey(leaseKey, options);
var mutex = ResolveMutex(inMemoryLeaseKey, options);
if (!mutex.Wait(ResolveTimeout(options)))
{
throw new AbandonedMutexException($"Abandoned attempt to acquire lock for lease key {inMemoryLeaseKey}");
}
return new LeaseContext(inMemoryLeaseKey, () => mutex.Release());
}
public async Task<ILeaseContext> AcquireAsync(string leaseKey, LeaseManagerOptions options = null)
{
var inMemoryLeaseKey = BuildInMemoryKey(leaseKey, options);
var mutex = ResolveMutex(inMemoryLeaseKey, options);
if (!(await mutex.WaitAsync(ResolveTimeout(options))))
{
throw new AbandonedMutexException($"Abandoned attempt to acquire lock for lease key {inMemoryLeaseKey}");
}
return new LeaseContext(inMemoryLeaseKey, () => mutex.Release());
}
private SemaphoreSlim ResolveMutex(string leaseKey, LeaseManagerOptions options = null)
{
SemaphoreSlim mutex;
lock (_locks)
{
if (!_locks.ContainsKey(leaseKey))
{
_locks.Add(leaseKey, new SemaphoreSlim(1,1));
}
mutex = _locks[leaseKey];
}
return mutex;
}
private string BuildInMemoryKey(string leaseKey, LeaseManagerOptions options = null) =>
$"{options?.Realm ?? _defaultOptions.Realm}_{leaseKey}";
private TimeSpan ResolveTimeout(LeaseManagerOptions options = null) =>
options?.Timeout ?? _defaultOptions.Timeout;
}