Merge pull request '#646 Репозиторий Хранения названий источников данных от систем' (#11) from DataSourceSystem into master

Reviewed-on: #11
This commit is contained in:
on.nemtina 2024-12-16 09:47:14 +05:00
commit e3319867dd
34 changed files with 841 additions and 468 deletions

View File

@ -0,0 +1,51 @@
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
namespace Persistence.API.Controllers;
/// <summary>
/// Работа с системами
/// </summary>
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class DataSourceSystemController : ControllerBase
{
private readonly IDataSourceSystemRepository dataSourceSystemRepository;
public DataSourceSystemController(IDataSourceSystemRepository dataSourceSystemRepository)
{
this.dataSourceSystemRepository = dataSourceSystemRepository;
}
/// <summary>
/// Получить системы
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult<DataSourceSystemDto>> Get(CancellationToken token)
{
var result = await dataSourceSystemRepository.Get(token);
return Ok(result);
}
/// <summary>
/// Добавить систему
/// </summary>
/// <param name="dataSourceSystemDto"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
public async Task<IActionResult> Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
await dataSourceSystemRepository.Add(dataSourceSystemDto, token);
return CreatedAtAction(nameof(Add), true);
}
}

View File

@ -1,4 +1,4 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
@ -44,17 +44,17 @@ public class TechMessagesController : ControllerBase
return Ok(result);
}
/// <summary>
/// Получить статистику по системам
/// </summary>
/// <param name="autoDrillingSystem"></param>
/// <param name="categoryIds"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("statistics")]
public async Task<ActionResult<IEnumerable<MessagesStatisticDto>>> GetStatistics([FromQuery] IEnumerable<string> autoDrillingSystem, [FromQuery] IEnumerable<int> categoryIds, CancellationToken token)
{
var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token);
/// <summary>
/// Получить статистику по системам
/// </summary>
/// <param name="autoDrillingSystem"></param>
/// <param name="categoryIds"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("statistics")]
public async Task<ActionResult<IEnumerable<MessagesStatisticDto>>> GetStatistics([FromQuery] IEnumerable<Guid> autoDrillingSystem, [FromQuery] IEnumerable<int> categoryIds, CancellationToken token)
{
var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token);
return Ok(result);
}
@ -78,11 +78,11 @@ public class TechMessagesController : ControllerBase
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("range")]
public async Task<ActionResult<DatesRangeDto>> GetDatesRangeAsync(CancellationToken token)
public async Task<ActionResult<DatesRangeDto?>> GetDatesRangeAsync(CancellationToken token)
{
var result = await techMessagesRepository.GetDatesRangeAsync(token);
return Ok(result);
return result == null ? NoContent() : Ok(result);
}
/// <summary>
@ -100,19 +100,20 @@ public class TechMessagesController : ControllerBase
return Ok(result);
}
/// <summary>
/// Добавить новые технологические сообщения
/// </summary>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
public async Task<IActionResult> AddRange([FromBody] IEnumerable<TechMessageDto> dtos, CancellationToken token)
{
var userId = User.GetUserId<Guid>();
/// <summary>
/// Добавить новые технологические сообщения
/// </summary>
/// <param name="systemId"></param>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost("{systemId}")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
public async Task<IActionResult> AddRange([FromRoute] Guid systemId, [FromBody] IEnumerable<TechMessageDto> dtos, CancellationToken token)
{
var userId = User.GetUserId<Guid>();
var result = await techMessagesRepository.AddRange(dtos, userId, token);
var result = await techMessagesRepository.AddRange(systemId, dtos, userId, token);
return CreatedAtAction(nameof(AddRange), result);
}

View File

@ -12,11 +12,11 @@ public abstract class BaseClient
this.logger = logger;
}
public async Task<T> ExecuteGetResponse<T>(Func<Task<IApiResponse<T>>> getMethod, CancellationToken token)
public async Task<T?> ExecuteGetResponse<T>(Func<Task<IApiResponse<T>>> getMethod, CancellationToken token)
{
var response = await getMethod.Invoke().WaitAsync(token);
if (response.IsSuccessful)
if (response.IsSuccessStatusCode)
{
return response.Content;
}
@ -32,7 +32,7 @@ public abstract class BaseClient
{
var response = await postMethod.Invoke().WaitAsync(token);
if (response.IsSuccessful)
if (response.IsSuccessStatusCode)
{
return;
}
@ -48,7 +48,7 @@ public abstract class BaseClient
{
var response = await postMethod.Invoke().WaitAsync(token);
if (response.IsSuccessful)
if (response.IsSuccessStatusCode)
{
return response.Content;
}

View File

@ -16,7 +16,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
{
var result = await ExecuteGetResponse<int>(
var result = await ExecuteGetResponse(
async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token);
return result;
@ -25,7 +25,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<PaginationContainer<DataWithWellDepthAndSectionDto>> GetByDate(Guid idDiscriminator, DateTimeOffset moment,
SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token)
{
var result = await ExecuteGetResponse<PaginationContainer<DataWithWellDepthAndSectionDto>>(
var result = await ExecuteGetResponse(
async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token);
return result;
@ -33,10 +33,10 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<IEnumerable<ChangeLogDto>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<ChangeLogDto>>(
var result = await ExecuteGetResponse(
async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token);
return result;
return result!;
}
public async Task<int> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token)
@ -89,7 +89,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto?>(
var result = await ExecuteGetResponse(
async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token);
return result;
@ -98,5 +98,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
public void Dispose()
{
refitChangeLogClient.Dispose();
}
GC.SuppressFinalize(this);
}
}

View File

@ -0,0 +1,37 @@
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 DataSourceSystemClient : BaseClient, IDataSourceSystemClient
{
private readonly IRefitDataSourceSystemClient dataSourceSystemClient;
public DataSourceSystemClient(IRefitDataSourceSystemClient dataSourceSystemClient, ILogger<DataSourceSystemClient> logger) : base(logger)
{
this.dataSourceSystemClient = dataSourceSystemClient;
}
public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
await ExecutePostResponse(
async () => await dataSourceSystemClient.Add(dataSourceSystemDto, token), token);
}
public async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
{
var result = await ExecuteGetResponse(
async () => await dataSourceSystemClient.Get(token), token);
return result!;
}
public void Dispose()
{
dataSourceSystemClient.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@ -0,0 +1,25 @@
using Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с системами
/// </summary>
public interface IDataSourceSystemClient : IDisposable
{
/// <summary>
/// Получить системы
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token);
/// <summary>
/// Добавить систему
/// </summary>
/// <param name="dataSourceSystemDto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
}

View File

@ -14,14 +14,14 @@ public interface ITechMessagesClient : IDisposable
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddRange(IEnumerable<TechMessageDto> dtos, CancellationToken token);
Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, CancellationToken token);
/// <summary>
/// Получить диапазон дат, для которых есть данные в репозитории
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token);
Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token);
/// <summary>
/// Получить список технологических сообщений в виде страницы
@ -43,16 +43,16 @@ public interface ITechMessagesClient : IDisposable
/// <summary>
/// Получить статистику по системам
/// </summary>
/// <param name="autoDrillingSystem"></param>
/// <param name="categoryId"></param>
/// <param name="systemIds"></param>
/// <param name="categoryIds"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token);
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systemIds, IEnumerable<int> categoryIds, CancellationToken token);
/// <summary>
/// Получить список всех систем
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<string>> GetSystems(CancellationToken token);
Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token);
}

