< Summary

Information
Class: Services.ApiServices._1CApi.OData.OneCNomenclatureCreationLock
Assembly: Services
File(s): /home/runner/work/Studio2Prod/Studio2Prod/AppRepository/ApiServices/1CApi/OData/OneCNomenclatureCreationLock.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 42
Coverable lines: 42
Total lines: 97
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 6
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
AcquireAsync()0%2040%
BuildLockName(...)100%210%
AddParameter(...)100%210%
.ctor(...)100%210%
DisposeAsync()0%620%

File(s)

/home/runner/work/Studio2Prod/Studio2Prod/AppRepository/ApiServices/1CApi/OData/OneCNomenclatureCreationLock.cs

#LineLine coverage
 1using System.Data;
 2using System.Security.Cryptography;
 3using System.Text;
 4using Microsoft.EntityFrameworkCore;
 5using Microsoft.Extensions.DependencyInjection;
 6using OzonRepositories.Context;
 7
 8namespace Services.ApiServices._1CApi.OData;
 9
 10/// <summary>Сериализует создание одной номенклатуры между экземплярами приложения.</summary>
 11public interface IOneCNomenclatureCreationLock
 12{
 13    Task<IAsyncDisposable> AcquireAsync(string article, string producerName, CancellationToken cancellationToken = defau
 14}
 15
 16public sealed class OneCNomenclatureCreationLock : IOneCNomenclatureCreationLock
 17{
 18    private const int TimeoutSeconds = 30;
 19    private readonly IServiceScopeFactory _scopeFactory;
 20
 021    public OneCNomenclatureCreationLock(IServiceScopeFactory scopeFactory)
 22    {
 023        _scopeFactory = scopeFactory;
 024    }
 25
 26    public async Task<IAsyncDisposable> AcquireAsync(string article, string producerName, CancellationToken cancellation
 27    {
 028        var scope = _scopeFactory.CreateAsyncScope();
 29        try
 30        {
 031            var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
 032            var connection = db.Database.GetDbConnection();
 033            await connection.OpenAsync(cancellationToken);
 34
 035            var lockName = BuildLockName(article, producerName);
 036            await using var command = connection.CreateCommand();
 037            command.CommandText = "SELECT GET_LOCK(@lockName, @timeoutSeconds)";
 038            AddParameter(command, "@lockName", lockName);
 039            AddParameter(command, "@timeoutSeconds", TimeoutSeconds);
 040            var acquired = Convert.ToInt32(await command.ExecuteScalarAsync(cancellationToken)) == 1;
 041            if (!acquired)
 042                throw new TimeoutException($"Не удалось получить межпроцессную блокировку создания номенклатуры '{articl
 43
 044            return new Releaser(scope, connection, lockName);
 045        }
 046        catch
 47        {
 048            await scope.DisposeAsync();
 049            throw;
 50        }
 051    }
 52
 53    private static string BuildLockName(string article, string producerName)
 54    {
 055        var source = $"{article}|{producerName}";
 056        var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source)));
 057        return $"onec-nomenclature:{hash}";
 58    }
 59
 60    private static void AddParameter(IDbCommand command, string name, object value)
 61    {
 062        var parameter = command.CreateParameter();
 063        parameter.ParameterName = name;
 064        parameter.Value = value;
 065        command.Parameters.Add(parameter);
 066    }
 67
 68    private sealed class Releaser : IAsyncDisposable
 69    {
 70        private readonly AsyncServiceScope _scope;
 71        private readonly System.Data.Common.DbConnection _connection;
 72        private readonly string _lockName;
 73
 074        public Releaser(AsyncServiceScope scope, System.Data.Common.DbConnection connection, string lockName)
 75        {
 076            _scope = scope;
 077            _connection = connection;
 078            _lockName = lockName;
 079        }
 80
 81        public async ValueTask DisposeAsync()
 82        {
 83            try
 84            {
 085                await using var command = _connection.CreateCommand();
 086                command.CommandText = "SELECT RELEASE_LOCK(@lockName)";
 087                AddParameter(command, "@lockName", _lockName);
 088                await command.ExecuteScalarAsync();
 089            }
 90            finally
 91            {
 092                await _connection.CloseAsync();
 093                await _scope.DisposeAsync();
 94            }
 095        }
 96    }
 97}