diff --git a/Persistence.API/Controllers/SetpointController.cs b/Persistence.API/Controllers/SetpointController.cs index c374d9e..0ff6878 100644 --- a/Persistence.API/Controllers/SetpointController.cs +++ b/Persistence.API/Controllers/SetpointController.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Persistence.Models; using Persistence.Repositories; diff --git a/Persistence.Client/Clients/Base/BaseClient.cs b/Persistence.Client/Clients/Base/BaseClient.cs new file mode 100644 index 0000000..2332cbd --- /dev/null +++ b/Persistence.Client/Clients/Base/BaseClient.cs @@ -0,0 +1,62 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Helpers; +using Refit; + +namespace Persistence.Client.Clients.Base; +public abstract class BaseClient +{ + private readonly ILogger logger; + + public BaseClient(ILogger logger) + { + this.logger = logger; + } + + public async Task ExecuteGetResponse(Func>> getMethod, CancellationToken token) + { + var response = await getMethod.Invoke().WaitAsync(token); + + if (response.IsSuccessful) + { + return response.Content; + } + + var exception = response.GetPersistenceException(); + + logger.LogError(exception.Message); + + throw exception; + } + + public async Task ExecutePostResponse(Func> postMethod, CancellationToken token) + { + var response = await postMethod.Invoke().WaitAsync(token); + + if (response.IsSuccessful) + { + return; + } + + var exception = response.GetPersistenceException(); + + logger.LogError(exception.Message); + + throw exception; + } + + public async Task ExecutePostResponse(Func>> postMethod, CancellationToken token) + { + var response = await postMethod.Invoke().WaitAsync(token); + + if (response.IsSuccessful) + { + return response.Content; + } + + var exception = response.GetPersistenceException(); + + logger.LogError(exception.Message); + + throw exception; + } +} diff --git a/Persistence.Client/Clients/ChangeLogClient.cs b/Persistence.Client/Clients/ChangeLogClient.cs new file mode 100644 index 0000000..00aee71 --- /dev/null +++ b/Persistence.Client/Clients/ChangeLogClient.cs @@ -0,0 +1,102 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Clients.Base; +using Persistence.Client.Clients.Interfaces; +using Persistence.Models; +using Persistence.Models.Requests; + +namespace Persistence.Client.Clients; +public class ChangeLogClient : BaseClient, IChangeLogClient +{ + private readonly Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient; + + public ChangeLogClient(Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient, ILogger logger) : base(logger) + { + this.refitChangeLogClient = refitChangeLogClient; + } + + public async Task ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token); + + return result; + } + + public async Task> GetByDate(Guid idDiscriminator, DateTimeOffset moment, + SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token); + + return result; + } + + public async Task> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token); + + return result; + } + + public async Task Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.Add(idDiscriminator, dto, token), token); + + return result; + } + + public async Task AddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.AddRange(idDiscriminator, dtos, token), token); + + return result; + } + + public async Task Update(DataWithWellDepthAndSectionDto dto, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.Update(dto, token), token); + + return result; + } + + public async Task UpdateRange(IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.UpdateRange(dtos, token), token); + + return result; + } + + public async Task Delete(Guid id, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.Delete(id, token), token); + + return result; + } + + public async Task DeleteRange(IEnumerable ids, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.DeleteRange(ids, token), token); + + return result; + } + + public async Task GetDatesRange(Guid idDiscriminator, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token); + + return result; + } + + public void Dispose() + { + refitChangeLogClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/IChangeLogClient.cs b/Persistence.Client/Clients/IChangeLogClient.cs deleted file mode 100644 index 06bbc4d..0000000 --- a/Persistence.Client/Clients/IChangeLogClient.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Persistence.Models; -using Persistence.Models.Requests; -using Refit; - -namespace Persistence.Client.Clients; - -/// -/// Интерфейс для тестирования API, предназначенного для работы с записями ChangeLod -/// -public interface IChangeLogClient -{ - private const string BaseRoute = "/api/ChangeLog"; - - /// - /// Импорт с заменой: удаление старых строк и добавление новых - /// - /// - /// - /// - [Post($"{BaseRoute}/replace/{{idDiscriminator}}")] - Task> ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos); - - /// - /// Получение актуальных данных на определенную дату (с пагинацией) - /// - /// - /// - /// параметры запроса фильтрации - /// параметры запроса пагинации - /// - [Get($"{BaseRoute}/moment/{{idDiscriminator}}")] - Task>> GetByDate( - Guid idDiscriminator, - DateTimeOffset moment, - [Query] SectionPartRequest filterRequest, - [Query] PaginationRequest paginationRequest); - - /// - /// Получение исторических данных за определенный период времени - /// - /// - /// - /// - /// - [Get($"{BaseRoute}/history/{{idDiscriminator}}")] - Task>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd); - - /// - /// Добавить одну запись - /// - /// - /// - /// - [Post($"{BaseRoute}/{{idDiscriminator}}")] - Task> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto); - - /// - /// Добавить несколько записей - /// - /// - /// - /// - [Post($"{BaseRoute}/range/{{idDiscriminator}}")] - Task> AddRange(Guid idDiscriminator, IEnumerable dtos); - - /// - /// Обновить одну запись - /// - /// - /// - [Put($"{BaseRoute}")] - Task> Update(DataWithWellDepthAndSectionDto dto); - - /// - /// Обновить несколько записей - /// - /// - /// - [Put($"{BaseRoute}/range")] - Task> UpdateRange(IEnumerable dtos); - - /// - /// Удалить одну запись - /// - /// - /// - [Delete($"{BaseRoute}")] - Task> Delete(Guid id); - - /// - /// Удалить несколько записей - /// - /// - /// - [Delete($"{BaseRoute}/range")] - Task> DeleteRange([Body] IEnumerable ids); - - /// - /// Получение списка дат, в которые происходили изменения (день, месяц, год, без времени) - /// - /// - /// - [Get($"{BaseRoute}/datesRange/{{idDiscriminator}}")] - Task> GetDatesRange(Guid idDiscriminator); - -} diff --git a/Persistence.Client/Clients/ITimeSeriesClient.cs b/Persistence.Client/Clients/ITimeSeriesClient.cs deleted file mode 100644 index c2cbf91..0000000 --- a/Persistence.Client/Clients/ITimeSeriesClient.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Persistence.Models; -using Refit; - -namespace Persistence.Client.Clients; -public interface ITimeSeriesClient - where TDto : class, new() -{ - private const string BaseRoute = "/api/dataSaub"; - - [Post($"{BaseRoute}")] - Task> AddRange(IEnumerable dtos); - - [Get($"{BaseRoute}")] - Task>> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd); - - [Get($"{BaseRoute}/resampled")] - Task>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024); - - [Get($"{BaseRoute}/datesRange")] - Task> GetDatesRange(); -} diff --git a/Persistence.Client/Clients/ITimestampedSetClient.cs b/Persistence.Client/Clients/ITimestampedSetClient.cs deleted file mode 100644 index bbff603..0000000 --- a/Persistence.Client/Clients/ITimestampedSetClient.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Persistence.Models; -using Refit; - -namespace Persistence.Client.Clients; - -/// -/// Клиент для работы с репозиторием для хранения разных наборов данных рядов. -/// idDiscriminator - идентифицирует конкретный набор данных, прим.: циклы измерения АСИБР, или отчет о DrillTest. -/// idDiscriminator формируют клиенты и только им известно что они обозначают. -/// Так как данные приходят редко, то их прореживания для построения графиков не предусмотрено. -/// -public interface ITimestampedSetClient -{ - private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}"; - - /// - /// Добавление новых данных - /// - /// Дискриминатор (идентификатор) набора - /// - /// - [Post(baseUrl)] - Task> AddRange(Guid idDiscriminator, IEnumerable sets); - - /// - /// Получение данных с фильтрацией. Значение фильтра null - отключен - /// - /// Дискриминатор (идентификатор) набора - /// Фильтр позднее даты - /// Фильтр свойств набора. Можно запросить только некоторые свойства из набора - /// - /// - /// - [Get(baseUrl)] - Task>> Get(Guid idDiscriminator, [Query] DateTimeOffset? geTimestamp, [Query] IEnumerable? columnNames, int skip, int take); - - /// - /// Получить последние данные - /// - /// Дискриминатор (идентификатор) набора - /// Фильтр свойств набора. Можно запросить только некоторые свойства из набора - /// - /// - [Get($"{baseUrl}/last")] - Task>> GetLast(Guid idDiscriminator, [Query] IEnumerable? columnNames, int take); - - /// - /// Количество записей по указанному набору в БД. Для пагинации. - /// - /// Дискриминатор (идентификатор) набора - /// - [Get($"{baseUrl}/count")] - Task> Count(Guid idDiscriminator); - - /// - /// Диапазон дат за которые есть данные - /// - /// Дискриминатор (идентификатор) набора - /// - [Get($"{baseUrl}/datesRange")] - Task> GetDatesRange(Guid idDiscriminator); -} diff --git a/Persistence.Client/Clients/Interfaces/IChangeLogClient.cs b/Persistence.Client/Clients/Interfaces/IChangeLogClient.cs new file mode 100644 index 0000000..0d24585 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/IChangeLogClient.cs @@ -0,0 +1,98 @@ +using Persistence.Models; +using Persistence.Models.Requests; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с записями ChangeLog +/// +public interface IChangeLogClient : IDisposable +{ + /// + /// Добавить одну запись + /// + /// + /// + /// + /// + Task Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token); + + /// + /// Добавить несколько записей + /// + /// + /// + /// + /// + Task AddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + /// + /// Импорт с заменой: удаление старых строк и добавление новых + /// + /// + /// + /// + /// + Task ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + /// + /// Удалить одну запись + /// + /// + /// + /// + Task Delete(Guid id, CancellationToken token); + + /// + /// Удалить несколько записей + /// + /// + /// + /// + Task DeleteRange(IEnumerable ids, CancellationToken token); + + /// + /// Получение актуальных данных на определенную дату (с пагинацией) + /// + /// + /// + /// + /// + /// + /// + Task> GetByDate(Guid idDiscriminator, DateTimeOffset moment, SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token); + + /// + /// Получение исторических данных за определенный период времени + /// + /// + /// + /// + /// + /// + Task> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); + + /// + /// Получение списка дат, в которые происходили изменения (день, месяц, год, без времени) + /// + /// + /// + /// + Task GetDatesRange(Guid idDiscriminator, CancellationToken token); + + /// + /// Обновить одну запись + /// + /// + /// + /// + Task Update(DataWithWellDepthAndSectionDto dto, CancellationToken token); + + /// + /// Обновить несколько записей + /// + /// + /// + /// + Task UpdateRange(IEnumerable dtos, CancellationToken token); +} \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/ISetpointClient.cs b/Persistence.Client/Clients/Interfaces/ISetpointClient.cs new file mode 100644 index 0000000..295ab87 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/ISetpointClient.cs @@ -0,0 +1,59 @@ +using Persistence.Models; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с уставками +/// +public interface ISetpointClient : IDisposable +{ + /// + /// Добавить уставку + /// + /// + /// + /// + /// + Task Add(Guid setpointKey, object newValue, CancellationToken token); + + /// + /// Получить актуальные значения уставок + /// + /// + /// + /// + Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token); + + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + Task GetDatesRangeAsync(CancellationToken token); + + /// + /// Получить значения уставок за определенный момент времени + /// + /// + /// + /// + /// + Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token); + + /// + /// Получить историю изменений значений уставок + /// + /// + /// + /// + Task>> GetLog(IEnumerable setpointKeys, CancellationToken token); + + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); +} \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs new file mode 100644 index 0000000..bbf635c --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs @@ -0,0 +1,58 @@ +using Persistence.Models; +using Persistence.Models.Requests; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с технологическими сообщениями +/// +public interface ITechMessagesClient : IDisposable +{ + /// + /// Добавить новые технологические сообщения + /// + /// + /// + /// + Task AddRange(IEnumerable dtos, CancellationToken token); + + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + Task GetDatesRangeAsync(CancellationToken token); + + /// + /// Получить список технологических сообщений в виде страницы + /// + /// + /// + /// + Task> GetPage(PaginationRequest request, CancellationToken token); + + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); + + /// + /// Получить статистику по системам + /// + /// + /// + /// + /// + Task> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token); + + /// + /// Получить список всех систем + /// + /// + /// + Task> GetSystems(CancellationToken token); +} \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs b/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs new file mode 100644 index 0000000..316c0c9 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs @@ -0,0 +1,44 @@ +using Persistence.Models; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с временными данными +/// +/// +public interface ITimeSeriesClient : IDisposable where TDto : class, new() +{ + /// + /// Добавление записей + /// + /// + /// + /// + Task AddRange(IEnumerable dtos, CancellationToken token); + + /// + /// Получить список объектов, удовлетворяющий диапазону дат + /// + /// + /// + /// + /// + Task> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); + + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + Task GetDatesRange(CancellationToken token); + + /// + /// Получить список объектов с прореживанием, удовлетворяющий диапазону дат + /// + /// + /// + /// + /// + /// + Task> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default); +} \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs b/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs new file mode 100644 index 0000000..21fd222 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs @@ -0,0 +1,59 @@ +using Persistence.Models; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с репозиторием для хранения разных наборов данных рядов. +/// idDiscriminator - идентифицирует конкретный набор данных, прим.: циклы измерения АСИБР, или отчет о DrillTest. +/// idDiscriminator формируют клиенты и только им известно что они обозначают. +/// Так как данные приходят редко, то их прореживания для построения графиков не предусмотрено. +/// +public interface ITimestampedSetClient : IDisposable +{ + /// + /// Записать новые данные + /// + /// + /// + /// + /// + Task AddRange(Guid idDiscriminator, IEnumerable sets, CancellationToken token); + + /// + /// Количество записей по указанному набору в БД. Для пагинации + /// + /// + /// + /// + Task Count(Guid idDiscriminator, CancellationToken token); + + /// + /// Получение данных с фильтрацией. Значение фильтра null - отключен + /// + /// + /// + /// + /// + /// + /// + /// + Task> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable? columnNames, int skip, int take, CancellationToken token); + + /// + /// Диапазон дат за которые есть данные + /// + /// + /// + /// + Task GetDatesRange(Guid idDiscriminator, CancellationToken token); + + /// + /// + /// + /// + /// + /// + /// + /// + Task> GetLast(Guid idDiscriminator, IEnumerable? columnNames, int take, CancellationToken token); +} \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/IWitsDataClient.cs b/Persistence.Client/Clients/Interfaces/IWitsDataClient.cs new file mode 100644 index 0000000..e0fee60 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/IWitsDataClient.cs @@ -0,0 +1,47 @@ +using Persistence.Models; +using Refit; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с параметрами Wits +/// +public interface IWitsDataClient : IDisposable +{ + /// + /// Получить набор параметров (Wits) для построения графика + /// + /// + /// + /// + /// + /// + /// + Task> GetValuesForGraph(Guid discriminatorId, [Query] DateTimeOffset dateFrom, [Query] DateTimeOffset dateTo, [Query] int approxPointsCount, CancellationToken token); + + /// + /// Сохранить набор параметров (Wits) + /// + /// + /// + /// + Task AddRange(IEnumerable dtos, CancellationToken token); + + /// + /// Получить порцию записей, начиная с заданной даты + /// + /// + /// + /// + /// + /// + Task> GetPart(Guid discriminatorId, [Query] DateTimeOffset dateBegin, [Query] int take = 24 * 60 * 60, CancellationToken token = default); + + /// + /// Получить диапазон дат, для которых есть данные в репозитории + /// + /// + /// + /// + Task GetDatesRangeAsync(Guid discriminatorId, CancellationToken token); +} diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitChangeLogClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitChangeLogClient.cs new file mode 100644 index 0000000..c7a7bc1 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitChangeLogClient.cs @@ -0,0 +1,46 @@ +using Persistence.Models; +using Persistence.Models.Requests; +using Refit; + +namespace Persistence.Client.Clients.Interfaces.Refit; + +public interface IRefitChangeLogClient : IDisposable +{ + private const string BaseRoute = "/api/ChangeLog"; + + [Post($"{BaseRoute}/replace/{{idDiscriminator}}")] + Task> ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + [Get($"{BaseRoute}/moment/{{idDiscriminator}}")] + Task>> GetByDate( + Guid idDiscriminator, + DateTimeOffset moment, + [Query] SectionPartRequest filterRequest, + [Query] PaginationRequest paginationRequest, + CancellationToken token); + + [Get($"{BaseRoute}/history/{{idDiscriminator}}")] + Task>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); + + [Post($"{BaseRoute}/{{idDiscriminator}}")] + Task> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token); + + [Post($"{BaseRoute}/range/{{idDiscriminator}}")] + Task> AddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + [Put($"{BaseRoute}")] + Task> Update(DataWithWellDepthAndSectionDto dto, CancellationToken token); + + [Put($"{BaseRoute}/range")] + Task> UpdateRange(IEnumerable dtos, CancellationToken token); + + [Delete($"{BaseRoute}")] + Task> Delete(Guid id, CancellationToken token); + + [Delete($"{BaseRoute}/range")] + Task> DeleteRange([Body] IEnumerable ids, CancellationToken token); + + [Get($"{BaseRoute}/datesRange/{{idDiscriminator}}")] + Task> GetDatesRange(Guid idDiscriminator, CancellationToken token); + +} diff --git a/Persistence.Client/Clients/ISetpointClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs similarity index 67% rename from Persistence.Client/Clients/ISetpointClient.cs rename to Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs index 47c4352..69a2719 100644 --- a/Persistence.Client/Clients/ISetpointClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs @@ -1,23 +1,20 @@ using Persistence.Models; using Refit; -namespace Persistence.Client.Clients; +namespace Persistence.Client.Clients.Interfaces.Refit; -/// -/// Интерфейс клиента для работы с уставками -/// -public interface ISetpointClient +public interface IRefitSetpointClient : IDisposable { private const string BaseRoute = "/api/setpoint"; [Get($"{BaseRoute}/current")] - Task>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable setpointKeys); + Task>> GetCurrent([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, CancellationToken token); [Get($"{BaseRoute}/history")] - Task>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, [Query] DateTimeOffset historyMoment); + Task>> GetHistory([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, [Query] DateTimeOffset historyMoment, CancellationToken token); [Get($"{BaseRoute}/log")] - Task>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable setpointKeys); + Task>>> GetLog([Query(CollectionFormat.Multi)] IEnumerable setpointKeys, CancellationToken token); [Get($"{BaseRoute}/range")] Task> GetDatesRangeAsync(CancellationToken token); @@ -26,5 +23,5 @@ public interface ISetpointClient Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); [Post($"{BaseRoute}/")] - Task Add(Guid setpointKey, object newValue); + Task Add(Guid setpointKey, object newValue, CancellationToken token); } diff --git a/Persistence.Client/Clients/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs similarity index 82% rename from Persistence.Client/Clients/ITechMessagesClient.cs rename to Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs index 1fde2a9..64cb49e 100644 --- a/Persistence.Client/Clients/ITechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs @@ -2,12 +2,9 @@ using Persistence.Models.Requests; using Refit; -namespace Persistence.Client.Clients +namespace Persistence.Client.Clients.Interfaces.Refit { - /// - /// Интерфейс клиента для хранения технологических сообщений - /// - public interface ITechMessagesClient + public interface IRefitTechMessagesClient : IDisposable { private const string BaseRoute = "/api/techMessages"; diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs new file mode 100644 index 0000000..79135e1 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs @@ -0,0 +1,21 @@ +using Persistence.Models; +using Refit; + +namespace Persistence.Client.Clients.Interfaces.Refit; +public interface IRefitTimeSeriesClient : IDisposable + where TDto : class, new() +{ + private const string BaseRoute = "/api/dataSaub"; + + [Post($"{BaseRoute}")] + Task> AddRange(IEnumerable dtos, CancellationToken token); + + [Get($"{BaseRoute}")] + Task>> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); + + [Get($"{BaseRoute}/resampled")] + Task>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default); + + [Get($"{BaseRoute}/datesRange")] + Task> GetDatesRange(CancellationToken token); +} diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs new file mode 100644 index 0000000..8caeb61 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs @@ -0,0 +1,24 @@ +using Persistence.Models; +using Refit; + +namespace Persistence.Client.Clients.Interfaces.Refit; + +public interface IRefitTimestampedSetClient : IDisposable +{ + private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}"; + + [Post(baseUrl)] + Task> AddRange(Guid idDiscriminator, IEnumerable sets, CancellationToken token); + + [Get(baseUrl)] + Task>> Get(Guid idDiscriminator, [Query] DateTimeOffset? geTimestamp, [Query] IEnumerable? columnNames, int skip, int take, CancellationToken token); + + [Get($"{baseUrl}/last")] + Task>> GetLast(Guid idDiscriminator, [Query] IEnumerable? columnNames, int take, CancellationToken token); + + [Get($"{baseUrl}/count")] + Task> Count(Guid idDiscriminator, CancellationToken token); + + [Get($"{baseUrl}/datesRange")] + Task> GetDatesRange(Guid idDiscriminator, CancellationToken token); +} diff --git a/Persistence.Client/Clients/IWitsDataClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitWitsDataClient.cs similarity index 83% rename from Persistence.Client/Clients/IWitsDataClient.cs rename to Persistence.Client/Clients/Interfaces/Refit/IRefitWitsDataClient.cs index 95a34c3..c22f919 100644 --- a/Persistence.Client/Clients/IWitsDataClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitWitsDataClient.cs @@ -1,8 +1,9 @@ -using Persistence.Models; +using Microsoft.AspNetCore.Mvc; +using Persistence.Models; using Refit; -namespace Persistence.Client.Clients; -public interface IWitsDataClient +namespace Persistence.Client.Clients.Interfaces.Refit; +public interface IRefitWitsDataClient : IDisposable { private const string BaseRoute = "/api/witsData"; diff --git a/Persistence.Client/Clients/SetpointClient.cs b/Persistence.Client/Clients/SetpointClient.cs new file mode 100644 index 0000000..b1df4b4 --- /dev/null +++ b/Persistence.Client/Clients/SetpointClient.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Clients.Base; +using Persistence.Client.Clients.Interfaces; +using Persistence.Client.Clients.Interfaces.Refit; +using Persistence.Models; + +namespace Persistence.Client.Clients; + +public class SetpointClient : BaseClient, ISetpointClient +{ + private readonly IRefitSetpointClient refitSetpointClient; + + public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger logger) : base(logger) + { + this.refitSetpointClient = refitSetpointClient; + } + + public async Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token); + + return result; + } + + public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token); + + return result; + } + + public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) + { + var result = await ExecuteGetResponse>>( + async () => await refitSetpointClient.GetLog(setpointKeys, token), token); + + return result; + } + + public async Task GetDatesRangeAsync(CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitSetpointClient.GetDatesRangeAsync(token), token); + + return result; + } + + public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitSetpointClient.GetPart(dateBegin, take, token), token); + + return result; + } + + public async Task Add(Guid setpointKey, object newValue, CancellationToken token) + { + await ExecutePostResponse( + async () => await refitSetpointClient.Add(setpointKey, newValue, token), token); + } + + public void Dispose() + { + refitSetpointClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/TechMessagesClient.cs b/Persistence.Client/Clients/TechMessagesClient.cs new file mode 100644 index 0000000..c1000b1 --- /dev/null +++ b/Persistence.Client/Clients/TechMessagesClient.cs @@ -0,0 +1,71 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Clients.Base; +using Persistence.Client.Clients.Interfaces; +using Persistence.Client.Clients.Interfaces.Refit; +using Persistence.Models; +using Persistence.Models.Requests; + +namespace Persistence.Client.Clients; + +public class TechMessagesClient : BaseClient, ITechMessagesClient +{ + private readonly IRefitTechMessagesClient refitTechMessagesClient; + + public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger logger) : base(logger) + { + this.refitTechMessagesClient = refitTechMessagesClient; + } + + public async Task> GetPage(PaginationRequest request, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitTechMessagesClient.GetPage(request, token), token); + + return result; + } + + public async Task AddRange(IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitTechMessagesClient.AddRange(dtos, token), token); + + return result; + } + + public async Task> GetSystems(CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitTechMessagesClient.GetSystems(token), token); + + return result; + } + + public async Task GetDatesRangeAsync(CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token); + + return result; + } + + public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token); + + return result; + } + + public async Task> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitTechMessagesClient.GetStatistics(autoDrillingSystem, categoryId, token), token); + + return result; + } + + public void Dispose() + { + refitTechMessagesClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/TimeSeriesClient.cs b/Persistence.Client/Clients/TimeSeriesClient.cs new file mode 100644 index 0000000..a3fba7d --- /dev/null +++ b/Persistence.Client/Clients/TimeSeriesClient.cs @@ -0,0 +1,53 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Clients.Base; +using Persistence.Client.Clients.Interfaces; +using Persistence.Client.Clients.Interfaces.Refit; +using Persistence.Models; + +namespace Persistence.Client.Clients; +public class TimeSeriesClient : BaseClient, ITimeSeriesClient where TDto : class, new() +{ + private readonly IRefitTimeSeriesClient timeSeriesClient; + + public TimeSeriesClient(IRefitTimeSeriesClient refitTechMessagesClient, ILogger> logger) : base(logger) + { + this.timeSeriesClient = refitTechMessagesClient; + } + + public async Task AddRange(IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await timeSeriesClient.AddRange(dtos, token), token); + + return result; + } + + public async Task> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token); + + return result; + } + + public async Task> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default) + { + var result = await ExecuteGetResponse>( + async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token); + + return result; + } + + public async Task GetDatesRange(CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await timeSeriesClient.GetDatesRange(token), token); + + return result; + } + + public void Dispose() + { + timeSeriesClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/TimestampedSetClient.cs b/Persistence.Client/Clients/TimestampedSetClient.cs new file mode 100644 index 0000000..4d40d8b --- /dev/null +++ b/Persistence.Client/Clients/TimestampedSetClient.cs @@ -0,0 +1,61 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Clients.Base; +using Persistence.Client.Clients.Interfaces; +using Persistence.Client.Clients.Interfaces.Refit; +using Persistence.Models; + +namespace Persistence.Client.Clients; +public class TimestampedSetClient : BaseClient, ITimestampedSetClient +{ + private readonly IRefitTimestampedSetClient refitTimestampedSetClient; + + public TimestampedSetClient(IRefitTimestampedSetClient refitTimestampedSetClient, ILogger logger) : base(logger) + { + this.refitTimestampedSetClient = refitTimestampedSetClient; + } + + public async Task AddRange(Guid idDiscriminator, IEnumerable sets, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitTimestampedSetClient.AddRange(idDiscriminator, sets, token), token); + + return result; + } + + public async Task> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable? columnNames, int skip, int take, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token); + + return result; + } + + public async Task> GetLast(Guid idDiscriminator, IEnumerable? columnNames, int take, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token); + + return result; + } + + public async Task Count(Guid idDiscriminator, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitTimestampedSetClient.Count(idDiscriminator, token), token); + + return result; + } + + public async Task GetDatesRange(Guid idDiscriminator, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitTimestampedSetClient.GetDatesRange(idDiscriminator, token), token); + + return result; + } + + public void Dispose() + { + refitTimestampedSetClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/WitsDataClient.cs b/Persistence.Client/Clients/WitsDataClient.cs new file mode 100644 index 0000000..ad58be1 --- /dev/null +++ b/Persistence.Client/Clients/WitsDataClient.cs @@ -0,0 +1,53 @@ +using Microsoft.Extensions.Logging; +using Persistence.Client.Clients.Base; +using Persistence.Client.Clients.Interfaces; +using Persistence.Client.Clients.Interfaces.Refit; +using Persistence.Models; + +namespace Persistence.Client.Clients; +public class WitsDataClient : BaseClient, IWitsDataClient +{ + private readonly IRefitWitsDataClient refitWitsDataClient; + + public WitsDataClient(IRefitWitsDataClient refitWitsDataClient, ILogger logger) : base(logger) + { + this.refitWitsDataClient = refitWitsDataClient; + } + + public async Task AddRange(IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitWitsDataClient.AddRange(dtos, token), token); + + return result; + } + + public async Task GetDatesRangeAsync(Guid discriminatorId, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token); + + return result; + } + + public async Task> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default) + { + var result = await ExecuteGetResponse>( + async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token); + + return result; + } + + public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token); + + return result; + } + + public void Dispose() + { + refitWitsDataClient.Dispose(); + } +} diff --git a/Persistence.Client/CustomExceptions/AcceptableException.cs b/Persistence.Client/CustomExceptions/AcceptableException.cs new file mode 100644 index 0000000..0bdea54 --- /dev/null +++ b/Persistence.Client/CustomExceptions/AcceptableException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Not Acceptable (406) +/// +public class AcceptableException : Exception +{ + public AcceptableException(string message) + : base(message) { } +} diff --git a/Persistence.Client/CustomExceptions/BadGatewayException.cs b/Persistence.Client/CustomExceptions/BadGatewayException.cs new file mode 100644 index 0000000..2730140 --- /dev/null +++ b/Persistence.Client/CustomExceptions/BadGatewayException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Bad gateway (502) +/// +public class BadGatewayException : Exception +{ + public BadGatewayException(string message) + : base(message) { } +} diff --git a/Persistence.Client/CustomExceptions/ForbiddenException.cs b/Persistence.Client/CustomExceptions/ForbiddenException.cs new file mode 100644 index 0000000..bfd9e7d --- /dev/null +++ b/Persistence.Client/CustomExceptions/ForbiddenException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Forbidden (403) +/// +public class ForbiddenException : Exception +{ + public ForbiddenException(string message) + : base(message) { } +} diff --git a/Persistence.Client/CustomExceptions/InternalServerException.cs b/Persistence.Client/CustomExceptions/InternalServerException.cs new file mode 100644 index 0000000..6e8265b --- /dev/null +++ b/Persistence.Client/CustomExceptions/InternalServerException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Internal Server Error (500) +/// +public class InternalServerException : Exception +{ + public InternalServerException(string message) + : base(message) { } +} diff --git a/Persistence.Client/CustomExceptions/LockedException.cs b/Persistence.Client/CustomExceptions/LockedException.cs new file mode 100644 index 0000000..c24dca4 --- /dev/null +++ b/Persistence.Client/CustomExceptions/LockedException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Locked (423) +/// +public class LockedException : Exception +{ + public LockedException(string message) + : base(message) { } +} diff --git a/Persistence.Client/CustomExceptions/ServiceUnavailableException.cs b/Persistence.Client/CustomExceptions/ServiceUnavailableException.cs new file mode 100644 index 0000000..3929d42 --- /dev/null +++ b/Persistence.Client/CustomExceptions/ServiceUnavailableException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Service Unavailable Error (503) +/// +public class ServiceUnavailableException : Exception +{ + public ServiceUnavailableException(string message) + : base(message) { } +} diff --git a/Persistence.Client/CustomExceptions/TooManyRequestsException.cs b/Persistence.Client/CustomExceptions/TooManyRequestsException.cs new file mode 100644 index 0000000..d28f642 --- /dev/null +++ b/Persistence.Client/CustomExceptions/TooManyRequestsException.cs @@ -0,0 +1,10 @@ +namespace Persistence.Client.CustomExceptions; + +/// +/// Too Many Requests (429) +/// +public class TooManyRequestsException : Exception +{ + public TooManyRequestsException(string message) + : base(message) { } +} diff --git a/Persistence.Client/Helpers/ApiTokenHelper.cs b/Persistence.Client/Helpers/ApiTokenHelper.cs index d21363f..a2f632e 100644 --- a/Persistence.Client/Helpers/ApiTokenHelper.cs +++ b/Persistence.Client/Helpers/ApiTokenHelper.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Persistence.Models.Configurations; using RestSharp; @@ -27,17 +27,23 @@ public static class ApiTokenHelper httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); } - private static string CreateDefaultJwtToken(this AuthUser authUser) - { - var nameIdetifier = Guid.NewGuid().ToString(); - var claims = new List() - { - new(ClaimTypes.NameIdentifier, nameIdetifier), - new("client_id", authUser.ClientId), - new("username", authUser.Username), - new("password", authUser.Password), - new("grant_type", authUser.GrantType) - }; + public static void Authorize(this HttpClient httpClient, string jwtToken) + { + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken); + } + + private static string CreateDefaultJwtToken(this AuthUser authUser) + { + var nameIdetifier = Guid.NewGuid().ToString(); + var claims = new List() + { + new(ClaimTypes.NameIdentifier, nameIdetifier), + new("client_id", authUser.ClientId), + new("username", authUser.Username), + new("password", authUser.Password), + new("grant_type", authUser.GrantType), + new(ClaimTypes.NameIdentifier.ToString(), Guid.NewGuid().ToString()) + }; var tokenDescriptor = new SecurityTokenDescriptor { diff --git a/Persistence.Client/Helpers/ExceptionsHelper.cs b/Persistence.Client/Helpers/ExceptionsHelper.cs new file mode 100644 index 0000000..0e3a31a --- /dev/null +++ b/Persistence.Client/Helpers/ExceptionsHelper.cs @@ -0,0 +1,35 @@ +using System.ComponentModel.DataAnnotations; +using Persistence.Client.CustomExceptions; +using Refit; + +namespace Persistence.Client.Helpers; +public static class ExceptionsHelper +{ + private static readonly Dictionary ExceptionsDictionary = new Dictionary() + { + { System.Net.HttpStatusCode.BadRequest, new ValidationException("Ошибка валидации, формата или маршрутизации запроса") }, + { System.Net.HttpStatusCode.Unauthorized, new UnauthorizedAccessException("Ошибка авторизации, клиент должен аутентифицировать себя, чтобы получить запрошенный ответ") }, + { System.Net.HttpStatusCode.Forbidden, new ForbiddenException("Клиент известен серверу, но он неавторизован") }, + { System.Net.HttpStatusCode.NotFound, new EntryPointNotFoundException("Сервер не может найти запрошенный ресурс") }, + { System.Net.HttpStatusCode.MethodNotAllowed, new MethodAccessException("Обращение запрещено") }, + { System.Net.HttpStatusCode.NotAcceptable, new AcceptableException("После выполнения согласования контента не найдено содержимого, соответствующего заданным критериям") }, + { System.Net.HttpStatusCode.RequestTimeout, new TimeoutException("Время ожидания истекло") }, + { System.Net.HttpStatusCode.Locked, new LockedException("Запрашиваемый ресурс заблокирован") }, + { System.Net.HttpStatusCode.TooManyRequests, new TooManyRequestsException("Пользователь отправил слишком много запросов в определённый промежуток времени") }, + { System.Net.HttpStatusCode.InternalServerError, new InternalServerException("На сервере произошла ошибка, в результате которой он не может успешно обработать запрос") }, + { System.Net.HttpStatusCode.NotImplemented, new NotImplementedException("Метод запроса не поддерживается сервером") }, + { System.Net.HttpStatusCode.BadGateway, new BadGatewayException("В процессе обработки запроса полуен недопустимый ответ от целевого сервера") }, + { System.Net.HttpStatusCode.ServiceUnavailable, new ServiceUnavailableException("В процессе обработки запроса полуен недопустимый ответ от целевого сервера") }, + { System.Net.HttpStatusCode.GatewayTimeout, new TimeoutException("Время ожидания целевого сервера истекло") } + }; + + public static Exception GetPersistenceException(this IApiResponse response) + { + ExceptionsDictionary + .TryGetValue(response.StatusCode, out var exception); + + var result = exception ?? new Exception("Неопознанная ошибка"); + + return result; + } +} diff --git a/Persistence.Client/Persistence.Client.csproj b/Persistence.Client/Persistence.Client.csproj index 3f61a17..7d81fc3 100644 --- a/Persistence.Client/Persistence.Client.csproj +++ b/Persistence.Client/Persistence.Client.csproj @@ -1,9 +1,41 @@ - + net8.0 enable enable + + + True + + Persistence.Client + + 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + + 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + + Persistence.Client + + + Digital Drilling + + Digital Drilling + + Пакет для получения клиентов для работы с Persistence сервисом + + + https://git.ddrilling.ru/on.nemtina/persistence.git + + git + + true + + snupkg + + C:\Projects\Nuget + + + Readme.md @@ -11,6 +43,10 @@ 1.0.$([System.DateTime]::UtcNow.ToString(yyMM.ddHH)) + + + + @@ -22,4 +58,5 @@ + diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs index 697c901..31b6fd9 100644 --- a/Persistence.Client/PersistenceClientFactory.cs +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -1,32 +1,132 @@ -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; +using Persistence.Client.Clients.Interfaces; +using Persistence.Client.Clients; using Persistence.Client.Helpers; using Refit; +using Persistence.Factories; +using Persistence.Client.Clients.Interfaces.Refit; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; using System.Text.Json; namespace Persistence.Client { - /// - /// Фабрика клиентов для доступа к Persistence - сервису - /// - public class PersistenceClientFactory - { - private static readonly JsonSerializerOptions JsonSerializerOptions = new() - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - PropertyNameCaseInsensitive = true - }; - private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); - private readonly HttpClient httpClient; - public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IConfiguration configuration) - { - this.httpClient = httpClientFactory.CreateClient(); + /// + /// Фабрика клиентов для доступа к Persistence - сервису + /// + public class PersistenceClientFactory + { + private static readonly JsonSerializerOptions JsonSerializerOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true + }; + private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); + private readonly IServiceProvider provider; + private HttpClient httpClient; + public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IServiceProvider provider, IConfiguration configuration) + { + this.provider = provider; - httpClient.Authorize(configuration); - } + httpClient = httpClientFactory.CreateClient(); - public T GetClient() - { - return RestService.For(httpClient, RefitSettings); - } - } + httpClient.Authorize(configuration); + } + + public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IAuthTokenFactory authTokenFactory, IServiceProvider provider, IConfiguration configuration) + { + this.provider = provider; + + httpClient = httpClientFactory.CreateClient(); + + var token = authTokenFactory.GetToken(); + httpClient.Authorize(token); + } + + /// + /// Получить клиент для работы с уставками + /// + /// + public ISetpointClient GetSetpointClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new SetpointClient(restClient, logger); + + return client; + } + + /// + /// Получить клиент для работы с технологическими сообщениями + /// + /// + public ITechMessagesClient GetTechMessagesClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new TechMessagesClient(restClient, logger); + + return client; + } + + /// + /// Получить клиент для работы с временными данными + /// + /// + /// + public ITimeSeriesClient GetTimeSeriesClient() + where TDto : class, new() + { + var logger = provider.GetRequiredService>>(); + + var restClient = RestService.For>(httpClient, RefitSettings); + var client = new TimeSeriesClient(restClient, logger); + + return client; + } + + /// + /// Получить клиент для работы с данными с отметкой времени + /// + /// + public ITimestampedSetClient GetTimestampedSetClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new TimestampedSetClient(restClient, logger); + + return client; + } + + /// + /// Получить клиент для работы с записями ChangeLog + /// + /// + public IChangeLogClient GetChangeLogClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new ChangeLogClient(restClient, logger); + + return client; + } + + /// + /// Получить клиент для работы c параметрами Wits + /// + /// + public IWitsDataClient GetWitsDataClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new WitsDataClient(restClient, logger); + + return client; + } + } } diff --git a/Persistence.Client/Readme.md b/Persistence.Client/Readme.md new file mode 100644 index 0000000..e9f4024 --- /dev/null +++ b/Persistence.Client/Readme.md @@ -0,0 +1,47 @@ +# Persistence Client Nuget Readme +## Краткое описание Persistence сервиса +Persistence сервис отвечает за работу с хранимыми данными +в рамках совокупности различных систем. + +## Описание пакета +Данный пакет предоставляет возможность взаимодействия с +Persistence сервисом посредством обращения к конкретному +клиенту, ответсвенному за работу с одной из областей сервиса. + +## Список предоставляемых клиентов +- `ISetpointClient` - Клиент для работы с уставками +- `ITechMessagesClient` - Клиент для работы с технологическими сообщениями +- `ITimeSeriesClient` - Клиент для работы с временными данными +- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени +- `IChangeLogClient` - Клиент для работы с записями ChangeLog +- `IWitsDataClient` - Клиент для работы с параметрами Wits + +## Использование +Для получения того или иного Persistence - клиента нужно +обращаться к фабрике Persistence клиентов - `PersistenceClientFactory`. Для этого требуется: +1. Добавить в проект фабрику HTTP - клиентов `IHttpClientFactory`. +
Она должна предоставлять HTTP - клиента через метод `GetClient()`. +>В том случае, если фабрика клиентов предоставляет не авторизованного клиента - +необходимо добавить в проект фабрику токенов аутентификации `IAuthTokenFactory` с методом `GetToken()`, +возвращающем токен в виде строки (без префикса `Bearer`). + +2. Добавить логирование `ILoger` +3. Внедрить зависимость в проект `services.AddSingleton();` - пример. +4. Обратиться к фабрике Persistence - клиентов и получить требуемого клиента. + +## xunit тестирование +При написании интеграционных тестов с ипользованием Persistence - клиентов +Http - клиент не обязан быть авторизован через передачу токена в `PersistenceClientFactory`. +Для осуществления тестовой авторизации достаточно добавить в `appsettings.Tests.json` : +```json +"NeedUseKeyCloak": false, + "AuthUser": { + "username": "myuser", + "password": 12345, + "clientId": "webapi", + "grantType": "password" + }, + "KeycloakGetTokenUrl": "http://192.168.0.10:8321/realms/Persistence/protocol/openid-connect/token" +``` +При этом возможна авторизация через `KeyCloak`. + diff --git a/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs b/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs index 43a5418..51edebd 100644 --- a/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs @@ -1,12 +1,12 @@ -using Mapster; +using Mapster; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Persistence.Client; -using Persistence.Client.Clients; +using Persistence.Client.Clients.Interfaces; +using Persistence.Database.Entity; using Persistence.Database.Model; using Persistence.Models; using Persistence.Models.Requests; -using System.Net; using Xunit; namespace Persistence.IntegrationTests.Controllers; @@ -20,7 +20,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest var persistenceClientFactory = scope.ServiceProvider .GetRequiredService(); - client = persistenceClientFactory.GetClient(); + client = persistenceClientFactory.GetChangeLogClient(); } [Fact] @@ -33,11 +33,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest var dtos = Generate(2); // act - var result = await client.ClearAndAddRange(idDiscriminator, dtos); + var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.Equal(2, result.Content); + Assert.Equal(2, result); } [Fact] @@ -50,11 +49,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest var dtos = createdResult.Item2.Select(e => e.Adapt()); // act - var result = await client.ClearAndAddRange(idDiscriminator, dtos); + var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.Equal(insertedCount * 2, result.Content); + Assert.Equal(insertedCount*2, result); } [Fact] @@ -67,11 +65,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest var dto = dtos.FirstOrDefault()!; // act - var result = await client.Add(idDiscriminator, dto); + var result = await client.Add(idDiscriminator, dto, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.Created, result.StatusCode); - Assert.Equal(count, result.Content); + Assert.Equal(count, result); } [Fact] @@ -83,11 +80,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest var dtos = Generate(count); // act - var result = await client.AddRange(idDiscriminator, dtos); + var result = await client.AddRange(idDiscriminator, dtos, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.Created, result.StatusCode); - Assert.Equal(count, result.Content); + Assert.Equal(count, result); } [Fact] @@ -99,8 +95,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest var idDiscriminator = Guid.NewGuid(); var dtos = Generate(1); var dto = dtos.FirstOrDefault()!; - var result = await client.Add(idDiscriminator, dto); - Assert.Equal(HttpStatusCode.Created, result.StatusCode); + var result = await client.Add(idDiscriminator, dto, new CancellationToken()); var entity = dbContext.ChangeLog .Where(x => x.IdDiscriminator == idDiscriminator) @@ -109,27 +104,23 @@ public class ChangeLogControllerTest : BaseIntegrationTest dto.DepthEnd += 10; // act - result = await client.Update(dto); + result = await client.Update(dto, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.Equal(2, result.Content); + Assert.Equal(2, result); var dateBegin = DateTimeOffset.UtcNow.AddDays(-1); var dateEnd = DateTimeOffset.UtcNow.AddDays(1); - var changeLogResult = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd); - Assert.Equal(HttpStatusCode.OK, changeLogResult.StatusCode); - Assert.NotNull(changeLogResult.Content); + var changeLogResult = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, new CancellationToken()); + Assert.NotNull(changeLogResult); - var changeLogDtos = changeLogResult.Content; - - var obsoleteDto = changeLogDtos - .Where(e => e.Obsolete.HasValue) + var obsoleteDto = changeLogResult + .Where(e => e.Obsolete.HasValue) .FirstOrDefault(); - var activeDto = changeLogDtos - .Where(e => !e.Obsolete.HasValue) + var activeDto = changeLogResult + .Where(e => !e.Obsolete.HasValue) .FirstOrDefault(); if (obsoleteDto == null || activeDto == null) @@ -162,11 +153,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest }).ToArray(); // act - var result = await client.UpdateRange(dtos); + var result = await client.UpdateRange(dtos, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.Equal(count * 2, result.Content); + Assert.Equal(count * 2, result); } [Fact] @@ -180,11 +170,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest dbContext.SaveChanges(); // act - var result = await client.Delete(entity.Id); + var result = await client.Delete(entity.Id, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.Equal(1, result.Content); + Assert.Equal(1, result); } [Fact] @@ -199,11 +188,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest // act var ids = entities.Select(e => e.Id); - var result = await client.DeleteRange(ids); + var result = await client.DeleteRange(ids, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.Equal(count, result.Content); + Assert.Equal(count, result); } [Fact] @@ -215,21 +203,20 @@ public class ChangeLogControllerTest : BaseIntegrationTest var entities = changeLogItems.Item2.OrderBy(e => e.Creation); // act - var result = await client.GetDatesRange(idDiscriminator); + var result = await client.GetDatesRange(idDiscriminator, new CancellationToken()); // assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.NotNull(result.Content); + Assert.NotNull(result); var minDate = entities.First().Creation; var maxDate = entities.Last().Creation; var expectedMinDate = minDate.ToUniversalTime().ToString(); - var actualMinDate = result.Content.From.ToUniversalTime().ToString(); + var actualMinDate = result.From.ToUniversalTime().ToString(); Assert.Equal(expectedMinDate, actualMinDate); var expectedMaxDate = maxDate.ToUniversalTime().ToString(); - var actualMaxDate = result.Content.To.ToUniversalTime().ToString(); + var actualMaxDate = result.To.ToUniversalTime().ToString(); Assert.Equal(expectedMaxDate, actualMaxDate); } @@ -250,7 +237,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest var ids = entities.Select(e => e.Id); var idsToDelete = ids.Skip(2); - var deletedCount = await client.DeleteRange(idsToDelete); + var deletedCount = await client.DeleteRange(idsToDelete, new CancellationToken()); var filterRequest = new SectionPartRequest() { @@ -266,16 +253,15 @@ public class ChangeLogControllerTest : BaseIntegrationTest }; var moment = DateTimeOffset.UtcNow.AddDays(16); - var result = await client.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest); + var result = await client.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, new CancellationToken()); - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.NotNull(result.Content); + Assert.NotNull(result); var restEntities = entities.Where(e => !idsToDelete.Contains(e.Id)); - Assert.Equal(restEntities.Count(), result.Content.Count); + Assert.Equal(restEntities.Count(), result.Count); var actualIds = restEntities.Select(e => e.Id); - var expectedIds = result.Content.Items.Select(e => e.Id); + var expectedIds = result.Items.Select(e => e.Id); Assert.Equivalent(expectedIds, actualIds); } @@ -305,17 +291,16 @@ public class ChangeLogControllerTest : BaseIntegrationTest entity.DepthEnd += 10; } var dtos = entities.Select(e => e.Adapt()).ToArray(); - await client.UpdateRange(dtos); + await client.UpdateRange(dtos, new CancellationToken()); //act var dateBegin = DateTimeOffset.UtcNow.AddDays(daysBeforeNowFilter); var dateEnd = DateTimeOffset.UtcNow.AddDays(daysAfterNowFilter); - var result = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd); + var result = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, new CancellationToken()); //assert - Assert.Equal(HttpStatusCode.OK, result.StatusCode); - Assert.NotNull(result.Content); - Assert.Equal(changeLogCount, result.Content.Count()); + Assert.NotNull(result); + Assert.Equal(changeLogCount, result.Count()); } diff --git a/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs b/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs index 3c94f47..404d8b2 100644 --- a/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/SetpointControllerTest.cs @@ -1,6 +1,6 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Persistence.Client; -using Persistence.Client.Clients; +using Persistence.Client.Clients.Interfaces; using Persistence.Database.Model; using System.Net; using Xunit; @@ -21,8 +21,8 @@ namespace Persistence.IntegrationTests.Controllers var persistenceClientFactory = scope.ServiceProvider .GetRequiredService(); - setpointClient = persistenceClientFactory.GetClient(); - } + setpointClient = persistenceClientFactory.GetSetpointClient(); + } [Fact] public async Task GetCurrent_returns_success() @@ -34,14 +34,13 @@ namespace Persistence.IntegrationTests.Controllers Guid.NewGuid() }; - //act - var response = await setpointClient.GetCurrent(setpointKeys); + //act + var response = await setpointClient.GetCurrent(setpointKeys, new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetCurrent_AfterSave_returns_success() @@ -49,15 +48,14 @@ namespace Persistence.IntegrationTests.Controllers //arrange var setpointKey = await Add(); - //act - var response = await setpointClient.GetCurrent([setpointKey]); + //act + var response = await setpointClient.GetCurrent([setpointKey], new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotEmpty(response.Content); - Assert.Equal(setpointKey, response.Content.FirstOrDefault()?.Key); - } + //assert + Assert.NotNull(response); + Assert.NotEmpty(response); + Assert.Equal(setpointKey, response.FirstOrDefault()?.Key); + } [Fact] public async Task GetHistory_returns_success() @@ -70,14 +68,13 @@ namespace Persistence.IntegrationTests.Controllers }; var historyMoment = DateTimeOffset.UtcNow; - //act - var response = await setpointClient.GetHistory(setpointKeys, historyMoment); + //act + var response = await setpointClient.GetHistory(setpointKeys, historyMoment, new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetHistory_AfterSave_returns_success() @@ -87,15 +84,14 @@ namespace Persistence.IntegrationTests.Controllers var historyMoment = DateTimeOffset.UtcNow; historyMoment = historyMoment.AddDays(1); - //act - var response = await setpointClient.GetHistory([setpointKey], historyMoment); + //act + var response = await setpointClient.GetHistory([setpointKey], historyMoment, new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotEmpty(response.Content); - Assert.Equal(setpointKey, response.Content.FirstOrDefault()?.Key); - } + //assert + Assert.NotNull(response); + Assert.NotEmpty(response); + Assert.Equal(setpointKey, response.FirstOrDefault()?.Key); + } [Fact] public async Task GetLog_returns_success() @@ -107,14 +103,13 @@ namespace Persistence.IntegrationTests.Controllers Guid.NewGuid() }; - //act - var response = await setpointClient.GetLog(setpointKeys); + //act + var response = await setpointClient.GetLog(setpointKeys, new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetLog_AfterSave_returns_success() @@ -122,15 +117,14 @@ namespace Persistence.IntegrationTests.Controllers //arrange var setpointKey = await Add(); - //act - var response = await setpointClient.GetLog([setpointKey]); + //act + var response = await setpointClient.GetLog([setpointKey], new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotEmpty(response.Content); - Assert.Equal(setpointKey, response.Content.FirstOrDefault().Key); - } + //assert + Assert.NotNull(response); + Assert.NotEmpty(response); + Assert.Equal(setpointKey, response.FirstOrDefault().Key); + } [Fact] public async Task GetDatesRange_returns_success() @@ -141,12 +135,11 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Equal(DateTimeOffset.MinValue, response.Content!.From); - Assert.Equal(DateTimeOffset.MaxValue, response.Content!.To); - } + //assert + Assert.NotNull(response); + Assert.Equal(DateTimeOffset.MinValue, response!.From); + Assert.Equal(DateTimeOffset.MaxValue, response!.To); + } [Fact] public async Task GetDatesRange_AfterSave_returns_success() @@ -163,21 +156,20 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await setpointClient.GetDatesRangeAsync(CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); + //assert + Assert.NotNull(response); - var expectedValue = part.Content! - .FirstOrDefault()!.Created - .ToString("dd.MM.yyyy-HH:mm:ss"); - var actualValueFrom = response.Content.From - .ToString("dd.MM.yyyy-HH:mm:ss"); - Assert.Equal(expectedValue, actualValueFrom); + var expectedValue = part! + .FirstOrDefault()!.Created + .ToString("dd.MM.yyyy-HH:mm:ss"); + var actualValueFrom = response.From + .ToString("dd.MM.yyyy-HH:mm:ss"); + Assert.Equal(expectedValue, actualValueFrom); - var actualValueTo = response.Content.To - .ToString("dd.MM.yyyy-HH:mm:ss"); - Assert.Equal(expectedValue, actualValueTo); - } + var actualValueTo = response.To + .ToString("dd.MM.yyyy-HH:mm:ss"); + Assert.Equal(expectedValue, actualValueTo); + } [Fact] public async Task GetPart_returns_success() @@ -189,11 +181,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetPart_AfterSave_returns_success() @@ -206,11 +197,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await setpointClient.GetPart(dateBegin, take, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotEmpty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.NotEmpty(response); + } [Fact] public async Task Save_returns_success() @@ -228,13 +218,10 @@ namespace Persistence.IntegrationTests.Controllers Value2 = 2 }; - //act - var response = await setpointClient.Add(setpointKey, setpointValue); + //act + await setpointClient.Add(setpointKey, setpointValue, new CancellationToken()); - //assert - Assert.Equal(HttpStatusCode.Created, response.StatusCode); - - return setpointKey; - } - } + return setpointKey; + } + } } diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index f970b25..3ec7fce 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -1,7 +1,7 @@ using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Persistence.Client; -using Persistence.Client.Clients; +using Persistence.Client.Clients.Interfaces; using Persistence.Database.Entity; using Persistence.Models; using Persistence.Models.Requests; @@ -21,9 +21,9 @@ namespace Persistence.IntegrationTests.Controllers var persistenceClientFactory = scope.ServiceProvider .GetRequiredService(); - techMessagesClient = persistenceClientFactory.GetClient(); - memoryCache = scope.ServiceProvider.GetRequiredService(); - } + techMessagesClient = persistenceClientFactory.GetTechMessagesClient(); + memoryCache = scope.ServiceProvider.GetRequiredService(); + } [Fact] public async Task GetPage_returns_success() @@ -43,13 +43,12 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content.Items); - Assert.Equal(requestDto.Skip, response.Content.Skip); - Assert.Equal(requestDto.Take, response.Content.Take); - } + //assert + Assert.NotNull(response); + Assert.Empty(response.Items); + Assert.Equal(requestDto.Skip, response.Skip); + Assert.Equal(requestDto.Take, response.Take); + } [Fact] public async Task GetPage_AfterSave_returns_success() @@ -67,11 +66,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Equal(dtosCount, response.Content.Count); - } + //assert + Assert.NotNull(response); + Assert.Equal(dtosCount, response.Count); + } [Fact] public async Task InsertRange_returns_success() @@ -79,16 +77,17 @@ namespace Persistence.IntegrationTests.Controllers await InsertRange(); } - [Fact] - public async Task InsertRange_returns_BadRequest() - { - //arrange - var dtos = new List() - { - new() - { - EventId = Guid.NewGuid(), - CategoryId = -1, // < 0 + [Fact] + public async Task InsertRange_returns_BadRequest() + { + //arrange + const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса"; + var dtos = new List() + { + new TechMessageDto() + { + EventId = Guid.NewGuid(), + CategoryId = -1, // < 0 Timestamp = DateTimeOffset.UtcNow, Depth = -1, // < 0 MessageText = string.Empty, // length < 0 @@ -97,12 +96,17 @@ namespace Persistence.IntegrationTests.Controllers } }; - //act - var response = await techMessagesClient.AddRange(dtos, CancellationToken.None); - - //assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } + try + { + //act + var response = await techMessagesClient.AddRange(dtos, new CancellationToken()); + } + catch (Exception ex) + { + //assert + Assert.Equal(exceptionMessage, ex.Message); + } + } [Fact] public async Task GetSystems_returns_success() @@ -115,11 +119,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetSystems(CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetSystems_AfterSave_returns_success() @@ -134,12 +137,11 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetSystems(CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - string?[]? content = response.Content?.ToArray(); - Assert.Equal(systems, content); - } + //assert + Assert.NotNull(response); + string?[]? content = response?.ToArray(); + Assert.Equal(systems, content); + } [Fact] public async Task GetStatistics_returns_success() @@ -155,11 +157,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetStatistics_AfterSave_returns_success() @@ -173,27 +174,30 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var categories = response.Content - .FirstOrDefault()?.Categories - .FirstOrDefault(e => e.Key == 0).Value; - Assert.Equal(filteredDtos.Count(), categories); - } + //assert + Assert.NotNull(response); + var categories = response + .FirstOrDefault()?.Categories + .FirstOrDefault(e => e.Key == 0).Value; + Assert.Equal(filteredDtos.Count(), categories); + } - [Fact] - public async Task GetDatesRange_returns_success() - { - //act - var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); + [Fact] + public async Task GetDatesRange_returns_success() + { + //arrange + memoryCache.Remove(SystemCacheKey); + dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - //Assert.Equal(DateTimeOffset.MinValue, response.Content?.From); - //Assert.Equal(DateTimeOffset.MaxValue, response.Content?.To); - } + //act + var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); + + //assert + Assert.NotNull(response); + Assert.Equal(DateTimeOffset.MinValue, response?.From); + Assert.Equal(DateTimeOffset.MaxValue, response?.To); + } [Fact] public async Task GetDatesRange_AfterSave_returns_success() @@ -204,12 +208,11 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotNull(response.Content?.From); - Assert.NotNull(response.Content?.To); - } + //assert + Assert.NotNull(response); + Assert.NotNull(response?.From); + Assert.NotNull(response?.To); + } [Fact] public async Task GetPart_returns_success() @@ -221,11 +224,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetPart_AfterSave_returns_success() @@ -238,11 +240,10 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotEmpty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.NotEmpty(response); + } private async Task> InsertRange() { @@ -279,9 +280,8 @@ namespace Persistence.IntegrationTests.Controllers //act var response = await techMessagesClient.AddRange(dtos, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.Created, response.StatusCode); - Assert.Equal(dtos.Count, response.Content); + //assert + Assert.Equal(dtos.Count, response); return dtos; } diff --git a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs index 952522d..ef43a10 100644 --- a/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TimeSeriesBaseControllerTest.cs @@ -1,7 +1,7 @@ using Mapster; using Microsoft.Extensions.DependencyInjection; using Persistence.Client; -using Persistence.Client.Clients; +using Persistence.Client.Clients.Interfaces; using Persistence.Database.Model; using System.Net; using Xunit; @@ -22,7 +22,7 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat var persistenceClientFactory = scope.ServiceProvider .GetRequiredService(); - timeSeriesClient = persistenceClientFactory.GetClient>(); + timeSeriesClient = persistenceClientFactory.GetTimeSeriesClient(); } public async Task InsertRangeSuccess(TDto dto) @@ -31,11 +31,10 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat var expected = dto.Adapt(); //act - var response = await timeSeriesClient.AddRange([expected]); + var response = await timeSeriesClient.AddRange(new TDto[] { expected }, new CancellationToken()); //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(1, response.Content); + Assert.Equal(1, response); } public async Task GetSuccess(DateTimeOffset beginDate, DateTimeOffset endDate, TEntity entity) @@ -47,12 +46,11 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat dbContext.SaveChanges(); - var response = await timeSeriesClient.Get(beginDate, endDate); + var response = await timeSeriesClient.Get(beginDate, endDate, new CancellationToken()); //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Single(response.Content); + Assert.NotNull(response); + Assert.Single(response); } public async Task GetDatesRangeSuccess(TEntity entity) @@ -69,13 +67,12 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat dbContext.SaveChanges(); - var response = await timeSeriesClient.GetDatesRange(); + var response = await timeSeriesClient.GetDatesRange(new CancellationToken()); //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); + Assert.NotNull(response); - var datesRangeActual = (response.Content.To - response.Content.From).Days; + var datesRangeActual = (response.To - response.From).Days; Assert.Equal(datesRangeExpected, datesRangeActual); } @@ -99,11 +96,10 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat dbContext.SaveChanges(); - var response = await timeSeriesClient.GetResampledData(entity.Date.AddMinutes(-1), differenceBetweenStartAndEndDays * 24 * 60 * 60 + 60, approxPointsCount); + var response = await timeSeriesClient.GetResampledData(entity.Date.AddMinutes(-1), differenceBetweenStartAndEndDays * 24 * 60 * 60 + 60, approxPointsCount, new CancellationToken()); //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); + Assert.NotNull(response); var ratio = entities.Count / approxPointsCount; if (ratio > 1) @@ -112,15 +108,11 @@ public abstract class TimeSeriesBaseControllerTest : BaseIntegrat .Where((_, index) => index % ratio == 0) .Count(); - Assert.Equal(expectedResampledCount, response.Content.Count()); + Assert.Equal(expectedResampledCount, response.Count()); } else { - Assert.Equal(entities.Count, response.Content.Count()); + Assert.Equal(entities.Count(), response.Count()); } - - } - - } diff --git a/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs b/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs index 1e7aa7e..f3546f5 100644 --- a/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TimestampedSetControllerTest.cs @@ -1,6 +1,6 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Persistence.Client; -using Persistence.Client.Clients; +using Persistence.Client.Clients.Interfaces; using Persistence.Models; using Xunit; @@ -14,7 +14,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest var persistenceClientFactory = scope.ServiceProvider .GetRequiredService(); - client = persistenceClientFactory.GetClient(); + client = persistenceClientFactory.GetTimestampedSetClient(); } [Fact] @@ -25,11 +25,10 @@ public class TimestampedSetControllerTest : BaseIntegrationTest IEnumerable testSets = Generate(10, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); // act - var response = await client.AddRange(idDiscriminator, testSets); + var response = await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.Equal(testSets.Count(), response.Content); + Assert.Equal(testSets.Count(), response); } [Fact] @@ -39,16 +38,14 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // act - var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue); + var response = await client.Get(idDiscriminator, null, null, 0, int.MaxValue, CancellationToken.None); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var items = response.Content!; - Assert.Equal(count, items.Count()); + Assert.NotNull(response); + Assert.Equal(count, response.Count()); } [Fact] @@ -58,18 +55,16 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); string[] props = ["A"]; // act - var response = await client.Get(idDiscriminator, null, props, 0, int.MaxValue); + var response = await client.Get(idDiscriminator, null, props, 0, int.MaxValue, new CancellationToken()); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var items = response.Content!; - Assert.Equal(count, items.Count()); - foreach (var item in items) + Assert.NotNull(response); + Assert.Equal(count, response.Count()); + foreach (var item in response) { Assert.Single(item.Set); var kv = item.Set.First(); @@ -77,7 +72,7 @@ public class TimestampedSetControllerTest : BaseIntegrationTest } } - [Fact] + [Fact] public async Task Get_geDate() { // arrange @@ -86,21 +81,19 @@ public class TimestampedSetControllerTest : BaseIntegrationTest var dateMin = DateTimeOffset.Now; var dateMax = DateTimeOffset.Now.AddSeconds(count); IEnumerable testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7))); - var insertResponse = await client.AddRange(idDiscriminator, testSets); + var insertResponse = await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var tail = testSets.OrderBy(t => t.Timestamp).Skip(count / 2).Take(int.MaxValue); var geDate = tail.First().Timestamp; var tolerance = TimeSpan.FromSeconds(1); var expectedCount = tail.Count(); // act - var response = await client.Get(idDiscriminator, geDate, null, 0, int.MaxValue); + var response = await client.Get(idDiscriminator, geDate, null, 0, int.MaxValue, CancellationToken.None); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var items = response.Content!; - Assert.Equal(expectedCount, items.Count()); - var minDate = items.Min(t => t.Timestamp); + Assert.NotNull(response); + Assert.Equal(expectedCount, response.Count()); + var minDate = response.Min(t => t.Timestamp); Assert.Equal(geDate, geDate, tolerance); } @@ -111,21 +104,19 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var expectedCount = count / 2; // act - var response = await client.Get(idDiscriminator, null, null, 2, expectedCount); + var response = await client.Get(idDiscriminator, null, null, 2, expectedCount, new CancellationToken()); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var items = response.Content!; - Assert.Equal(expectedCount, items.Count()); - } + Assert.NotNull(response); + Assert.Equal(expectedCount, response.Count()); + } - [Fact] + [Fact] public async Task Get_with_big_skip_take() { // arrange @@ -133,16 +124,14 @@ public class TimestampedSetControllerTest : BaseIntegrationTest var expectedCount = 1; int count = 10 + expectedCount; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // act - var response = await client.Get(idDiscriminator, null, null, count - expectedCount, count); + var response = await client.Get(idDiscriminator, null, null, count - expectedCount, count, new CancellationToken()); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var items = response.Content!; - Assert.Equal(expectedCount, items.Count()); + Assert.NotNull(response); + Assert.Equal(expectedCount, response.Count()); } [Fact] @@ -152,17 +141,15 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 10; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var expectedCount = 8; // act - var response = await client.GetLast(idDiscriminator, null, expectedCount); + var response = await client.GetLast(idDiscriminator, null, expectedCount, new CancellationToken()); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var items = response.Content!; - Assert.Equal(expectedCount, items.Count()); + Assert.NotNull(response); + Assert.Equal(expectedCount, response.Count()); } [Fact] @@ -174,18 +161,16 @@ public class TimestampedSetControllerTest : BaseIntegrationTest var dateMin = DateTimeOffset.Now; var dateMax = DateTimeOffset.Now.AddSeconds(count - 1); IEnumerable testSets = Generate(count, dateMin.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); var tolerance = TimeSpan.FromSeconds(1); // act - var response = await client.GetDatesRange(idDiscriminator); + var response = await client.GetDatesRange(idDiscriminator, new CancellationToken()); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - var range = response.Content!; - Assert.Equal(dateMin, range.From, tolerance); - Assert.Equal(dateMax, range.To, tolerance); + Assert.NotNull(response); + Assert.Equal(dateMin, response.From, tolerance); + Assert.Equal(dateMax, response.To, tolerance); } [Fact] @@ -195,14 +180,13 @@ public class TimestampedSetControllerTest : BaseIntegrationTest Guid idDiscriminator = Guid.NewGuid(); int count = 144; IEnumerable testSets = Generate(count, DateTimeOffset.Now.ToOffset(TimeSpan.FromHours(7))); - await client.AddRange(idDiscriminator, testSets); + await client.AddRange(idDiscriminator, testSets, CancellationToken.None); // act - var response = await client.Count(idDiscriminator); + var response = await client.Count(idDiscriminator, new CancellationToken()); // assert - Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode); - Assert.Equal(count, response.Content); + Assert.Equal(count, response); } private static IEnumerable Generate(int n, DateTimeOffset from) diff --git a/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs b/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs index f279845..731ec9e 100644 --- a/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/WitsDataControllerTest.cs @@ -1,6 +1,7 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Persistence.Client; using Persistence.Client.Clients; +using Persistence.Client.Clients.Interfaces; using Persistence.Database.Entity; using Persistence.Models; using System.Net; @@ -17,8 +18,8 @@ public class WitsDataControllerTest : BaseIntegrationTest var persistenceClientFactory = scope.ServiceProvider .GetRequiredService(); - witsDataClient = persistenceClientFactory.GetClient(); - } + witsDataClient = persistenceClientFactory.GetWitsDataClient(); + } [Fact] public async Task GetDatesRangeAsync_returns_success() @@ -31,10 +32,9 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - } + //assert + Assert.NotNull(response); + } [Fact] public async Task GetPart_returns_success() @@ -49,11 +49,10 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task InsertRange_returns_success() @@ -79,11 +78,10 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Empty(response.Content); - } + //assert + Assert.NotNull(response); + Assert.Empty(response); + } [Fact] public async Task GetDatesRangeAsync_AfterSave_returns_success() @@ -97,26 +95,25 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.GetDatesRangeAsync(discriminatorId, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); + //assert + Assert.NotNull(response); - var expectedDateFrom = dtos - .Select(e => e.Timestamped) - .Min() - .ToString("dd.MM.yyyy-HH:mm:ss"); - var actualDateFrom = response.Content.From.DateTime - .ToString("dd.MM.yyyy-HH:mm:ss"); - Assert.Equal(expectedDateFrom, actualDateFrom); + var expectedDateFrom = dtos + .Select(e => e.Timestamped) + .Min() + .ToString("dd.MM.yyyy-HH:mm:ss"); + var actualDateFrom = response.From.DateTime + .ToString("dd.MM.yyyy-HH:mm:ss"); + Assert.Equal(expectedDateFrom, actualDateFrom); - var expectedDateTo = dtos - .Select(e => e.Timestamped) - .Max() - .ToString("dd.MM.yyyy-HH:mm:ss"); - var actualDateTo = response.Content.To.DateTime - .ToString("dd.MM.yyyy-HH:mm:ss"); - Assert.Equal(expectedDateTo, actualDateTo); - } + var expectedDateTo = dtos + .Select(e => e.Timestamped) + .Max() + .ToString("dd.MM.yyyy-HH:mm:ss"); + var actualDateTo = response.To.DateTime + .ToString("dd.MM.yyyy-HH:mm:ss"); + Assert.Equal(expectedDateTo, actualDateTo); + } [Fact] public async Task GetPart_AfterSave_returns_success() @@ -132,15 +129,14 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.GetPart(discriminatorId, dateBegin, take, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.NotEmpty(response.Content); - Assert.Equal(take, response.Content.Count()); + //assert + Assert.NotNull(response); + Assert.NotEmpty(response); + Assert.Equal(take, response.Count()); - var expectedDto = dtos.FirstOrDefault(); - var actualDto = response.Content.FirstOrDefault(); - Assert.Equal(expectedDto?.DiscriminatorId, actualDto?.DiscriminatorId); + var expectedDto = dtos.FirstOrDefault(); + var actualDto = response.FirstOrDefault(); + Assert.Equal(expectedDto?.DiscriminatorId, actualDto?.DiscriminatorId); var expectedValueDto = expectedDto?.Values.FirstOrDefault(); var actualValueDto = actualDto?.Values.FirstOrDefault(); @@ -163,27 +159,27 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointCount, CancellationToken.None); - //assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotNull(response.Content); - Assert.Equal(approxPointCount, response.Content.Count()); - } + //assert + Assert.NotNull(response); + Assert.Equal(approxPointCount, response.Count()); + } - [Fact] - public async Task AddRange_returns_BadRequest() - { - //arrange - var dtos = new List() - { - new WitsDataDto() - { - DiscriminatorId = Guid.NewGuid(), - Timestamped = DateTimeOffset.UtcNow, - Values = new List() - { - new WitsValueDto() - { - RecordId = -1, // < 0 + [Fact] + public async Task AddRange_returns_BadRequest() + { + //arrange + const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса"; + var dtos = new List() + { + new WitsDataDto() + { + DiscriminatorId = Guid.NewGuid(), + Timestamped = DateTimeOffset.UtcNow, + Values = new List() + { + new WitsValueDto() + { + RecordId = -1, // < 0 ItemId = 101, // > 100 Value = string.Empty } @@ -191,12 +187,17 @@ public class WitsDataControllerTest : BaseIntegrationTest } }; - //act - var response = await witsDataClient.AddRange(dtos, CancellationToken.None); - - //assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } + try + { + //act + var response = await witsDataClient.AddRange(dtos, CancellationToken.None); + } + catch (Exception ex) + { + //assert + Assert.Equal(exceptionMessage, ex.Message); + } + } private async Task> AddRange(int countToCreate = 10) { @@ -225,10 +226,9 @@ public class WitsDataControllerTest : BaseIntegrationTest //act var response = await witsDataClient.AddRange(dtos, CancellationToken.None); - //assert - var count = dtos.SelectMany(e => e.Values).Count(); - Assert.Equal(HttpStatusCode.Created, response.StatusCode); - Assert.Equal(count, response.Content); + //assert + var count = dtos.SelectMany(e => e.Values).Count(); + Assert.Equal(count, response); return dtos; } diff --git a/Persistence.IntegrationTests/WebAppFactoryFixture.cs b/Persistence.IntegrationTests/WebAppFactoryFixture.cs index 89b5553..535236f 100644 --- a/Persistence.IntegrationTests/WebAppFactoryFixture.cs +++ b/Persistence.IntegrationTests/WebAppFactoryFixture.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Persistence.API; using Persistence.Client; using Persistence.Database.Model; @@ -34,11 +35,13 @@ public class WebAppFactoryFixture : WebApplicationFactory services.AddDbContext(options => options.UseNpgsql(connectionString)); - services.RemoveAll(); - services.AddSingleton(provider => - { - return new TestHttpClientFactory(this); - }); + services.AddLogging(builder => builder.AddConsole()); + + services.RemoveAll(); + services.AddSingleton(provider => + { + return new TestHttpClientFactory(this); + }); services.AddSingleton(); diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index 4a7b69e..db59f63 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -1,4 +1,4 @@ -using Mapster; +using Mapster; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Persistence.Database.Entity; diff --git a/Persistence/Factories/IAuthTokenFactory.cs b/Persistence/Factories/IAuthTokenFactory.cs new file mode 100644 index 0000000..2b12095 --- /dev/null +++ b/Persistence/Factories/IAuthTokenFactory.cs @@ -0,0 +1,13 @@ +namespace Persistence.Factories; + +/// +/// Фабрика токенов аутентификации +/// +public interface IAuthTokenFactory +{ + /// + /// Получить токен + /// + /// + public string GetToken(); +}