View File

@ -0,0 +1,14 @@
using Persistence.Models;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitDataSourceSystemClient : IDisposable
{
private const string BaseRoute = "/api/dataSourceSystem";
[Get($"{BaseRoute}")]
Task<IApiResponse<IEnumerable<DataSourceSystemDto>>> Get(CancellationToken token);
[Post($"{BaseRoute}")]
Task<IApiResponse> Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
}

View File

@ -1,4 +1,5 @@
using Persistence.Models;
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Models.Requests;
using Refit;
@ -11,19 +12,19 @@ namespace Persistence.Client.Clients.Interfaces.Refit
[Get($"{BaseRoute}")]
Task<IApiResponse<PaginationContainer<TechMessageDto>>> GetPage([Query] PaginationRequest request, CancellationToken token);
[Post($"{BaseRoute}")]
Task<IApiResponse<int>> AddRange([Body] IEnumerable<TechMessageDto> dtos, CancellationToken token);
[Post($"{BaseRoute}/{{systemId}}")]
Task<IApiResponse<int>> AddRange(Guid systemId, [Body] IEnumerable<TechMessageDto> dtos, CancellationToken token);
[Get($"{BaseRoute}/systems")]
Task<IApiResponse<IEnumerable<string>>> GetSystems(CancellationToken token);
Task<IApiResponse<IEnumerable<DataSourceSystemDto>>> GetSystems(CancellationToken token);
[Get($"{BaseRoute}/range")]
Task<IApiResponse<DatesRangeDto>> GetDatesRangeAsync(CancellationToken token);
Task<IApiResponse<DatesRangeDto?>> GetDatesRangeAsync(CancellationToken token);
[Get($"{BaseRoute}/part")]
Task<IApiResponse<IEnumerable<TechMessageDto>>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
[Get($"{BaseRoute}/statistics")]
Task<IApiResponse<IEnumerable<MessagesStatisticDto>>> GetStatistics([Query] string autoDrillingSystem, [Query] int categoryId, CancellationToken token);
Task<IApiResponse<IEnumerable<MessagesStatisticDto>>> GetStatistics([Query(CollectionFormat.Multi)] IEnumerable<Guid> systemIds, [Query(CollectionFormat.Multi)] IEnumerable<int> categoryIds, CancellationToken token);
}
}

View File

@ -17,42 +17,42 @@ public class SetpointClient : BaseClient, ISetpointClient
public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<SetpointValueDto>>(
var result = await ExecuteGetResponse(
async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token);
return result;
return result!;
}
public async Task<IEnumerable<SetpointValueDto>> GetHistory(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<SetpointValueDto>>(
var result = await ExecuteGetResponse(
async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token);
return result;
return result!;
}
public async Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLog(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var result = await ExecuteGetResponse<Dictionary<Guid, IEnumerable<SetpointLogDto>>>(
var result = await ExecuteGetResponse(
async () => await refitSetpointClient.GetLog(setpointKeys, token), token);
return result;
return result!;
}
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto>(
var result = await ExecuteGetResponse(
async () => await refitSetpointClient.GetDatesRangeAsync(token), token);
return result;
return result!;
}
public async Task<IEnumerable<SetpointLogDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<SetpointLogDto>>(
var result = await ExecuteGetResponse(
async () => await refitSetpointClient.GetPart(dateBegin, take, token), token);
return result;
return result!;
}
public async Task Add(Guid setpointKey, object newValue, CancellationToken token)
@ -64,5 +64,7 @@ public class SetpointClient : BaseClient, ISetpointClient
public void Dispose()
{
refitSetpointClient.Dispose();
}
GC.SuppressFinalize(this);
}
}

View File

