-
Notifications
You must be signed in to change notification settings - Fork 257
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Feature #3175
- Loading branch information
Showing
8 changed files
with
310 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
src/Paramore.Brighter.Locking.MsSql/MsSqlLockingProvider.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
#region Licence | ||
|
||
/* The MIT License (MIT) | ||
Copyright © 2021 Ian Cooper <[email protected]> | ||
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 System.Collections.Concurrent; | ||
using System.Data; | ||
using System.Data.Common; | ||
using Microsoft.Data.SqlClient; | ||
using Microsoft.Extensions.Logging; | ||
using Paramore.Brighter.Logging; | ||
using Paramore.Brighter.MsSql; | ||
|
||
namespace Paramore.Brighter.Locking.MsSql; | ||
|
||
/// <summary> | ||
/// The Microsoft Sql Server Locking Provider | ||
/// </summary> | ||
/// <param name="connectionProvider">The Sql Server connection Provider</param> | ||
public class MsSqlLockingProvider(IMsSqlConnectionProvider connectionProvider) : IDistributedLock, IAsyncDisposable | ||
{ | ||
private readonly ConcurrentDictionary<string, DbConnection> _connections = new(); | ||
|
||
private readonly ILogger _logger = ApplicationLogging.CreateLogger<MsSqlLockingProvider>(); | ||
/// <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) | ||
{ | ||
if (_connections.ContainsKey(resource)) | ||
{ | ||
return null; | ||
} | ||
|
||
var connection = await connectionProvider.GetConnectionAsync(cancellationToken); | ||
if (connection.State != ConnectionState.Open) | ||
await connection.OpenAsync(cancellationToken); | ||
|
||
await using var command = connection.CreateCommand(); | ||
command.CommandText = MsSqlLockingQueries.ObtainLockQuery; | ||
command.Parameters.Add(new SqlParameter("@Resource", SqlDbType.NVarChar, 255)); | ||
command.Parameters["@Resource"].Value = resource; | ||
command.Parameters.Add(new SqlParameter("@LockTimeout", SqlDbType.Int)); | ||
command.Parameters["@LockTimeout"].Value = 0; | ||
|
||
var result = (await command.ExecuteScalarAsync(cancellationToken)) ?? -999; | ||
|
||
var resultCode = (int)result; | ||
|
||
_logger.LogInformation("Attempt to obtain lock returned: {MsSqlLockResult}", GetLockStatusCode(resultCode)); | ||
|
||
if (resultCode < 0) | ||
return null; | ||
|
||
_connections.TryAdd(resource, connection); | ||
|
||
return resource; | ||
} | ||
|
||
/// <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) | ||
{ | ||
if (!_connections.TryRemove(resource, out var connection)) | ||
{ | ||
return; | ||
} | ||
|
||
await using var command = connection.CreateCommand(); | ||
command.CommandText = MsSqlLockingQueries.ReleaseLockQuery; | ||
command.Parameters.Add(new SqlParameter("@Resource", SqlDbType.NVarChar, 255)); | ||
command.Parameters["@Resource"].Value = resource; | ||
await command.ExecuteNonQueryAsync(cancellationToken); | ||
|
||
await connection.CloseAsync(); | ||
await connection.DisposeAsync(); | ||
} | ||
|
||
/// <summary> | ||
/// Convert Status code to messages | ||
/// Doc: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-getapplock-transact-sql?view=sql-server-ver16#return-code-values | ||
/// </summary> | ||
/// <param name="code">Status Code</param> | ||
/// <returns>Status Message</returns> | ||
private string GetLockStatusCode(int code) | ||
=> code switch | ||
{ | ||
0 => "The lock was successfully granted synchronously.", | ||
1 => "The lock was granted successfully after waiting for other incompatible locks to be released.", | ||
-1 => "The lock request timed out.", | ||
-2 => "The lock request was canceled.", | ||
-3 => "The lock request was chosen as a deadlock victim.", | ||
_ => "Indicates a parameter validation or other call error." | ||
}; | ||
|
||
/// <summary> | ||
/// Dispose Locking Provider | ||
/// </summary> | ||
public async ValueTask DisposeAsync() | ||
{ | ||
foreach (var connection in _connections) | ||
{ | ||
await connection.Value.DisposeAsync(); | ||
} | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
src/Paramore.Brighter.Locking.MsSql/MsSqlLockingQueries.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
namespace Paramore.Brighter.Locking.MsSql; | ||
|
||
public static class MsSqlLockingQueries | ||
{ | ||
public const string ObtainLockQuery = "declare @result int; " + | ||
"Exec @result = sp_getapplock " + | ||
"@DbPrincipal = 'dbo' " + | ||
",@Resource = @Resource" + | ||
",@LockMode = 'Exclusive'" + | ||
",@LockTimeout = @LockTimeout" + | ||
",@LockOwner = 'Session'; " + | ||
"Select @result"; | ||
|
||
public const string ReleaseLockQuery = "EXEC sp_releaseapplock " + | ||
"@Resource = @Resource " + | ||
",@DbPrincipal = 'dbo' " + | ||
",@LockOwner = 'Session';"; | ||
} |
21 changes: 21 additions & 0 deletions
21
src/Paramore.Brighter.Locking.MsSql/Paramore.Brighter.Locking.MsSql.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> | ||
<Authors>Paul Reardon</Authors> | ||
<Description>A Locking Provider for Microsoft SQL Server</Description> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Paramore.Brighter.MsSql\Paramore.Brighter.MsSql.csproj" /> | ||
<ProjectReference Include="..\Paramore.Brighter\Paramore.Brighter.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Data.SqlClient" /> | ||
</ItemGroup> | ||
|
||
</Project> |
100 changes: 100 additions & 0 deletions
100
tests/Paramore.Brighter.MSSQL.Tests/LockingProvider/MsSqlLockingProviderTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
using System; | ||
using System.Data; | ||
using System.Data.Common; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.Data.SqlClient; | ||
using Microsoft.Extensions.Logging.Abstractions; | ||
using Paramore.Brighter.Locking.MsSql; | ||
using Paramore.Brighter.MsSql; | ||
using Xunit; | ||
|
||
namespace Paramore.Brighter.MSSQL.Tests.LockingProvider; | ||
|
||
[Trait("Category", "MSSQL")] | ||
public class MsSqlLockingProviderTests | ||
{ | ||
private readonly MsSqlTestHelper _msSqlTestHelper; | ||
|
||
public MsSqlLockingProviderTests() | ||
{ | ||
_msSqlTestHelper = new MsSqlTestHelper(); | ||
_msSqlTestHelper.SetupMessageDb(); | ||
} | ||
|
||
|
||
[Fact] | ||
public async Task GivenAMsSqlLockingProvider_WhenLockIsCalled_LockCanBeObtainedAndThenReleased() | ||
{ | ||
var provider = new MsSqlLockingProvider(_msSqlTestHelper.ConnectionProvider); | ||
var resource = "Sweeper"; | ||
|
||
var result = await provider.ObtainLockAsync(resource, CancellationToken.None); | ||
|
||
Assert.NotEmpty(result); | ||
Assert.Equal(resource, result); | ||
|
||
await provider.ReleaseLockAsync(resource, result, CancellationToken.None); | ||
} | ||
|
||
[Fact] | ||
public async Task GivenTwoLockingProviders_WhenLockIsCalledOnBoth_OneFailsUntilTheFirstLockIsReleased() | ||
{ | ||
var provider1 = new MsSqlLockingProvider(_msSqlTestHelper.ConnectionProvider); | ||
var provider2 = new MsSqlLockingProvider(_msSqlTestHelper.ConnectionProvider); | ||
var resource = "Sweeper"; | ||
|
||
var firstLock = await provider1.ObtainLockAsync(resource, CancellationToken.None); | ||
var secondLock = await provider2.ObtainLockAsync(resource, CancellationToken.None); | ||
|
||
Assert.NotEmpty(firstLock); | ||
Assert.Null(secondLock); | ||
|
||
await provider1.ReleaseLockAsync(resource, firstLock, CancellationToken.None); | ||
var secondLockAttemptTwo = await provider2.ObtainLockAsync(resource, CancellationToken.None); | ||
|
||
Assert.NotEmpty(secondLockAttemptTwo); | ||
} | ||
|
||
[Fact] | ||
public async Task GivenAnExistingLock_WhenConnectionDies_LockIsReleased() | ||
{ | ||
var resource = Guid.NewGuid().ToString(); | ||
var connection = await ObtainLockForManualDisposal(resource); | ||
|
||
var provider1 = new MsSqlLockingProvider(_msSqlTestHelper.ConnectionProvider); | ||
|
||
var lockAttempt = await provider1.ObtainLockAsync(resource, CancellationToken.None); | ||
|
||
// Ensure Lock was not obtained | ||
Assert.Null(lockAttempt); | ||
|
||
await connection.DisposeAsync(); | ||
|
||
var lockAttemptTwo = await provider1.ObtainLockAsync(resource, CancellationToken.None); | ||
|
||
// Ensure Lock was Obtained | ||
Assert.False(string.IsNullOrEmpty(lockAttemptTwo)); | ||
} | ||
|
||
private async Task<DbConnection> ObtainLockForManualDisposal(string resource) | ||
{ | ||
var connectionProvider = _msSqlTestHelper.ConnectionProvider; | ||
var connection = await connectionProvider.GetConnectionAsync(CancellationToken.None); | ||
await connection.OpenAsync(); | ||
var command = connection.CreateCommand(); | ||
command.CommandText = MsSqlLockingQueries.ObtainLockQuery; | ||
command.Parameters.Add(new SqlParameter("@Resource", SqlDbType.NVarChar, 255)); | ||
command.Parameters["@Resource"].Value = resource; | ||
command.Parameters.Add(new SqlParameter("@LockTimeout", SqlDbType.Int)); | ||
command.Parameters["@LockTimeout"].Value = 0; | ||
|
||
var respone = await command.ExecuteScalarAsync(CancellationToken.None); | ||
|
||
//Assert Lock was successful | ||
int.TryParse(respone.ToString(), out var responseCode); | ||
Assert.True(responseCode >= 0); | ||
|
||
return connection; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters