Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added SqlServer for distributed lock #4

Merged
merged 3 commits into from
Jul 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions source/Locks.SqlServer/Extensions/ExntesionUseSqlServer.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
using Locks.Configurators;
using Locks.Internals.Distributed.Storage;
using Locks.SqlServer.Internals;
using Microsoft.Extensions.DependencyInjection;

namespace Locks.SqlServer.Extensions
namespace Locks
{
public static class ExntesionUseSqlServer
{
public static void UseSqlServer(
this IDistributedLockStorageConfigurator configurator)
this IDistributedLockStorageConfigurator configurator,
string connectionString)
{
var services = configurator.Services;

services.AddSingleton(new SqlServerConnectionFactory(connectionString));
services.AddSingleton<IDistributedLockRepository, SqlServerDistributedLockRepository>();
}
}
}
14 changes: 14 additions & 0 deletions source/Locks.SqlServer/Internals/SqlServerConnectionFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.Data.SqlClient;
using System.Data.Common;

namespace Locks.SqlServer.Internals
{
internal sealed class SqlServerConnectionFactory
{
private readonly string _connectionString;

internal SqlServerConnectionFactory(string connectionString) => _connectionString = connectionString;

public SqlConnection Create() => new SqlConnection(_connectionString);
}
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,85 @@
using System;
using System.Threading.Tasks;
using Locks.Internals.Distributed.Storage;
using Microsoft.Data.SqlClient;

namespace Locks.SqlServer.Internals
{
internal sealed class SqlServerDistributedLockRepository : IDistributedLockRepository
{
public Task AddFirstLock(DistributedLockStorageModel @lock)
private readonly SqlServerConnectionFactory _connectionFactory;

public SqlServerDistributedLockRepository(SqlServerConnectionFactory connectionFactory)
{
throw new NotImplementedException();
_connectionFactory = connectionFactory;
}

public Task<bool> Release(DistributedLockStorageModel @lock, DateTime nowUtc)
public async Task AddFirstLock(DistributedLockStorageModel @lock)
{
throw new NotImplementedException();
const string queryString = "INSERT INTO [dbo].[DistributedLocks] VALUES (@Key, @ExpirationUtc)";

using (var connection = _connectionFactory.Create())
{
SqlCommand command = new SqlCommand(queryString, connection);

command.Parameters.Add(new SqlParameter("ExpirationUtc", @lock.ExpirationUtc));
command.Parameters.Add(new SqlParameter("Key", @lock.Key));

connection.Open();

await command
.ExecuteNonQueryAsync()
.ConfigureAwait(false);
}
}

public Task<bool> TryAcquire(string key, DateTime nowUtc, DateTime newExpirationUtc)
public async Task<bool> Release(DistributedLockStorageModel @lock, DateTime nowUtc)
{
throw new NotImplementedException();
const string queryString = "UPDATE [dbo].[DistributedLocks] SET ExpirationUtc = @NowUtc WHERE [Key] = @Key AND ExpirationUtc = @ExpirationUtc";

int updatedRows = 0;

using (var connection = _connectionFactory.Create())
{
SqlCommand command = new SqlCommand(queryString, connection);

command.Parameters.Add(new SqlParameter("NowUtc", nowUtc));
command.Parameters.Add(new SqlParameter("ExpirationUtc", @lock.ExpirationUtc));
command.Parameters.Add(new SqlParameter("Key", @lock.Key));


connection.Open();

updatedRows = await command
.ExecuteNonQueryAsync()
.ConfigureAwait(false);
}

return updatedRows > 0;
}

public async Task<bool> TryAcquire(string key, DateTime nowUtc, DateTime newExpirationUtc)
{
const string queryString = "UPDATE [dbo].[DistributedLocks] SET ExpirationUtc = @ExpirationUtc WHERE [Key] = @Key AND ExpirationUtc <= @NowUtc";

int updatedRows = 0;

using (var connection = _connectionFactory.Create())
{
SqlCommand command = new SqlCommand(queryString, connection);

command.Parameters.Add(new SqlParameter("ExpirationUtc", newExpirationUtc));
command.Parameters.Add(new SqlParameter("Key", key));
command.Parameters.Add(new SqlParameter("NowUtc", nowUtc));

connection.Open();

updatedRows = await command
.ExecuteNonQueryAsync()
.ConfigureAwait(false);
}

return updatedRows > 0;
}
}
}
4 changes: 4 additions & 0 deletions source/Locks.SqlServer/Locks.SqlServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Locks\Locks.csproj" />
</ItemGroup>
Expand Down
97 changes: 97 additions & 0 deletions tests/Locks.Tests/DistributedLockTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using Locks.Tests.Seed;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.MsSql;
using Xunit;

namespace Locks.Tests
{
public sealed class DistributedLockTests : IAsyncLifetime
{
private IServiceProvider _serviceProvider;

Check warning on line 11 in tests/Locks.Tests/DistributedLockTests.cs

View workflow job for this annotation

GitHub Actions / Build & Tests

Non-nullable field '_serviceProvider' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.

Check warning on line 11 in tests/Locks.Tests/DistributedLockTests.cs

View workflow job for this annotation

GitHub Actions / Build & Tests

Non-nullable field '_serviceProvider' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.

public async Task InitializeAsync()
{
var msSqlContainer = new MsSqlBuilder().Build();

await msSqlContainer.StartAsync();

var connectionString = msSqlContainer.GetConnectionString();

IServiceCollection services = new ServiceCollection();

services.AddDistributedLock(x => x.UseSqlServer(connectionString));

// KeyedInMemoryLock is disabled because we want multiple tasks to query the database
services.AddSingleton<IMemoryLock, DisabledMemoryLock>();

_serviceProvider = services.BuildServiceProvider();

const string queryStringCreate = "CREATE TABLE [dbo].[DistributedLocks] ([Key] VARCHAR(60) NOT NULL PRIMARY KEY, [ExpirationUtc] DATETIME NOT NULL)";

using (var connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryStringCreate, connection);

connection.Open();

await command
.ExecuteNonQueryAsync()
.ConfigureAwait(false);
}
}

[Fact(DisplayName = "Distributed lock works correct in distributed enviroment")]
public async Task Test()
{
var distributedLock = _serviceProvider.GetRequiredService<IDistributedLock>();

const string lockKeyA = "A";
const string lockKeyB = "B";
const string lockKeyC = "C";

for (var i = 0; i < 2; i++)
{
var a1 = distributedLock.AcquireAsync(lockKeyA);
var b1 = distributedLock.AcquireAsync(lockKeyB);
var c1 = distributedLock.AcquireAsync(lockKeyC);

await Task.WhenAll(a1, b1, c1);

var a2 = distributedLock.AcquireAsync(lockKeyA);
var b2 = distributedLock.AcquireAsync(lockKeyB);
var c2 = distributedLock.AcquireAsync(lockKeyC);

Assert.True(a1.IsCompleted, Message(nameof(a1)));
Assert.True(b1.IsCompleted, Message(nameof(b1)));
Assert.True(c1.IsCompleted, Message(nameof(c1)));

// Second tasks should wait when locks will be released
Assert.False(a2.IsCompleted, Message(nameof(a2), nameof(a1)));
Assert.False(b2.IsCompleted, Message(nameof(b2), nameof(b1)));
Assert.False(c2.IsCompleted, Message(nameof(c2), nameof(c1)));

// When first tasks release locks, second tasks can continue
await a1.Result.DisposeAsync();
await b1.Result.DisposeAsync();
await c1.Result.DisposeAsync();

await Task.WhenAll(a2, b2, c2);

Assert.True(a2.IsCompleted, Message(nameof(a2)));
Assert.True(b2.IsCompleted, Message(nameof(b2)));
Assert.True(c2.IsCompleted, Message(nameof(c2)));

await a2.Result.DisposeAsync();
await b2.Result.DisposeAsync();
await c2.Result.DisposeAsync();
}
}

public Task DisposeAsync() => Task.CompletedTask;

private string Message(string x) => $"Task {x} should be completed.";

private string Message(string x, string y) => $"Task {x} did not wait for task {y} to release the distributed lock.";
}
}
2 changes: 2 additions & 0 deletions tests/Locks.Tests/Locks.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Testcontainers.MsSql" Version="3.9.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand All @@ -24,6 +25,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\source\Locks.SqlServer\Locks.SqlServer.csproj" />
<ProjectReference Include="..\..\source\Locks\Locks.csproj" />
</ItemGroup>

Expand Down
10 changes: 10 additions & 0 deletions tests/Locks.Tests/Seed/DisabledMemoryLock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Locks.Tests.Seed
{
internal sealed class DisabledMemoryLock : IMemoryLock
{
public Task<IMemoryLockInstance> AcquireAsync(string key, CancellationToken cancellationToken = default)
{
return Task.FromResult<IMemoryLockInstance>(new DisabledMemoryLockInstance());
}
}
}
7 changes: 7 additions & 0 deletions tests/Locks.Tests/Seed/DisabledMemoryLockInstance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Locks.Tests.Seed
{
internal sealed class DisabledMemoryLockInstance : IMemoryLockInstance
{
public void Dispose() { }
}
}
Loading