@ -18,31 +18,31 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token)
{
var result = await ExecuteGetResponse<PaginationContainer<TechMessageDto>>(
var result = await ExecuteGetResponse(
async () => await refitTechMessagesClient.GetPage(request, token), token);
return result;
return result!;
}
public async Task<int> AddRange(IEnumerable<TechMessageDto> dtos, CancellationToken token)
public async Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitTechMessagesClient.AddRange(dtos, token), token);
async () => await refitTechMessagesClient.AddRange(systemId, dtos, token), token);
return result;
}
public async Task<IEnumerable<string>> GetSystems(CancellationToken token)
public async Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<string>>(
var result = await ExecuteGetResponse(
async () => await refitTechMessagesClient.GetSystems(token), token);
return result;
return result!;
}
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
public async Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto>(
var result = await ExecuteGetResponse(
async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token);
return result;
@ -50,22 +50,24 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
public async Task<IEnumerable<TechMessageDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<TechMessageDto>>(
var result = await ExecuteGetResponse(
async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token);
return result;
return result!;
}
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token)
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systemIds, IEnumerable<int> categoryIds, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<MessagesStatisticDto>>(
async () => await refitTechMessagesClient.GetStatistics(autoDrillingSystem, categoryId, token), token);
var result = await ExecuteGetResponse(
async () => await refitTechMessagesClient.GetStatistics(systemIds, categoryIds, token), token);
return result;
return result!;
}
public void Dispose()
{
refitTechMessagesClient.Dispose();
}
GC.SuppressFinalize(this);
}
}

View File

@ -24,23 +24,23 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
public async Task<IEnumerable<TDto>> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<TDto>>(
var result = await ExecuteGetResponse(
async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token);
return result;
return result!;
}
public async Task<IEnumerable<TDto>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default)
{
var result = await ExecuteGetResponse<IEnumerable<TDto>>(
var result = await ExecuteGetResponse(
async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token);
return result;
return result!;
}
public async Task<DatesRangeDto?> GetDatesRange(CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto?>(
var result = await ExecuteGetResponse(
async () => await timeSeriesClient.GetDatesRange(token), token);
return result;
@ -49,5 +49,7 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
public void Dispose()
{
timeSeriesClient.Dispose();
}
GC.SuppressFinalize(this);
}
}

View File

@ -24,23 +24,23 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
public async Task<IEnumerable<TimestampedSetDto>> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable<string>? columnNames, int skip, int take, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<TimestampedSetDto>>(
var result = await ExecuteGetResponse(
async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token);
return result;
return result!;
}
public async Task<IEnumerable<TimestampedSetDto>> GetLast(Guid idDiscriminator, IEnumerable<string>? columnNames, int take, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<TimestampedSetDto>>(
var result = await ExecuteGetResponse(
async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token);
return result;
return result!;
}
public async Task<int> Count(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse<int>(
var result = await ExecuteGetResponse(
async () => await refitTimestampedSetClient.Count(idDiscriminator, token), token);
return result;
@ -48,7 +48,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto?>(
var result = await ExecuteGetResponse(
async () => await refitTimestampedSetClient.GetDatesRange(idDiscriminator, token), token);
return result;
@ -57,5 +57,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
public void Dispose()
{
refitTimestampedSetClient.Dispose();
}
GC.SuppressFinalize(this);
}
}

View File

@ -24,30 +24,32 @@ public class WitsDataClient : BaseClient, IWitsDataClient
public async Task<DatesRangeDto> GetDatesRangeAsync(Guid discriminatorId, CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto>(
var result = await ExecuteGetResponse(
async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token);
return result;
return result!;
}
public async Task<IEnumerable<WitsDataDto>> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default)
{
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
var result = await ExecuteGetResponse(
async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token);
return result;
return result!;
}
public async Task<IEnumerable<WitsDataDto>> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
var result = await ExecuteGetResponse(
async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token);
return result;
return result!;
}
public void Dispose()
{
refitWitsDataClient.Dispose();
}
GC.SuppressFinalize(this);
}
}

View File

@ -128,5 +128,19 @@ namespace Persistence.Client
return client;
}
/// <summary>
/// Получить клиент для работы c системами
/// </summary>
/// <returns></returns>
public IDataSourceSystemClient GetDataSourceSystemClient()
{
var logger = provider.GetRequiredService<ILogger<DataSourceSystemClient>>();
var restClient = RestService.For<IRefitDataSourceSystemClient>(httpClient, RefitSettings);
var client = new DataSourceSystemClient(restClient, logger);
return client;
}
}
}

View File

@ -15,6 +15,7 @@ Persistence сервисом посредством обращения к кон
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
- `IWitsDataClient` - Клиент для работы с параметрами Wits
- `IDataSourceSystemClient` - Клиент для работы с системами
## Использование
Для получения того или иного Persistence - клиента нужно

View File

