forked from BrighterCommand/Brighter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamoDbLockingProvider.cs
145 lines (131 loc) · 6.11 KB
/
DynamoDbLockingProvider.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
134
135
136
137
138
139
140
141
142
143
144
145
#region Licence
/* The MIT License (MIT)
Copyright © 2024 Dominic Hickie <dominichickie@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Microsoft.Extensions.Logging;
using Paramore.Brighter.Logging;
namespace Paramore.Brighter.Locking.DynamoDb
{
public class DynamoDbLockingProvider : IDistributedLock
{
private readonly IAmazonDynamoDB _dynamoDb;
private readonly DynamoDbLockingProviderOptions _options;
private readonly TimeProvider _timeProvider;
private static readonly ILogger s_logger = ApplicationLogging.CreateLogger<DynamoDbLockingProvider>();
public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options)
:this(dynamoDb, options, TimeProvider.System)
{
}
public DynamoDbLockingProvider(IAmazonDynamoDB dynamoDb, DynamoDbLockingProviderOptions options, TimeProvider timeProvider)
{
_dynamoDb = dynamoDb;
_options = options;
_timeProvider = timeProvider;
}
/// <summary>
/// Attempt to obtain a lock on a resource
/// </summary>
/// <param name="resource">The name of the resource to Lock</param>
/// <param name="cancellationToken">The Cancellation Token</param>
/// <returns>The id of the lock that has been acquired or null if no lock was able to be acquired</returns>
public async Task<string?> ObtainLockAsync(string resource, CancellationToken cancellationToken = default)
{
var lockId = Guid.NewGuid().ToString();
try
{
await _dynamoDb.PutItemAsync(BuildLockRequest(resource, lockId), cancellationToken);
}
catch (ConditionalCheckFailedException)
{
s_logger.LogInformation("Unable to obtain lock for resource {resource}, an existing lock is in place", resource);
return null;
}
s_logger.LogInformation("Obtained lock {lockId} for resource {resource}", lockId, resource);
return lockId;
}
/// <summary>
/// Release a lock
/// </summary>
/// <param name="resource">The name of the resource to Lock</param>
/// <param name="lockId">The lock Id that was provided when the lock was obtained</param>
/// <param name="cancellationToken"></param>
/// <returns>Awaitable Task</returns>
public async Task ReleaseLockAsync(string resource, string lockId, CancellationToken cancellationToken = default)
{
if (_options.ManuallyReleaseLock)
{
try
{
await _dynamoDb.DeleteItemAsync(BuildReleaseRequest(resource, lockId), cancellationToken);
}
catch (ConditionalCheckFailedException)
{
s_logger.LogInformation("Unable to release lock {lockId} for resource {resourceId} - lock has expired", lockId, resource);
}
}
}
private PutItemRequest BuildLockRequest(string resource, string lockId)
{
var now = _timeProvider.GetUtcNow();
var leaseExpiry = now.Add(_options.LeaseValidity);
return new PutItemRequest
{
TableName = _options.LockTableName,
Item = new Dictionary<string, AttributeValue>
{
{"ResourceId", new AttributeValue{ S = $"{_options.LeaseholderGroupId}_{resource}"} },
{"LeaseExpiry", new AttributeValue{ N = leaseExpiry.ToUnixTimeMilliseconds().ToString()} },
{"LockId", new AttributeValue{S = lockId} }
},
ConditionExpression = "attribute_not_exists(#r) OR (attribute_exists(#r) AND #e <= :t)",
ExpressionAttributeNames = new Dictionary<string, string>
{
{"#r", "LockId"},
{"#e", "LeaseExpiry"}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{":t", new AttributeValue {N = now.ToUnixTimeMilliseconds().ToString()} }
}
};
}
private DeleteItemRequest BuildReleaseRequest(string resource, string leaseId)
{
return new DeleteItemRequest
{
TableName = _options.LockTableName,
Key = new Dictionary<string, AttributeValue>
{
{"ResourceId", new AttributeValue{S = $"{_options.LeaseholderGroupId}_{resource}"} }
},
ConditionExpression = "attribute_exists(#r) AND #l = :l",
ExpressionAttributeNames = new Dictionary<string, string>
{
{"#r", "ResourceId"},
{"#l", "LockId"}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{":l", new AttributeValue{S = leaseId} }
}
};
}
}
}