@ -9,10 +9,10 @@ using Persistence.Database.Model;
#nullable disable
namespace Persistence.Database.Postgres.Migrations
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
{
[DbContext(typeof(PersistenceDbContext))]
[Migration("20241202072250_TechMessageMigration")]
[DbContext(typeof(PersistencePostgresContext))]
[Migration("20241212041758_TechMessageMigration")]
partial class TechMessageMigration
{
/// <inheritdoc />
@ -48,6 +48,30 @@ namespace Persistence.Database.Postgres.Migrations
b.ToTable("DrillingSystem");
});
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
{
b.Property<Guid>("DiscriminatorId")
.HasColumnType("uuid")
.HasComment("Дискриминатор системы");
b.Property<int>("ParameterId")
.HasColumnType("integer")
.HasComment("Id параметра");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Временная отметка");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Значение параметра в виде строки");
b.HasKey("DiscriminatorId", "ParameterId", "Timestamp");
b.ToTable("ParameterData");
});
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.Property<Guid>("EventId")
@ -59,27 +83,23 @@ namespace Persistence.Database.Postgres.Migrations
.HasColumnType("integer")
.HasComment("Id Категории важности");
b.Property<double?>("Depth")
.HasColumnType("double precision")
.HasComment("Глубина забоя");
b.Property<int>("EventState")
.HasColumnType("integer")
.HasComment("Статус события");
b.Property<string>("MessageText")
b.Property<Guid>("SystemId")
.HasColumnType("uuid")
.HasComment("Id системы, к которой относится сообщение");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("varchar(512)")
.HasComment("Текст сообщения");
b.Property<Guid>("SystemId")
.HasColumnType("uuid")
.HasComment("Id системы автобурения, к которой относится сообщение");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Дата возникновения");
b.Property<Guid>("UserId")
.HasColumnType("uuid")
.HasComment("Id пользователя за пультом бурильщика");
b.HasKey("EventId");
b.HasIndex("SystemId");
@ -110,6 +130,59 @@ namespace Persistence.Database.Postgres.Migrations
});
});
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Ключ записи");
b.Property<DateTimeOffset>("Creation")
.HasColumnType("timestamp with time zone")
.HasComment("Дата создания записи");
b.Property<double>("DepthEnd")
.HasColumnType("double precision")
.HasComment("Глубина забоя на дату окончания интервала");
b.Property<double>("DepthStart")
.HasColumnType("double precision")
.HasComment("Глубина забоя на дату начала интервала");
b.Property<Guid>("IdAuthor")
.HasColumnType("uuid")
.HasComment("Автор изменения");
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
.HasComment("Дискриминатор таблицы");
b.Property<Guid?>("IdEditor")
.HasColumnType("uuid")
.HasComment("Редактор");
b.Property<Guid?>("IdNext")
.HasColumnType("uuid")
.HasComment("Id заменяющей записи");
b.Property<Guid>("IdSection")
.HasColumnType("uuid")
.HasComment("Ключ секции");
b.Property<DateTimeOffset?>("Obsolete")
.HasColumnType("timestamp with time zone")
.HasComment("Дата устаревания (например при удалении)");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("Значение");
b.HasKey("Id");
b.ToTable("ChangeLog");
});
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
{
b.Property<DateTimeOffset>("Date")

View File

@ -2,7 +2,7 @@
#nullable disable
namespace Persistence.Database.Postgres.Migrations
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
{
/// <inheritdoc />
public partial class TechMessageMigration : Migration
@ -11,16 +11,16 @@ namespace Persistence.Database.Postgres.Migrations
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DrillingSystem",
name: "DataSourceSystem",
columns: table => new
{
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы автобурения"),
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы автобурения"),
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы автобурения")
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы - источника данных"),
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы - источника данных"),
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы - источника данных")
},
constraints: table =>
{
table.PrimaryKey("PK_DrillingSystem", x => x.SystemId);
table.PrimaryKey("PK_DataSourceSystem", x => x.SystemId);
});
migrationBuilder.CreateTable(
@ -30,18 +30,17 @@ namespace Persistence.Database.Postgres.Migrations
EventId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id события"),
CategoryId = table.Column<int>(type: "integer", nullable: false, comment: "Id Категории важности"),
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"),
Depth = table.Column<double>(type: "double precision", nullable: true, comment: "Глубина забоя"),
MessageText = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы автобурения, к которой относится сообщение"),
UserId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id пользователя за пультом бурильщика")
Text = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы, к которой относится сообщение"),
EventState = table.Column<int>(type: "integer", nullable: false, comment: "Статус события")
},
constraints: table =>
{
table.PrimaryKey("PK_TechMessage", x => x.EventId);
table.ForeignKey(
name: "FK_TechMessage_DrillingSystem_SystemId",
name: "FK_TechMessage_DataSourceSystem_SystemId",
column: x => x.SystemId,
principalTable: "DrillingSystem",
principalTable: "DataSourceSystem",
principalColumn: "SystemId",
onDelete: ReferentialAction.Cascade);
});
@ -59,7 +58,7 @@ namespace Persistence.Database.Postgres.Migrations
name: "TechMessage");
migrationBuilder.DropTable(
name: "DrillingSystem");
name: "DataSourceSystem");
}
}
}

View File

@ -1,6 +1,5 @@
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
@ -25,31 +24,31 @@ namespace Persistence.Database.Postgres.Migrations
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Persistence.Database.Entity.DrillingSystem", b =>
modelBuilder.Entity("Persistence.Database.Entity.DataSourceSystem", b =>
{
b.Property<Guid>("SystemId")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasComment("Id системы автобурения");
.HasComment("Id системы - источника данных");
b.Property<string>("Description")
.HasColumnType("text")
.HasComment("Описание системы автобурения");
.HasComment("Описание системы - источника данных");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(256)")
.HasComment("Наименование системы автобурения");
.HasComment("Наименование системы - источника данных");
b.HasKey("SystemId");
b.ToTable("DrillingSystem");
b.ToTable("DataSourceSystem");
});
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
{
b.Property<int>("DiscriminatorId")
.HasColumnType("integer")
b.Property<Guid>("DiscriminatorId")
.HasColumnType("uuid")
.HasComment("Дискриминатор системы");
b.Property<int>("ParameterId")
@ -81,27 +80,23 @@ namespace Persistence.Database.Postgres.Migrations
.HasColumnType("integer")
.HasComment("Id Категории важности");
b.Property<double?>("Depth")
.HasColumnType("double precision")
.HasComment("Глубина забоя");
b.Property<int>("EventState")
.HasColumnType("integer")
.HasComment("Статус события");
b.Property<string>("MessageText")
b.Property<Guid>("SystemId")
.HasColumnType("uuid")
.HasComment("Id системы, к которой относится сообщение");
b.Property<string>("Text")
.IsRequired()
.HasColumnType("varchar(512)")
.HasComment("Текст сообщения");
b.Property<Guid>("SystemId")
.HasColumnType("uuid")
.HasComment("Id системы автобурения, к которой относится сообщение");
b.Property<DateTimeOffset>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("Дата возникновения");
b.Property<Guid>("UserId")
.HasColumnType("uuid")
.HasComment("Id пользователя за пультом бурильщика");
b.HasKey("EventId");
b.HasIndex("SystemId");
@ -137,48 +132,48 @@ namespace Persistence.Database.Postgres.Migrations
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("Id");
.HasComment("Ключ записи");
b.Property<DateTimeOffset>("Creation")
.HasColumnType("timestamp with time zone")
.HasColumnName("Creation");
.HasComment("Дата создания записи");
b.Property<double>("DepthEnd")
.HasColumnType("double precision")
.HasColumnName("DepthEnd");
.HasComment("Глубина забоя на дату окончания интервала");
b.Property<double>("DepthStart")
.HasColumnType("double precision")
.HasColumnName("DepthStart");
.HasComment("Глубина забоя на дату начала интервала");
b.Property<Guid>("IdAuthor")
.HasColumnType("uuid")
.HasColumnName("IdAuthor");
.HasComment("Автор изменения");
b.Property<Guid>("IdDiscriminator")
.HasColumnType("uuid")
.HasColumnName("IdDiscriminator");
.HasComment("Дискриминатор таблицы");
b.Property<Guid?>("IdEditor")
.HasColumnType("uuid")
.HasColumnName("IdEditor");
.HasComment("Редактор");
b.Property<Guid?>("IdNext")
.HasColumnType("uuid")
.HasColumnName("IdNext");
.HasComment("Id заменяющей записи");
b.Property<Guid>("IdSection")
.HasColumnType("uuid")
.HasColumnName("IdSection");
.HasComment("Ключ секции");
b.Property<DateTimeOffset?>("Obsolete")
.HasColumnType("timestamp with time zone")
.HasColumnName("Obsolete");
.HasComment("Дата устаревания (например при удалении)");
b.Property<IDictionary<string, object>>("Value")
b.Property<string>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasColumnName("Value");
.HasComment("Значение");
b.HasKey("Id");
@ -294,7 +289,7 @@ namespace Persistence.Database.Postgres.Migrations
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
{
b.HasOne("Persistence.Database.Entity.DrillingSystem", "System")
b.HasOne("Persistence.Database.Entity.DataSourceSystem", "System")
.WithMany()
.HasForeignKey("SystemId")
.OnDelete(DeleteBehavior.Cascade)

View File

@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
public class DataSourceSystem
{
[Key, Comment("Id системы - источника данных")]
public Guid SystemId { get; set; }
[Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы - источника данных")]
public required string Name { get; set; }
[Comment("Описание системы - источника данных")]
public string? Description { get; set; }
}

View File

@ -1,16 +0,0 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Persistence.Database.Entity;
public class DrillingSystem
{
[Key, Comment("Id системы автобурения")]
public Guid SystemId { get; set; }
[Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы автобурения")]
public required string Name { get; set; }
[Comment("Описание системы автобурения")]
public string? Description { get; set; }
}

View File

@ -1,4 +1,4 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@ -15,19 +15,16 @@ namespace Persistence.Database.Entity
[Comment("Дата возникновения")]
public DateTimeOffset Timestamp { get; set; }
[Comment("Глубина забоя")]
public double? Depth { get; set; }
[Column(TypeName = "varchar(512)"), Comment("Текст сообщения")]
public required string Text { get; set; }
[Column(TypeName = "varchar(512)"), Comment("Текст сообщения")]
public required string MessageText { get; set; }
[Required, Comment("Id системы, к которой относится сообщение")]
public required Guid SystemId { get; set; }
[Required, Comment("Id системы автобурения, к которой относится сообщение")]
public required Guid SystemId { get; set; }
[Required, ForeignKey(nameof(SystemId)), Comment("Система, к которой относится сообщение")]
public virtual required DataSourceSystem System { get; set; }
[Required, ForeignKey(nameof(SystemId)), Comment("Система автобурения, к которой относится сообщение")]
public virtual required DrillingSystem System { get; set; }
[Comment("Id пользователя за пультом бурильщика")]
public Guid UserId { get; set; }
}
[Comment("Статус события")]
public int EventState { get; set; }
}
}

View File

@ -21,7 +21,9 @@ public class PersistenceDbContext : DbContext
public DbSet<ParameterData> ParameterData => Set<ParameterData>();
public PersistenceDbContext(DbContextOptions options)
public DbSet<DataSourceSystem> DataSourceSystem => Set<DataSourceSystem>();
public PersistenceDbContext(DbContextOptions options)
: base(options)
{

View File

@ -0,0 +1,82 @@
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 Xunit;
namespace Persistence.IntegrationTests.Controllers
{
public class DataSourceSystemControllerTest : BaseIntegrationTest
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly IDataSourceSystemClient dataSourceSystemClient;
private readonly IMemoryCache memoryCache;
public DataSourceSystemControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var scope = factory.Services.CreateScope();
var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>();
dataSourceSystemClient = persistenceClientFactory.GetDataSourceSystemClient();
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
}
[Fact]
public async Task Get_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await dataSourceSystemClient.Get(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task Get_AfterSave_returns_success()
{
//arrange
await Add();
//act
var response = await dataSourceSystemClient.Get(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedSystemCount = 1;
var actualSystemCount = response!.Count();
Assert.Equal(expectedSystemCount, actualSystemCount);
}
[Fact]
public async Task Add_returns_success()
{
await Add();
}
private async Task Add()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<DataSourceSystem>();
var dto = new DataSourceSystemDto()
{
SystemId = Guid.NewGuid(),
Name = "Test",
Description = "Test"
};
//act
await dataSourceSystemClient.Add(dto, CancellationToken.None);
}
}
}

View File

@ -4,34 +4,35 @@ using Persistence.Client;
using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Enumerations;
using Persistence.Models.Requests;
using System.Net;
using Xunit;
namespace Persistence.IntegrationTests.Controllers
{
public class TechMessagesControllerTest : BaseIntegrationTest
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey";
private readonly ITechMessagesClient techMessagesClient;
private readonly IMemoryCache memoryCache;
public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var scope = factory.Services.CreateScope();
var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>();
public class TechMessagesControllerTest : BaseIntegrationTest
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly ITechMessagesClient techMessagesClient;
private readonly IMemoryCache memoryCache;
public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory)
{
var scope = factory.Services.CreateScope();
var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>();
techMessagesClient = persistenceClientFactory.GetTechMessagesClient();
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
}
[Fact]
public async Task GetPage_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
[Fact]
public async Task GetPage_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
var requestDto = new PaginationRequest()
{
@ -50,18 +51,18 @@ namespace Persistence.IntegrationTests.Controllers
Assert.Equal(requestDto.Take, response.Take);
}
[Fact]
public async Task GetPage_AfterSave_returns_success()
{
//arrange
var dtos = await InsertRange();
var dtosCount = dtos.Count();
var requestDto = new PaginationRequest()
{
Skip = 0,
Take = 2,
SortSettings = nameof(TechMessage.CategoryId)
};
[Fact]
public async Task GetPage_AfterSave_returns_success()
{
//arrange
var dtos = await InsertRange(Guid.NewGuid());
var dtosCount = dtos.Count();
var requestDto = new PaginationRequest()
{
Skip = 0,
Take = 2,
SortSettings = nameof(TechMessage.CategoryId)
};
//act
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
@ -71,17 +72,18 @@ namespace Persistence.IntegrationTests.Controllers
Assert.Equal(dtosCount, response.Count);
}
[Fact]
public async Task InsertRange_returns_success()
{
await InsertRange();
}
[Fact]
public async Task InsertRange_returns_success()
{
await InsertRange(Guid.NewGuid());
}
[Fact]
public async Task InsertRange_returns_BadRequest()
{
//arrange
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
var systemId = Guid.NewGuid();
var dtos = new List<TechMessageDto>()
{
new TechMessageDto()
@ -89,17 +91,15 @@ namespace Persistence.IntegrationTests.Controllers
EventId = Guid.NewGuid(),
CategoryId = -1, // < 0
Timestamp = DateTimeOffset.UtcNow,
Depth = -1, // < 0
MessageText = string.Empty, // length < 0
System = string.Concat(Enumerable.Repeat(nameof(TechMessageDto.System), 100)), // length > 256
UserId = Guid.NewGuid()
}
};
Text = string.Empty, // length < 0
EventState = EventState.Triggered
}
};
try
{
//act
var response = await techMessagesClient.AddRange(dtos, new CancellationToken());
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
}
catch (Exception ex)
{
@ -108,102 +108,97 @@ namespace Persistence.IntegrationTests.Controllers
}
}
[Fact]
public async Task GetSystems_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
//act
var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetSystems_AfterSave_returns_success()
{
//arrange
var dtos = await InsertRange();
var systems = dtos
.Select(e => e.System)
.Distinct()
.ToArray();
//act
var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert
Assert.NotNull(response);
string?[]? content = response?.ToArray();
Assert.Equal(systems, content);
}
[Fact]
public async Task GetStatistics_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
var importantId = 1;
var autoDrillingSystem = nameof(TechMessageDto.System);
//act
var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetStatistics_AfterSave_returns_success()
{
//arrange
var importantId = 0;
var autoDrillingSystem = nameof(TechMessageDto.System);
var dtos = await InsertRange();
var filteredDtos = dtos.Where(e => e.CategoryId == importantId && e.System == autoDrillingSystem);
//act
var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None);
//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()
public async Task GetSystems_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DrillingSystem>();
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
//act
var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Equal(DateTimeOffset.MinValue, response?.From);
Assert.Equal(DateTimeOffset.MaxValue, response?.To);
Assert.Empty(response);
}
[Fact]
public async Task GetDatesRange_AfterSave_returns_success()
{
//arrange
await InsertRange();
[Fact]
public async Task GetSystems_AfterSave_returns_success()
{
//arrange
await InsertRange(Guid.NewGuid());
//act
var response = await techMessagesClient.GetSystems(CancellationToken.None);
//assert
Assert.NotNull(response);
var expectedSystemCount = 1;
Assert.Equal(expectedSystemCount, response!.Count());
}
[Fact]
public async Task GetStatistics_returns_success()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
var categoryIds = new [] { 1, 2 };
var systemIds = new [] { Guid.NewGuid() };
//act
var response = await techMessagesClient.GetStatistics(systemIds, categoryIds, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.Empty(response);
}
[Fact]
public async Task GetStatistics_AfterSave_returns_success()
{
//arrange
var categoryIds = new[] { 1 };
var systemId = Guid.NewGuid();
var dtos = await InsertRange(systemId);
var filteredDtos = dtos.Where(e => categoryIds.Contains(e.CategoryId));
//act
var response = await techMessagesClient.GetStatistics([systemId], categoryIds, CancellationToken.None);
//assert
Assert.NotNull(response);
Assert.NotEmpty(response);
var categories = response
.FirstOrDefault()!.Categories
.Count();
Assert.Equal(filteredDtos.Count(), categories);
}
[Fact]
public async Task GetDatesRange_returns_NoContent()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
//act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
//assert
Assert.Null(response);
}
[Fact]
public async Task GetDatesRange_AfterSave_returns_success()
{
//arrange
await InsertRange(Guid.NewGuid());
//act
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
@ -229,13 +224,13 @@ namespace Persistence.IntegrationTests.Controllers
Assert.Empty(response);
}
[Fact]
public async Task GetPart_AfterSave_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 1;
await InsertRange();
[Fact]
public async Task GetPart_AfterSave_returns_success()
{
//arrange
var dateBegin = DateTimeOffset.UtcNow;
var take = 1;
await InsertRange(Guid.NewGuid());
//act
var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
@ -245,40 +240,36 @@ namespace Persistence.IntegrationTests.Controllers
Assert.NotEmpty(response);
}
private async Task<IEnumerable<TechMessageDto>> InsertRange()
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DrillingSystem>();
private async Task<IEnumerable<TechMessageDto>> InsertRange(Guid systemId)
{
//arrange
memoryCache.Remove(SystemCacheKey);
dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<DataSourceSystem>();
var dtos = new List<TechMessageDto>()
{
new()
{
EventId = Guid.NewGuid(),
CategoryId = 1,
Timestamp = DateTimeOffset.UtcNow,
Depth = 1.11,
MessageText = nameof(TechMessageDto.MessageText),
System = nameof(TechMessageDto.System).ToLower(),
UserId = Guid.NewGuid()
},
new()
{
EventId = Guid.NewGuid(),
CategoryId = 2,
Timestamp = DateTimeOffset.UtcNow,
Depth = 2.22,
MessageText = nameof(TechMessageDto.MessageText),
System = nameof(TechMessageDto.System).ToLower(),
UserId = Guid.NewGuid()
}
};
var dtos = new List<TechMessageDto>()
{
new TechMessageDto()
{
EventId = Guid.NewGuid(),
CategoryId = 1,
Timestamp = DateTimeOffset.UtcNow,
Text = nameof(TechMessageDto.Text),
EventState = Models.Enumerations.EventState.Triggered
},
new TechMessageDto()
{
EventId = Guid.NewGuid(),
CategoryId = 2,
Timestamp = DateTimeOffset.UtcNow,
Text = nameof(TechMessageDto.Text),
EventState = Models.Enumerations.EventState.Triggered
}
};
//act
var response = await techMessagesClient.AddRange(dtos, CancellationToken.None);
//act
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
//assert
Assert.Equal(dtos.Count, response);

View File

@ -34,7 +34,8 @@ public static class DependencyInjection
services.AddTransient<ITimestampedSetRepository, TimestampedSetRepository>();
services.AddTransient<ITechMessagesRepository, TechMessagesRepository>();
services.AddTransient<IParameterRepository, ParameterRepository>();
services.AddTransient<IDataSourceSystemRepository, DataSourceSystemCachedRepository>();
return services;
return services;
}
}

View File

@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Persistence.Models;
namespace Persistence.Repository.Repositories;
public class DataSourceSystemCachedRepository : DataSourceSystemRepository
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
private readonly IMemoryCache memoryCache;
private const int CacheExpirationInMinutes = 60;
private readonly TimeSpan? AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);
public DataSourceSystemCachedRepository(DbContext db, IMemoryCache memoryCache) : base(db)
{
this.memoryCache = memoryCache;
}
public override async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
await base.Add(dataSourceSystemDto, token);
memoryCache.Remove(SystemCacheKey);
}
public override async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
{
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async (cacheEntry) =>
{
cacheEntry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;
var dtos = await base.Get(token);
return dtos;
});
return systems!;
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Repositories;
namespace Persistence.Repository.Repositories;
public class DataSourceSystemRepository : IDataSourceSystemRepository
{
protected DbContext db;
public DataSourceSystemRepository(DbContext db)
{
this.db = db;
}
protected virtual IQueryable<DataSourceSystem> GetQueryReadOnly() => db.Set<DataSourceSystem>();
public virtual async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
{
var entity = dataSourceSystemDto.Adapt<DataSourceSystem>();
await db.Set<DataSourceSystem>().AddAsync(entity, token);
await db.SaveChangesAsync(token);
}
public virtual async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query.ToArrayAsync(token);
var dtos = entities.Select(e => e.Adapt<DataSourceSystemDto>());
return dtos;
}
}

View File

@ -1,6 +1,7 @@
using Mapster;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using Persistence.Database.Entity;
using Persistence.Models;
using Persistence.Models.Requests;
@ -9,17 +10,15 @@ using UuidExtensions;
namespace Persistence.Repository.Repositories
{
public class TechMessagesRepository : ITechMessagesRepository
{
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey";
private const int CacheExpirationInMinutes = 60;
private readonly IMemoryCache memoryCache;
private readonly DbContext db;
public class TechMessagesRepository : ITechMessagesRepository
{
private readonly IDataSourceSystemRepository sourceSystemRepository;
private DbContext db;
public TechMessagesRepository(DbContext db, IMemoryCache memoryCache)
public TechMessagesRepository(DbContext db, IDataSourceSystemRepository sourceSystemRepository)
{
this.memoryCache = memoryCache;
this.db = db;
this.sourceSystemRepository = sourceSystemRepository;
}
protected virtual IQueryable<TechMessage> GetQueryReadOnly() => db.Set<TechMessage>()
@ -50,19 +49,18 @@ namespace Persistence.Repository.Repositories
return dto;
}
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<string> autoDrillingSystem, IEnumerable<int> categoryIds, CancellationToken token)
{
var query = GetQueryReadOnly();
var systems = autoDrillingSystem.Select(s => s.ToLower().Trim());
var result = await query
.Where(e => !systems.Any() || systems.Contains(e.System.Name.ToLower().Trim()))
.GroupBy(e => e.System.Name, (key, group) => new
{
System = key,
Categories = group
.Where(g => !categoryIds.Any() || categoryIds.Contains(g.CategoryId))
})
.ToArrayAsync(token);
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systems, IEnumerable<int> categoryIds, CancellationToken token)
{
var query = GetQueryReadOnly();
var result = await query
.Where(e => !systems.Any() || systems.Contains(e.System.SystemId))
.GroupBy(e => e.System.SystemId, (key, group) => new
{
System = group.FirstOrDefault()!.System.Name,
Categories = group
.Where(g => !categoryIds.Any() || categoryIds.Contains(g.CategoryId))
})
.ToArrayAsync(token);
var entities = new List<MessagesStatisticDto>();
foreach (var e in result)
@ -81,27 +79,18 @@ namespace Persistence.Repository.Repositories
return entities;
}
public async Task<IEnumerable<string>> GetSystems(CancellationToken token)
{
var entities = await GetDrillingSystems(token);
var result = entities.Select(e => e.Name);
return result;
}
public async Task<int> AddRange(IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token)
{
public async Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token)
{
await CreateSystemIfNotExist(systemId, token);
var entities = new List<TechMessage>();
foreach (var dto in dtos)
{
var entity = dto.Adapt<TechMessage>();
var systems = await GetDrillingSystems(token);
var systemId = systems.FirstOrDefault(e => e.Name.ToLower().Trim() == dto.System.ToLower().Trim())?.SystemId
?? await CreateDrillingSystem(dto.System, token);
foreach (var dto in dtos)
{
var entity = dto.Adapt<TechMessage>();
await CreateSystemIfNotExist(systemId, token);
entity.SystemId = systemId;
entity.UserId = userId;
entities.Add(entity);
}
@ -125,54 +114,50 @@ namespace Persistence.Repository.Repositories
return dtos;
}
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
{
var query = GetQueryReadOnly()
.GroupBy(e => 1)
.Select(group => new
{
Min = group.Min(e => e.Timestamp),
Max = group.Max(e => e.Timestamp),
});
var values = await query.FirstOrDefaultAsync(token);
var result = new DatesRangeDto()
{
From = values?.Min ?? DateTimeOffset.MinValue,
To = values?.Max ?? DateTimeOffset.MaxValue
};
public async Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token)
{
var systems = await sourceSystemRepository.Get(token);
return systems!;
}
public async Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token)
{
var query = GetQueryReadOnly()
.GroupBy(e => 1)
.Select(group => new
{
Min = group.Min(e => e.Timestamp),
Max = group.Max(e => e.Timestamp),
});
var values = await query.FirstOrDefaultAsync(token);
if (values == null)
return null;
var result = new DatesRangeDto()
{
From = values?.Min ?? DateTimeOffset.MinValue,
To = values?.Max ?? DateTimeOffset.MaxValue
};
return result;
}
private async Task<IEnumerable<Models.DrillingSystemDto>> GetDrillingSystems(CancellationToken token)
{
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f =>
{
f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes);
private async Task CreateSystemIfNotExist(Guid systemId, CancellationToken token)
{
var systems = await sourceSystemRepository.Get(token);
var system = systems?.FirstOrDefault(e => e.SystemId == systemId);
var query = db.Set<Database.Entity.DrillingSystem>();
var entities = await query.ToListAsync(token);
var dtos = entities.Select(e => e.Adapt<Models.DrillingSystemDto>());
return dtos;
});
return systems!;
}
private async Task<Guid> CreateDrillingSystem(string name, CancellationToken token)
{
memoryCache.Remove(SystemCacheKey);
var entity = new DrillingSystem()
{
SystemId = Uuid7.Guid(),
Name = name.ToLower().Trim()
};
await db.Set<DrillingSystem>().AddAsync(entity, token);
await db.SaveChangesAsync(token);
return entity.SystemId;
}
}
if (system == null)
{
system = new DataSourceSystemDto()
{
SystemId = systemId,
Name = string.Empty
};
await sourceSystemRepository.Add(system, token);
}
}
}
}

View File

@ -1,9 +1,9 @@
namespace Persistence.Models;
namespace Persistence.Models;
/// <summary>
/// Модель системы автобурения
/// Модель системы - источника данных
/// </summary>
public class DrillingSystemDto
public class DataSourceSystemDto
{
/// <summary>
/// Ключ
@ -13,7 +13,7 @@ public class DrillingSystemDto
/// <summary>
/// Наименование
/// </summary>
public required string Name { get; set; }
public required string Name { get; set; } = string.Empty;
/// <summary>
/// Описание

View File

@ -0,0 +1,6 @@
namespace Persistence.Models.Enumerations;
public enum EventState
{
NotTriggered = 0,
Triggered = 1,
}

View File

@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using Persistence.Models.Enumerations;
namespace Persistence.Models
{
@ -24,29 +25,16 @@ namespace Persistence.Models
/// </summary>
public DateTimeOffset Timestamp { get; set; }
/// <summary>
/// Глубина забоя
/// </summary>
[Range(0, double.MaxValue, ErrorMessage = "Глубина забоя не может быть меньше 0")]
public double? Depth { get; set; }
/// <summary>
/// Текст сообщения
/// </summary>
[Required]
[StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")]
public required string Text { get; set; }
/// <summary>
/// Текст сообщения
/// </summary>
[Required]
[StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")]
public required string MessageText { get; set; }
/// <summary>
/// Система автобурения, к которой относится сообщение
/// </summary>
[Required]
[StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина наименования системы АБ от 1 до 256 символов")]
public required string System { get; set; }
/// <summary>
/// Id пользователя за пультом бурильщика
/// </summary>
public Guid UserId { get; set; }
}
/// <summary>
/// Статус события
/// </summary>
public EventState EventState { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using Persistence.Models;
namespace Persistence.Repositories;
/// <summary>
/// Интерфейс по работе с системами - источниками данных
/// </summary>
public interface IDataSourceSystemRepository
{
/// <summary>
/// Добавить систему
/// </summary>
/// <param name="dataSourceSystemDto"></param>
/// <returns></returns>
public Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
/// <summary>
/// Получить список систем
/// </summary>
/// <returns></returns>
public Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token);
}

View File

@ -22,14 +22,14 @@ namespace Persistence.Repositories
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddRange(IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token);
Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token);
/// <summary>
/// Получение списка уникальных названий систем АБ
/// Получение списка систем
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<string>> GetSystems(CancellationToken token);
Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token);
/// <summary>
/// Получение количества сообщений по категориям и системам автобурения
@ -38,7 +38,7 @@ namespace Persistence.Repositories
/// <param name="autoDrillingSystem">Система автобурения</param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<string> autoDrillingSystem, IEnumerable<int> categoryIds, CancellationToken token);
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> autoDrillingSystem, IEnumerable<int> categoryIds, CancellationToken token);
/// <summary>
/// Получить порцию записей, начиная с заданной даты
@ -54,6 +54,6 @@ namespace Persistence.Repositories
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token);
Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token);
}
}