From 5ad342a0441895bcf5ee18acf0b6b770f975ba8e Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Thu, 12 Dec 2024 11:47:52 +0500 Subject: [PATCH 1/7] =?UTF-8?q?=D0=90=D0=BA=D1=82=D1=83=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B1=D0=BE=D1=82=D1=83=20=D1=81=20=D1=82=D0=B5=D1=85=D0=BD?= =?UTF-8?q?=D0=BE=D0=BB=D0=BE=D0=B3=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8?= =?UTF-8?q?=D0=BC=D0=B8=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=D0=BC=D0=B8=20=D0=BF=D0=BE=D0=B4=20Event=20Service?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/TechMessagesController.cs | 9 +- .../Clients/Interfaces/ITechMessagesClient.cs | 8 +- .../Refit/IRefitTechMessagesClient.cs | 11 +- .../Clients/TechMessagesClient.cs | 12 +- ...12041758_TechMessageMigration.Designer.cs} | 103 +++++++++++++++--- ...=> 20241212041758_TechMessageMigration.cs} | 9 +- ...PersistencePostgresContextModelSnapshot.cs | 49 ++++----- Persistence.Database/Entity/TechMessage.cs | 11 +- .../Controllers/TechMessagesControllerTest.cs | 65 +++++------ .../Repositories/TechMessagesRepository.cs | 76 ++++++------- Persistence/Models/Enumerations/EventState.cs | 6 + Persistence/Models/TechMessageDto.cs | 20 +--- .../Repositories/ITechMessagesRepository.cs | 8 +- 13 files changed, 218 insertions(+), 169 deletions(-) rename Persistence.Database.Postgres/Migrations/{20241202072250_TechMessageMigration.Designer.cs => 20241212041758_TechMessageMigration.Designer.cs} (70%) rename Persistence.Database.Postgres/Migrations/{20241202072250_TechMessageMigration.cs => 20241212041758_TechMessageMigration.cs} (81%) create mode 100644 Persistence/Models/Enumerations/EventState.cs diff --git a/Persistence.API/Controllers/TechMessagesController.cs b/Persistence.API/Controllers/TechMessagesController.cs index a7b0094..e5705b9 100644 --- a/Persistence.API/Controllers/TechMessagesController.cs +++ b/Persistence.API/Controllers/TechMessagesController.cs @@ -52,7 +52,7 @@ public class TechMessagesController : ControllerBase /// /// [HttpGet("statistics")] - public async Task>> GetStatistics([FromQuery] IEnumerable autoDrillingSystem, [FromQuery] IEnumerable categoryIds, CancellationToken token) + public async Task>> GetStatistics([FromQuery] IEnumerable autoDrillingSystem, [FromQuery] IEnumerable categoryIds, CancellationToken token) { var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token); @@ -103,16 +103,17 @@ public class TechMessagesController : ControllerBase /// /// Добавить новые технологические сообщения /// + /// /// /// /// - [HttpPost] + [HttpPost("{systemId}")] [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] - public async Task AddRange([FromBody] IEnumerable dtos, CancellationToken token) + public async Task AddRange([FromRoute] Guid systemId, [FromBody] IEnumerable dtos, CancellationToken token) { var userId = User.GetUserId(); - var result = await techMessagesRepository.AddRange(dtos, userId, token); + var result = await techMessagesRepository.AddRange(systemId, dtos, userId, token); return CreatedAtAction(nameof(AddRange), result); } diff --git a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs index bbf635c..ce8a7ca 100644 --- a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs @@ -14,7 +14,7 @@ public interface ITechMessagesClient : IDisposable /// /// /// - Task AddRange(IEnumerable dtos, CancellationToken token); + Task AddRange(Guid systemId, IEnumerable dtos, CancellationToken token); /// /// Получить диапазон дат, для которых есть данные в репозитории @@ -43,16 +43,16 @@ public interface ITechMessagesClient : IDisposable /// /// Получить статистику по системам /// - /// + /// /// /// /// - Task> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token); + Task> GetStatistics(IEnumerable systemIds, IEnumerable categoryIds, CancellationToken token); /// /// Получить список всех систем /// /// /// - Task> GetSystems(CancellationToken token); + Task> GetSystems(CancellationToken token); } \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs index 64cb49e..138a0cd 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs @@ -1,4 +1,5 @@ -using Persistence.Models; +using Microsoft.AspNetCore.Mvc; +using Persistence.Models; using Persistence.Models.Requests; using Refit; @@ -11,11 +12,11 @@ namespace Persistence.Client.Clients.Interfaces.Refit [Get($"{BaseRoute}")] Task>> GetPage([Query] PaginationRequest request, CancellationToken token); - [Post($"{BaseRoute}")] - Task> AddRange([Body] IEnumerable dtos, CancellationToken token); + [Post($"{BaseRoute}/{{systemId}}")] + Task> AddRange(Guid systemId, [Body] IEnumerable dtos, CancellationToken token); [Get($"{BaseRoute}/systems")] - Task>> GetSystems(CancellationToken token); + Task>> GetSystems(CancellationToken token); [Get($"{BaseRoute}/range")] Task> GetDatesRangeAsync(CancellationToken token); @@ -24,6 +25,6 @@ namespace Persistence.Client.Clients.Interfaces.Refit Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); [Get($"{BaseRoute}/statistics")] - Task>> GetStatistics([Query] string autoDrillingSystem, [Query] int categoryId, CancellationToken token); + Task>> GetStatistics([Query] IEnumerable systemIds, [Query] IEnumerable categoryIds, CancellationToken token); } } diff --git a/Persistence.Client/Clients/TechMessagesClient.cs b/Persistence.Client/Clients/TechMessagesClient.cs index c1000b1..7950784 100644 --- a/Persistence.Client/Clients/TechMessagesClient.cs +++ b/Persistence.Client/Clients/TechMessagesClient.cs @@ -24,17 +24,17 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient return result; } - public async Task AddRange(IEnumerable dtos, CancellationToken token) + public async Task AddRange(Guid systemId, IEnumerable 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> GetSystems(CancellationToken token) + public async Task> GetSystems(CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse>( async () => await refitTechMessagesClient.GetSystems(token), token); return result; @@ -56,10 +56,10 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient return result; } - public async Task> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token) + public async Task> GetStatistics(IEnumerable systemIds, IEnumerable categoryIds, CancellationToken token) { var result = await ExecuteGetResponse>( - async () => await refitTechMessagesClient.GetStatistics(autoDrillingSystem, categoryId, token), token); + async () => await refitTechMessagesClient.GetStatistics(systemIds, categoryIds, token), token); return result; } diff --git a/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.Designer.cs b/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.Designer.cs similarity index 70% rename from Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.Designer.cs rename to Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.Designer.cs index 6ed33f7..0124f24 100644 --- a/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.Designer.cs +++ b/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.Designer.cs @@ -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 { /// @@ -48,6 +48,30 @@ namespace Persistence.Database.Postgres.Migrations b.ToTable("DrillingSystem"); }); + modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b => + { + b.Property("DiscriminatorId") + .HasColumnType("uuid") + .HasComment("Дискриминатор системы"); + + b.Property("ParameterId") + .HasColumnType("integer") + .HasComment("Id параметра"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone") + .HasComment("Временная отметка"); + + b.Property("Value") + .IsRequired() + .HasColumnType("varchar(256)") + .HasComment("Значение параметра в виде строки"); + + b.HasKey("DiscriminatorId", "ParameterId", "Timestamp"); + + b.ToTable("ParameterData"); + }); + modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b => { b.Property("EventId") @@ -59,27 +83,23 @@ namespace Persistence.Database.Postgres.Migrations .HasColumnType("integer") .HasComment("Id Категории важности"); - b.Property("Depth") - .HasColumnType("double precision") - .HasComment("Глубина забоя"); + b.Property("EventState") + .HasColumnType("integer") + .HasComment("Статус события"); - b.Property("MessageText") + b.Property("SystemId") + .HasColumnType("uuid") + .HasComment("Id системы, к которой относится сообщение"); + + b.Property("Text") .IsRequired() .HasColumnType("varchar(512)") .HasComment("Текст сообщения"); - b.Property("SystemId") - .HasColumnType("uuid") - .HasComment("Id системы автобурения, к которой относится сообщение"); - b.Property("Timestamp") .HasColumnType("timestamp with time zone") .HasComment("Дата возникновения"); - b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasComment("Ключ записи"); + + b.Property("Creation") + .HasColumnType("timestamp with time zone") + .HasComment("Дата создания записи"); + + b.Property("DepthEnd") + .HasColumnType("double precision") + .HasComment("Глубина забоя на дату окончания интервала"); + + b.Property("DepthStart") + .HasColumnType("double precision") + .HasComment("Глубина забоя на дату начала интервала"); + + b.Property("IdAuthor") + .HasColumnType("uuid") + .HasComment("Автор изменения"); + + b.Property("IdDiscriminator") + .HasColumnType("uuid") + .HasComment("Дискриминатор таблицы"); + + b.Property("IdEditor") + .HasColumnType("uuid") + .HasComment("Редактор"); + + b.Property("IdNext") + .HasColumnType("uuid") + .HasComment("Id заменяющей записи"); + + b.Property("IdSection") + .HasColumnType("uuid") + .HasComment("Ключ секции"); + + b.Property("Obsolete") + .HasColumnType("timestamp with time zone") + .HasComment("Дата устаревания (например при удалении)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("jsonb") + .HasComment("Значение"); + + b.HasKey("Id"); + + b.ToTable("ChangeLog"); + }); + modelBuilder.Entity("Persistence.Database.Model.DataSaub", b => { b.Property("Date") diff --git a/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs b/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs similarity index 81% rename from Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs rename to Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs index ccf18d4..2ee7a55 100644 --- a/Persistence.Database.Postgres/Migrations/20241202072250_TechMessageMigration.cs +++ b/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs @@ -3,7 +3,7 @@ using Microsoft.EntityFrameworkCore.Migrations; #nullable disable -namespace Persistence.Database.Postgres.Migrations +namespace Persistence.Database.Postgres.Migrations.PersistencePostgres { /// public partial class TechMessageMigration : Migration @@ -31,10 +31,9 @@ namespace Persistence.Database.Postgres.Migrations EventId = table.Column(type: "uuid", nullable: false, comment: "Id события"), CategoryId = table.Column(type: "integer", nullable: false, comment: "Id Категории важности"), Timestamp = table.Column(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"), - Depth = table.Column(type: "double precision", nullable: true, comment: "Глубина забоя"), - MessageText = table.Column(type: "varchar(512)", nullable: false, comment: "Текст сообщения"), - SystemId = table.Column(type: "uuid", nullable: false, comment: "Id системы автобурения, к которой относится сообщение"), - UserId = table.Column(type: "uuid", nullable: false, comment: "Id пользователя за пультом бурильщика") + Text = table.Column(type: "varchar(512)", nullable: false, comment: "Текст сообщения"), + SystemId = table.Column(type: "uuid", nullable: false, comment: "Id системы, к которой относится сообщение"), + EventState = table.Column(type: "integer", nullable: false, comment: "Статус события") }, constraints: table => { diff --git a/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs b/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs index 6ab8159..5a67396 100644 --- a/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs +++ b/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs @@ -1,6 +1,5 @@ // using System; -using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -48,8 +47,8 @@ namespace Persistence.Database.Postgres.Migrations modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b => { - b.Property("DiscriminatorId") - .HasColumnType("integer") + b.Property("DiscriminatorId") + .HasColumnType("uuid") .HasComment("Дискриминатор системы"); b.Property("ParameterId") @@ -81,27 +80,23 @@ namespace Persistence.Database.Postgres.Migrations .HasColumnType("integer") .HasComment("Id Категории важности"); - b.Property("Depth") - .HasColumnType("double precision") - .HasComment("Глубина забоя"); + b.Property("EventState") + .HasColumnType("integer") + .HasComment("Статус события"); - b.Property("MessageText") + b.Property("SystemId") + .HasColumnType("uuid") + .HasComment("Id системы, к которой относится сообщение"); + + b.Property("Text") .IsRequired() .HasColumnType("varchar(512)") .HasComment("Текст сообщения"); - b.Property("SystemId") - .HasColumnType("uuid") - .HasComment("Id системы автобурения, к которой относится сообщение"); - b.Property("Timestamp") .HasColumnType("timestamp with time zone") .HasComment("Дата возникновения"); - b.Property("UserId") - .HasColumnType("uuid") - .HasComment("Id пользователя за пультом бурильщика"); - b.HasKey("EventId"); b.HasIndex("SystemId"); @@ -137,48 +132,48 @@ namespace Persistence.Database.Postgres.Migrations b.Property("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid") - .HasColumnName("Id"); + .HasComment("Ключ записи"); b.Property("Creation") .HasColumnType("timestamp with time zone") - .HasColumnName("Creation"); + .HasComment("Дата создания записи"); b.Property("DepthEnd") .HasColumnType("double precision") - .HasColumnName("DepthEnd"); + .HasComment("Глубина забоя на дату окончания интервала"); b.Property("DepthStart") .HasColumnType("double precision") - .HasColumnName("DepthStart"); + .HasComment("Глубина забоя на дату начала интервала"); b.Property("IdAuthor") .HasColumnType("uuid") - .HasColumnName("IdAuthor"); + .HasComment("Автор изменения"); b.Property("IdDiscriminator") .HasColumnType("uuid") - .HasColumnName("IdDiscriminator"); + .HasComment("Дискриминатор таблицы"); b.Property("IdEditor") .HasColumnType("uuid") - .HasColumnName("IdEditor"); + .HasComment("Редактор"); b.Property("IdNext") .HasColumnType("uuid") - .HasColumnName("IdNext"); + .HasComment("Id заменяющей записи"); b.Property("IdSection") .HasColumnType("uuid") - .HasColumnName("IdSection"); + .HasComment("Ключ секции"); b.Property("Obsolete") .HasColumnType("timestamp with time zone") - .HasColumnName("Obsolete"); + .HasComment("Дата устаревания (например при удалении)"); - b.Property>("Value") + b.Property("Value") .IsRequired() .HasColumnType("jsonb") - .HasColumnName("Value"); + .HasComment("Значение"); b.HasKey("Id"); diff --git a/Persistence.Database/Entity/TechMessage.cs b/Persistence.Database/Entity/TechMessage.cs index ea29cc2..5c8b534 100644 --- a/Persistence.Database/Entity/TechMessage.cs +++ b/Persistence.Database/Entity/TechMessage.cs @@ -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 MessageText { get; set; } + public required string Text { get; set; } - [Required, Comment("Id системы автобурения, к которой относится сообщение")] + [Required, Comment("Id системы, к которой относится сообщение")] public required Guid SystemId { 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; } } } diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index 3501f87..6ad95b3 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -4,6 +4,7 @@ using Persistence.Client; using Persistence.Client.Clients.Interfaces; using Persistence.Database.Entity; using Persistence.Models; +using Persistence.Models.Enumerations; using Persistence.Models.Requests; using Xunit; @@ -53,7 +54,7 @@ namespace Persistence.IntegrationTests.Controllers public async Task GetPage_AfterSave_returns_success() { //arrange - var dtos = await InsertRange(); + var dtos = await InsertRange(Guid.NewGuid()); var dtosCount = dtos.Count(); var requestDto = new PaginationRequest() { @@ -73,7 +74,7 @@ namespace Persistence.IntegrationTests.Controllers [Fact] public async Task InsertRange_returns_success() { - await InsertRange(); + await InsertRange(Guid.NewGuid()); } [Fact] @@ -81,6 +82,7 @@ namespace Persistence.IntegrationTests.Controllers { //arrange const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса"; + var systemId = Guid.NewGuid(); var dtos = new List() { new TechMessageDto() @@ -88,17 +90,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, new CancellationToken()); } catch (Exception ex) { @@ -127,19 +127,15 @@ namespace Persistence.IntegrationTests.Controllers public async Task GetSystems_AfterSave_returns_success() { //arrange - var dtos = await InsertRange(); - var systems = dtos - .Select(e => e.System) - .Distinct() - .ToArray(); + var dtos = await InsertRange(Guid.NewGuid()); //act var response = await techMessagesClient.GetSystems(CancellationToken.None); //assert Assert.NotNull(response); - string?[]? content = response?.ToArray(); - Assert.Equal(systems, content); + var expectedSystemCount = 1; + Assert.Equal(expectedSystemCount, response!.Count()); } [Fact] @@ -150,11 +146,11 @@ namespace Persistence.IntegrationTests.Controllers dbContext.CleanupDbSet(); dbContext.CleanupDbSet(); - var imortantId = 1; - var autoDrillingSystem = nameof(TechMessageDto.System); + var imortantIds = new [] { 1 }; + var systemIds = new [] { Guid.NewGuid() }; //act - var response = await techMessagesClient.GetStatistics(autoDrillingSystem, imortantId, CancellationToken.None); + var response = await techMessagesClient.GetStatistics(systemIds, imortantIds, CancellationToken.None); //assert Assert.NotNull(response); @@ -165,19 +161,20 @@ namespace Persistence.IntegrationTests.Controllers public async Task GetStatistics_AfterSave_returns_success() { //arrange - var imortantId = 0; - var autoDrillingSystem = nameof(TechMessageDto.System); - var dtos = await InsertRange(); - var filteredDtos = dtos.Where(e => e.CategoryId == imortantId && e.System == autoDrillingSystem); + 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(autoDrillingSystem, imortantId, CancellationToken.None); + var response = await techMessagesClient.GetStatistics([systemId], categoryIds, CancellationToken.None); //assert Assert.NotNull(response); + Assert.NotEmpty(response); var categories = response - .FirstOrDefault()?.Categories - .FirstOrDefault(e => e.Key == 0).Value; + .FirstOrDefault()!.Categories + .Count(); Assert.Equal(filteredDtos.Count(), categories); } @@ -202,7 +199,7 @@ namespace Persistence.IntegrationTests.Controllers public async Task GetDatesRange_AfterSave_returns_success() { //arrange - await InsertRange(); + await InsertRange(Guid.NewGuid()); //act var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); @@ -234,7 +231,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange var dateBegin = DateTimeOffset.UtcNow; var take = 1; - await InsertRange(); + await InsertRange(Guid.NewGuid()); //act var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None); @@ -244,7 +241,7 @@ namespace Persistence.IntegrationTests.Controllers Assert.NotEmpty(response); } - private async Task> InsertRange() + private async Task> InsertRange(Guid systemId) { //arrange memoryCache.Remove(SystemCacheKey); @@ -258,26 +255,22 @@ namespace Persistence.IntegrationTests.Controllers EventId = Guid.NewGuid(), CategoryId = 1, Timestamp = DateTimeOffset.UtcNow, - Depth = 1.11, - MessageText = nameof(TechMessageDto.MessageText), - System = nameof(TechMessageDto.System).ToLower(), - UserId = Guid.NewGuid() + Text = nameof(TechMessageDto.Text), + EventState = Models.Enumerations.EventState.Triggered }, new TechMessageDto() { EventId = Guid.NewGuid(), CategoryId = 2, Timestamp = DateTimeOffset.UtcNow, - Depth = 2.22, - MessageText = nameof(TechMessageDto.MessageText), - System = nameof(TechMessageDto.System).ToLower(), - UserId = Guid.NewGuid() + Text = nameof(TechMessageDto.Text), + EventState = Models.Enumerations.EventState.Triggered } }; //act - var response = await techMessagesClient.AddRange(dtos, CancellationToken.None); + var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None); //assert Assert.Equal(dtos.Count, response); diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index 4659da0..3779892 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -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; @@ -50,12 +51,11 @@ namespace Persistence.Repository.Repositories return dto; } - public async Task> GetStatistics(IEnumerable autoDrillingSystem, IEnumerable categoryIds, CancellationToken token) + public async Task> GetStatistics(IEnumerable systems, IEnumerable categoryIds, CancellationToken token) { var query = GetQueryReadOnly(); - var systems = autoDrillingSystem.Select(s => s.ToLower().Trim()); var result = await query - .Where(e => systems.Count() == 0 || systems.Contains(e.System.Name.ToLower().Trim())) + .Where(e => systems.Count() == 0 || systems.Contains(e.System.SystemId)) .GroupBy(e => e.System.Name, (key, group) => new { System = key, @@ -81,27 +81,16 @@ namespace Persistence.Repository.Repositories return entities; } - public async Task> GetSystems(CancellationToken token) - { - var entities = await GetDrillingSystems(token); - var result = entities.Select(e => e.Name); - - return result; - } - - public async Task AddRange(IEnumerable dtos, Guid userId, CancellationToken token) + public async Task AddRange(Guid systemId, IEnumerable dtos, Guid userId, CancellationToken token) { var entities = new List(); foreach (var dto in dtos) { var entity = dto.Adapt(); - var systems = await GetDrillingSystems(token); - var systemId = systems.FirstOrDefault(e => e.Name.ToLower().Trim() == dto.System.ToLower().Trim())?.SystemId - ?? await CreateDrillingSystem(dto.System, token); + await CreateSystemIfNotExist(systemId, token); entity.SystemId = systemId; - entity.UserId = userId; entities.Add(entity); } @@ -125,6 +114,22 @@ namespace Persistence.Repository.Repositories return dtos; } + public async Task> GetSystems(CancellationToken token) + { + var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => + { + f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); + + var query = db.Set(); + var entities = await query.ToListAsync(token); + var dtos = entities.Select(e => e.Adapt()); + + return dtos; + }); + + return systems ?? []; + } + public async Task GetDatesRangeAsync(CancellationToken token) { var query = GetQueryReadOnly() @@ -144,35 +149,26 @@ namespace Persistence.Repository.Repositories return result; } - private async Task> GetDrillingSystems(CancellationToken token) + private async Task CreateSystemIfNotExist(Guid systemId, CancellationToken token) { - var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => + var systems = await GetSystems(token); + var system = systems?.FirstOrDefault(e => e.SystemId == systemId); + + if (system == null) { - f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); + system = new DrillingSystemDto() + { + SystemId = systemId, + Name = string.Empty + }; - var query = db.Set(); - var entities = await query.ToListAsync(token); - var dtos = entities.Select(e => e.Adapt()); + var entity = system.Adapt(); - return dtos; - }); + await db.Set().AddAsync(entity); + await db.SaveChangesAsync(token); - return systems!; - } - private async Task CreateDrillingSystem(string name, CancellationToken token) - { - memoryCache.Remove(SystemCacheKey); - - var entity = new Database.Entity.DrillingSystem() - { - SystemId = default, - Name = name.ToLower().Trim() - }; - - await db.Set().AddAsync(entity); - await db.SaveChangesAsync(token); - - return entity.SystemId; + memoryCache.Remove(SystemCacheKey); + } } } } diff --git a/Persistence/Models/Enumerations/EventState.cs b/Persistence/Models/Enumerations/EventState.cs new file mode 100644 index 0000000..3f4103c --- /dev/null +++ b/Persistence/Models/Enumerations/EventState.cs @@ -0,0 +1,6 @@ +namespace Persistence.Models.Enumerations; +public enum EventState +{ + NotTriggered = 0, + Triggered = 1, +} diff --git a/Persistence/Models/TechMessageDto.cs b/Persistence/Models/TechMessageDto.cs index 84da656..f429fe7 100644 --- a/Persistence/Models/TechMessageDto.cs +++ b/Persistence/Models/TechMessageDto.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using Persistence.Models.Enumerations; namespace Persistence.Models { @@ -24,29 +25,16 @@ namespace Persistence.Models /// public DateTimeOffset Timestamp { get; set; } - /// - /// Глубина забоя - /// - [Range(0, double.MaxValue, ErrorMessage = "Глубина забоя не может быть меньше 0")] - public double? Depth { get; set; } - /// /// Текст сообщения /// [Required] [StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")] - public required string MessageText { get; set; } + public required string Text { get; set; } /// - /// Система автобурения, к которой относится сообщение + /// Статус события /// - [Required] - [StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина наименования системы АБ от 1 до 256 символов")] - public required string System { get; set; } - - /// - /// Id пользователя за пультом бурильщика - /// - public Guid UserId { get; set; } + public EventState EventState { get; set; } } } diff --git a/Persistence/Repositories/ITechMessagesRepository.cs b/Persistence/Repositories/ITechMessagesRepository.cs index ae92912..c442e94 100644 --- a/Persistence/Repositories/ITechMessagesRepository.cs +++ b/Persistence/Repositories/ITechMessagesRepository.cs @@ -22,14 +22,14 @@ namespace Persistence.Repositories /// /// /// - Task AddRange(IEnumerable dtos, Guid userId, CancellationToken token); + Task AddRange(Guid systemId, IEnumerable dtos, Guid userId, CancellationToken token); /// - /// Получение списка уникальных названий систем АБ + /// Получение списка систем /// /// /// - Task> GetSystems(CancellationToken token); + Task> GetSystems(CancellationToken token); /// /// Получение количества сообщений по категориям и системам автобурения @@ -38,7 +38,7 @@ namespace Persistence.Repositories /// Система автобурения /// /// - Task> GetStatistics(IEnumerable autoDrillingSystem, IEnumerable categoryIds, CancellationToken token); + Task> GetStatistics(IEnumerable autoDrillingSystem, IEnumerable categoryIds, CancellationToken token); /// /// Получить порцию записей, начиная с заданной даты From a2b1d2e0c98bb59626bd6555e5c3898b18a046a9 Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Thu, 12 Dec 2024 17:05:47 +0500 Subject: [PATCH 2/7] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D1=85=D1=80=D0=B0=D0=BD=D0=B5=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8=D0=B9=20=D0=B8=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D1=87=D0=BD=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=B4=D0=B0?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=D1=85=20=D0=BE=D1=82=20=D1=81=D0=B8=D1=81?= =?UTF-8?q?=D1=82=D0=B5=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/DataSourceSystemController.cs | 51 ++++++++++++ .../Clients/DataSourceSystemClient.cs | 35 ++++++++ .../Interfaces/IDataSourceSystemClient.cs | 25 ++++++ .../Clients/Interfaces/ITechMessagesClient.cs | 2 +- .../Refit/IRefitDataSourceSystemClient.cs | 14 ++++ .../Refit/IRefitTechMessagesClient.cs | 2 +- .../Clients/TechMessagesClient.cs | 4 +- .../PersistenceClientFactory.cs | 14 ++++ Persistence.Client/Readme.md | 1 + ...{DrillingSystem.cs => DataSourceSystem.cs} | 8 +- Persistence.Database/Entity/TechMessage.cs | 4 +- Persistence.Database/PersistenceDbContext.cs | 2 + .../DataSourceSystemControllerTest.cs | 82 +++++++++++++++++++ .../Controllers/TechMessagesControllerTest.cs | 12 +-- Persistence.Repository/DependencyInjection.cs | 3 +- .../DataSourceSystemRepository.cs | 53 ++++++++++++ .../Repositories/TechMessagesRepository.cs | 14 ++-- ...ingSystemDto.cs => DataSourceSystemDto.cs} | 6 +- .../IDataSourceSystemRepository.cs | 22 +++++ .../Repositories/ITechMessagesRepository.cs | 2 +- 20 files changed, 328 insertions(+), 28 deletions(-) create mode 100644 Persistence.API/Controllers/DataSourceSystemController.cs create mode 100644 Persistence.Client/Clients/DataSourceSystemClient.cs create mode 100644 Persistence.Client/Clients/Interfaces/IDataSourceSystemClient.cs create mode 100644 Persistence.Client/Clients/Interfaces/Refit/IRefitDataSourceSystemClient.cs rename Persistence.Database/Entity/{DrillingSystem.cs => DataSourceSystem.cs} (63%) create mode 100644 Persistence.IntegrationTests/Controllers/DataSourceSystemControllerTest.cs create mode 100644 Persistence.Repository/Repositories/DataSourceSystemRepository.cs rename Persistence/Models/{DrillingSystemDto.cs => DataSourceSystemDto.cs} (70%) create mode 100644 Persistence/Repositories/IDataSourceSystemRepository.cs diff --git a/Persistence.API/Controllers/DataSourceSystemController.cs b/Persistence.API/Controllers/DataSourceSystemController.cs new file mode 100644 index 0000000..599c11e --- /dev/null +++ b/Persistence.API/Controllers/DataSourceSystemController.cs @@ -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; + +/// +/// Работа с системами +/// +[ApiController] +[Authorize] +[Route("api/[controller]")] +public class DataSourceSystemController : ControllerBase +{ + private readonly IDataSourceSystemRepository dataSourceSystemRepository; + + public DataSourceSystemController(IDataSourceSystemRepository dataSourceSystemRepository) + { + this.dataSourceSystemRepository = dataSourceSystemRepository; + } + + /// + /// Получить системы + /// + /// + /// + [HttpGet] + public async Task> Get(CancellationToken token) + { + var result = await dataSourceSystemRepository.Get(token); + + return Ok(result); + } + + /// + /// Добавить систему + /// + /// + /// + /// + [HttpPost] + [ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)] + public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token) + { + await dataSourceSystemRepository.Add(dataSourceSystemDto, token); + + return CreatedAtAction(nameof(Add), true); + } +} diff --git a/Persistence.Client/Clients/DataSourceSystemClient.cs b/Persistence.Client/Clients/DataSourceSystemClient.cs new file mode 100644 index 0000000..fbec180 --- /dev/null +++ b/Persistence.Client/Clients/DataSourceSystemClient.cs @@ -0,0 +1,35 @@ +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 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> Get(CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await dataSourceSystemClient.Get(token), token); + + return result; + } + + public void Dispose() + { + dataSourceSystemClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/Interfaces/IDataSourceSystemClient.cs b/Persistence.Client/Clients/Interfaces/IDataSourceSystemClient.cs new file mode 100644 index 0000000..fc25412 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/IDataSourceSystemClient.cs @@ -0,0 +1,25 @@ +using Persistence.Models; +using Refit; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с системами +/// +public interface IDataSourceSystemClient : IDisposable +{ + /// + /// Получить системы + /// + /// + /// + Task> Get(CancellationToken token); + + /// + /// Добавить систему + /// + /// + /// + /// + Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token); +} diff --git a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs index ce8a7ca..3cd0d92 100644 --- a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs @@ -54,5 +54,5 @@ public interface ITechMessagesClient : IDisposable /// /// /// - Task> GetSystems(CancellationToken token); + Task> GetSystems(CancellationToken token); } \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitDataSourceSystemClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitDataSourceSystemClient.cs new file mode 100644 index 0000000..ba20504 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitDataSourceSystemClient.cs @@ -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>> Get(CancellationToken token); + + [Post($"{BaseRoute}")] + Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token); +} diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs index 138a0cd..6937ff7 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs @@ -16,7 +16,7 @@ namespace Persistence.Client.Clients.Interfaces.Refit Task> AddRange(Guid systemId, [Body] IEnumerable dtos, CancellationToken token); [Get($"{BaseRoute}/systems")] - Task>> GetSystems(CancellationToken token); + Task>> GetSystems(CancellationToken token); [Get($"{BaseRoute}/range")] Task> GetDatesRangeAsync(CancellationToken token); diff --git a/Persistence.Client/Clients/TechMessagesClient.cs b/Persistence.Client/Clients/TechMessagesClient.cs index 7950784..d097451 100644 --- a/Persistence.Client/Clients/TechMessagesClient.cs +++ b/Persistence.Client/Clients/TechMessagesClient.cs @@ -32,9 +32,9 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient return result; } - public async Task> GetSystems(CancellationToken token) + public async Task> GetSystems(CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse>( async () => await refitTechMessagesClient.GetSystems(token), token); return result; diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs index c77ac04..5374e21 100644 --- a/Persistence.Client/PersistenceClientFactory.cs +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -128,5 +128,19 @@ namespace Persistence.Client return client; } + + /// + /// Получить клиент для работы c системами + /// + /// + public IDataSourceSystemClient GetDataSourceSystemClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new DataSourceSystemClient(restClient, logger); + + return client; + } } } diff --git a/Persistence.Client/Readme.md b/Persistence.Client/Readme.md index e9f4024..f7c35f6 100644 --- a/Persistence.Client/Readme.md +++ b/Persistence.Client/Readme.md @@ -15,6 +15,7 @@ Persistence сервисом посредством обращения к кон - `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени - `IChangeLogClient` - Клиент для работы с записями ChangeLog - `IWitsDataClient` - Клиент для работы с параметрами Wits +- `IDataSourceSystemClient` - Клиент для работы с системами ## Использование Для получения того или иного Persistence - клиента нужно diff --git a/Persistence.Database/Entity/DrillingSystem.cs b/Persistence.Database/Entity/DataSourceSystem.cs similarity index 63% rename from Persistence.Database/Entity/DrillingSystem.cs rename to Persistence.Database/Entity/DataSourceSystem.cs index 6588fb0..a0bf0c7 100644 --- a/Persistence.Database/Entity/DrillingSystem.cs +++ b/Persistence.Database/Entity/DataSourceSystem.cs @@ -3,14 +3,14 @@ using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; namespace Persistence.Database.Entity; -public class DrillingSystem +public class DataSourceSystem { - [Key, Comment("Id системы автобурения")] + [Key, Comment("Id системы")] public Guid SystemId { get; set; } - [Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы автобурения")] + [Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы")] public required string Name { get; set; } - [Comment("Описание системы автобурения")] + [Comment("Описание системы")] public string? Description { get; set; } } diff --git a/Persistence.Database/Entity/TechMessage.cs b/Persistence.Database/Entity/TechMessage.cs index 5c8b534..6abe718 100644 --- a/Persistence.Database/Entity/TechMessage.cs +++ b/Persistence.Database/Entity/TechMessage.cs @@ -21,8 +21,8 @@ namespace Persistence.Database.Entity [Required, Comment("Id системы, к которой относится сообщение")] public required Guid SystemId { get; set; } - [Required, ForeignKey(nameof(SystemId)), Comment("Система автобурения, к которой относится сообщение")] - public virtual required DrillingSystem System { get; set; } + [Required, ForeignKey(nameof(SystemId)), Comment("Система, к которой относится сообщение")] + public virtual required DataSourceSystem System { get; set; } [Comment("Статус события")] public int EventState { get; set; } diff --git a/Persistence.Database/PersistenceDbContext.cs b/Persistence.Database/PersistenceDbContext.cs index 849865d..6e6c8ec 100644 --- a/Persistence.Database/PersistenceDbContext.cs +++ b/Persistence.Database/PersistenceDbContext.cs @@ -21,6 +21,8 @@ public class PersistenceDbContext : DbContext public DbSet ParameterData => Set(); + public DbSet DataSourceSystem => Set(); + public PersistenceDbContext(DbContextOptions options) : base(options) { diff --git a/Persistence.IntegrationTests/Controllers/DataSourceSystemControllerTest.cs b/Persistence.IntegrationTests/Controllers/DataSourceSystemControllerTest.cs new file mode 100644 index 0000000..8638e90 --- /dev/null +++ b/Persistence.IntegrationTests/Controllers/DataSourceSystemControllerTest.cs @@ -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(); + + dataSourceSystemClient = persistenceClientFactory.GetDataSourceSystemClient(); + memoryCache = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task Get_returns_success() + { + //arrange + memoryCache.Remove(SystemCacheKey); + dbContext.CleanupDbSet(); + + //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(); + + var dto = new DataSourceSystemDto() + { + SystemId = Guid.NewGuid(), + Name = "Test", + Description = "Test" + }; + + //act + await dataSourceSystemClient.Add(dto, CancellationToken.None); + } + } +} diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index 6ad95b3..4d191a6 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -12,7 +12,7 @@ namespace Persistence.IntegrationTests.Controllers { public class TechMessagesControllerTest : BaseIntegrationTest { - private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey"; + 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) @@ -31,7 +31,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); var requestDto = new PaginationRequest() { @@ -113,7 +113,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); //act var response = await techMessagesClient.GetSystems(CancellationToken.None); @@ -144,7 +144,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); var imortantIds = new [] { 1 }; var systemIds = new [] { Guid.NewGuid() }; @@ -184,7 +184,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); //act var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); @@ -246,7 +246,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); var dtos = new List() { diff --git a/Persistence.Repository/DependencyInjection.cs b/Persistence.Repository/DependencyInjection.cs index 7a96217..b694775 100644 --- a/Persistence.Repository/DependencyInjection.cs +++ b/Persistence.Repository/DependencyInjection.cs @@ -35,7 +35,8 @@ public static class DependencyInjection services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - return services; + return services; } } diff --git a/Persistence.Repository/Repositories/DataSourceSystemRepository.cs b/Persistence.Repository/Repositories/DataSourceSystemRepository.cs new file mode 100644 index 0000000..174a1af --- /dev/null +++ b/Persistence.Repository/Repositories/DataSourceSystemRepository.cs @@ -0,0 +1,53 @@ +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 +{ + private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey"; + private DbContext db; + private readonly IMemoryCache memoryCache; + private const int CacheExpirationInMinutes = 60; + public DataSourceSystemRepository(DbContext db, IMemoryCache memoryCache) + { + this.db = db; + this.memoryCache = memoryCache; + } + protected virtual IQueryable GetQueryReadOnly() => db.Set(); + + public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token) + { + var entity = dataSourceSystemDto.Adapt(); + + await db.Set().AddAsync(entity); + await db.SaveChangesAsync(token); + + memoryCache.Remove(SystemCacheKey); + } + + public async Task> Get(CancellationToken token) + { + var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => + { + f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); + + var query = GetQueryReadOnly(); + var entities = await query.ToListAsync(token); + var dtos = entities.Select(e => e.Adapt()); + + return dtos; + }); + + return systems ?? []; + } +} diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index 3779892..f2fa333 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -12,7 +12,7 @@ namespace Persistence.Repository.Repositories { public class TechMessagesRepository : ITechMessagesRepository { - private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey"; + private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey"; private const int CacheExpirationInMinutes = 60; private readonly IMemoryCache memoryCache; private DbContext db; @@ -114,15 +114,15 @@ namespace Persistence.Repository.Repositories return dtos; } - public async Task> GetSystems(CancellationToken token) + public async Task> GetSystems(CancellationToken token) { var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => { f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); - var query = db.Set(); + var query = db.Set(); var entities = await query.ToListAsync(token); - var dtos = entities.Select(e => e.Adapt()); + var dtos = entities.Select(e => e.Adapt()); return dtos; }); @@ -156,15 +156,15 @@ namespace Persistence.Repository.Repositories if (system == null) { - system = new DrillingSystemDto() + system = new DataSourceSystemDto() { SystemId = systemId, Name = string.Empty }; - var entity = system.Adapt(); + var entity = system.Adapt(); - await db.Set().AddAsync(entity); + await db.Set().AddAsync(entity); await db.SaveChangesAsync(token); memoryCache.Remove(SystemCacheKey); diff --git a/Persistence/Models/DrillingSystemDto.cs b/Persistence/Models/DataSourceSystemDto.cs similarity index 70% rename from Persistence/Models/DrillingSystemDto.cs rename to Persistence/Models/DataSourceSystemDto.cs index c2e7abc..c4af908 100644 --- a/Persistence/Models/DrillingSystemDto.cs +++ b/Persistence/Models/DataSourceSystemDto.cs @@ -1,9 +1,9 @@ namespace Persistence.Models; /// -/// Модель системы автобурения +/// Модель системы /// -public class DrillingSystemDto +public class DataSourceSystemDto { /// /// Ключ @@ -13,7 +13,7 @@ public class DrillingSystemDto /// /// Наименование /// - public required string Name { get; set; } + public required string Name { get; set; } = string.Empty; /// /// Описание diff --git a/Persistence/Repositories/IDataSourceSystemRepository.cs b/Persistence/Repositories/IDataSourceSystemRepository.cs new file mode 100644 index 0000000..1d964eb --- /dev/null +++ b/Persistence/Repositories/IDataSourceSystemRepository.cs @@ -0,0 +1,22 @@ +using Persistence.Models; + +namespace Persistence.Repositories; + +/// +/// Интерфейс по работе с системами +/// +public interface IDataSourceSystemRepository +{ + /// + /// Добавить систему + /// + /// + /// + public Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token); + + /// + /// Получить список систем + /// + /// + public Task> Get(CancellationToken token); +} diff --git a/Persistence/Repositories/ITechMessagesRepository.cs b/Persistence/Repositories/ITechMessagesRepository.cs index c442e94..11c48fc 100644 --- a/Persistence/Repositories/ITechMessagesRepository.cs +++ b/Persistence/Repositories/ITechMessagesRepository.cs @@ -29,7 +29,7 @@ namespace Persistence.Repositories /// /// /// - Task> GetSystems(CancellationToken token); + Task> GetSystems(CancellationToken token); /// /// Получение количества сообщений по категориям и системам автобурения From ba75f2c8883baae4dd3570d1eb611f2aafb6c791 Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Fri, 13 Dec 2024 10:54:47 +0500 Subject: [PATCH 3/7] =?UTF-8?q?=D0=92=D1=8B=D0=B4=D0=B5=D0=BB=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9?= =?UTF-8?q?=20Cached=20=D1=80=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B8=D0=B9=20=D0=B4=D0=BB=D1=8F=20=D1=81=D0=B8=D1=81?= =?UTF-8?q?=D1=82=D0=B5=D0=BC=20-=20=D0=B8=D1=81=D1=82=D0=BE=D1=87=D0=BD?= =?UTF-8?q?=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Persistence.Repository/DependencyInjection.cs | 2 +- .../DataSourceSystemCachedRepository.cs | 34 +++++++++++++++++++ .../DataSourceSystemRepository.cs | 29 +++++----------- .../Repositories/TechMessagesRepository.cs | 33 +++++------------- 4 files changed, 51 insertions(+), 47 deletions(-) create mode 100644 Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs diff --git a/Persistence.Repository/DependencyInjection.cs b/Persistence.Repository/DependencyInjection.cs index 2b8c06a..a7db05e 100644 --- a/Persistence.Repository/DependencyInjection.cs +++ b/Persistence.Repository/DependencyInjection.cs @@ -34,7 +34,7 @@ public static class DependencyInjection services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); return services; } diff --git a/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs b/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs new file mode 100644 index 0000000..11a08dd --- /dev/null +++ b/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs @@ -0,0 +1,34 @@ +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; + + 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> Get(CancellationToken token) + { + var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => + { + var dtos = await base.Get(token); + + return dtos; + }); + + return systems ?? []; + } +} diff --git a/Persistence.Repository/Repositories/DataSourceSystemRepository.cs b/Persistence.Repository/Repositories/DataSourceSystemRepository.cs index 174a1af..9fade43 100644 --- a/Persistence.Repository/Repositories/DataSourceSystemRepository.cs +++ b/Persistence.Repository/Repositories/DataSourceSystemRepository.cs @@ -14,40 +14,27 @@ using Persistence.Repositories; namespace Persistence.Repository.Repositories; public class DataSourceSystemRepository : IDataSourceSystemRepository { - private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey"; - private DbContext db; - private readonly IMemoryCache memoryCache; - private const int CacheExpirationInMinutes = 60; - public DataSourceSystemRepository(DbContext db, IMemoryCache memoryCache) + protected DbContext db; + public DataSourceSystemRepository(DbContext db) { this.db = db; - this.memoryCache = memoryCache; } protected virtual IQueryable GetQueryReadOnly() => db.Set(); - public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token) + public virtual async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token) { var entity = dataSourceSystemDto.Adapt(); await db.Set().AddAsync(entity); await db.SaveChangesAsync(token); - - memoryCache.Remove(SystemCacheKey); } - public async Task> Get(CancellationToken token) + public virtual async Task> Get(CancellationToken token) { - var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => - { - f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); + var query = GetQueryReadOnly(); + var entities = await query.ToListAsync(token); + var dtos = entities.Select(e => e.Adapt()); - var query = GetQueryReadOnly(); - var entities = await query.ToListAsync(token); - var dtos = entities.Select(e => e.Adapt()); - - return dtos; - }); - - return systems ?? []; + return dtos; } } diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index 6ba7ff9..f542265 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -12,15 +12,13 @@ namespace Persistence.Repository.Repositories { public class TechMessagesRepository : ITechMessagesRepository { - private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey"; - private const int CacheExpirationInMinutes = 60; - private readonly IMemoryCache memoryCache; + 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 GetQueryReadOnly() => db.Set() @@ -116,18 +114,9 @@ namespace Persistence.Repository.Repositories public async Task> GetSystems(CancellationToken token) { - var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => - { - f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes); + var systems = await sourceSystemRepository.Get(token); - var query = db.Set(); - var entities = await query.ToListAsync(token); - var dtos = entities.Select(e => e.Adapt()); - - return dtos; - }); - - return systems ?? []; + return systems ?? []; } public async Task GetDatesRangeAsync(CancellationToken token) @@ -151,7 +140,7 @@ namespace Persistence.Repository.Repositories private async Task CreateSystemIfNotExist(Guid systemId, CancellationToken token) { - var systems = await GetSystems(token); + var systems = await sourceSystemRepository.Get(token); var system = systems?.FirstOrDefault(e => e.SystemId == systemId); if (system == null) @@ -161,14 +150,8 @@ namespace Persistence.Repository.Repositories SystemId = systemId, Name = string.Empty }; - - var entity = system.Adapt(); - - await db.Set().AddAsync(entity); - await db.SaveChangesAsync(token); - - memoryCache.Remove(SystemCacheKey); - } + await sourceSystemRepository.Add(system, token); + } } } } From 8f76400d77297ecc151c91853f6874fa256a06c2 Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Fri, 13 Dec 2024 11:00:41 +0500 Subject: [PATCH 4/7] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BC=D0=B8=D0=B3=D1=80=D0=B0=D1=86=D0=B8=D1=8E=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=87=D0=B0=D1=81=D1=82=D0=B8=20DataSourceSyste?= =?UTF-8?q?m?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../20241212041758_TechMessageMigration.cs | 16 ++++++++-------- .../PersistencePostgresContextModelSnapshot.cs | 12 ++++++------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs b/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs index c6806a4..c0066ae 100644 --- a/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs +++ b/Persistence.Database.Postgres/Migrations/20241212041758_TechMessageMigration.cs @@ -11,16 +11,16 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( - name: "DrillingSystem", + name: "DataSourceSystem", columns: table => new { - SystemId = table.Column(type: "uuid", nullable: false, comment: "Id системы автобурения"), - Name = table.Column(type: "varchar(256)", nullable: false, comment: "Наименование системы автобурения"), - Description = table.Column(type: "text", nullable: true, comment: "Описание системы автобурения") + SystemId = table.Column(type: "uuid", nullable: false, comment: "Id системы - источника данных"), + Name = table.Column(type: "varchar(256)", nullable: false, comment: "Наименование системы - источника данных"), + Description = table.Column(type: "text", nullable: true, comment: "Описание системы - источника данных") }, constraints: table => { - table.PrimaryKey("PK_DrillingSystem", x => x.SystemId); + table.PrimaryKey("PK_DataSourceSystem", x => x.SystemId); }); migrationBuilder.CreateTable( @@ -38,9 +38,9 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres { 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); }); @@ -58,7 +58,7 @@ namespace Persistence.Database.Postgres.Migrations.PersistencePostgres name: "TechMessage"); migrationBuilder.DropTable( - name: "DrillingSystem"); + name: "DataSourceSystem"); } } } diff --git a/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs b/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs index 5a67396..f233af8 100644 --- a/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs +++ b/Persistence.Database.Postgres/Migrations/PersistencePostgresContextModelSnapshot.cs @@ -24,25 +24,25 @@ 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("SystemId") .ValueGeneratedOnAdd() .HasColumnType("uuid") - .HasComment("Id системы автобурения"); + .HasComment("Id системы - источника данных"); b.Property("Description") .HasColumnType("text") - .HasComment("Описание системы автобурения"); + .HasComment("Описание системы - источника данных"); b.Property("Name") .IsRequired() .HasColumnType("varchar(256)") - .HasComment("Наименование системы автобурения"); + .HasComment("Наименование системы - источника данных"); b.HasKey("SystemId"); - b.ToTable("DrillingSystem"); + b.ToTable("DataSourceSystem"); }); modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b => @@ -289,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) From c589cbcd0d3b93835b13bed6add48d6eb46ce1ad Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Fri, 13 Dec 2024 11:01:53 +0500 Subject: [PATCH 5/7] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=82=D1=8C=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D0=B8=20=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D0=B8?= =?UTF-8?q?=20DataSourceSystem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Persistence.Database/Entity/DataSourceSystem.cs | 6 +++--- Persistence/Models/DataSourceSystemDto.cs | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Persistence.Database/Entity/DataSourceSystem.cs b/Persistence.Database/Entity/DataSourceSystem.cs index 160c903..a2fcaf9 100644 --- a/Persistence.Database/Entity/DataSourceSystem.cs +++ b/Persistence.Database/Entity/DataSourceSystem.cs @@ -5,12 +5,12 @@ using System.ComponentModel.DataAnnotations.Schema; namespace Persistence.Database.Entity; public class DataSourceSystem { - [Key, Comment("Id системы")] + [Key, Comment("Id системы - источника данных")] public Guid SystemId { get; set; } - [Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы")] + [Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы - источника данных")] public required string Name { get; set; } - [Comment("Описание системы")] + [Comment("Описание системы - источника данных")] public string? Description { get; set; } } diff --git a/Persistence/Models/DataSourceSystemDto.cs b/Persistence/Models/DataSourceSystemDto.cs index 8c47217..56df611 100644 --- a/Persistence/Models/DataSourceSystemDto.cs +++ b/Persistence/Models/DataSourceSystemDto.cs @@ -1,7 +1,7 @@ namespace Persistence.Models; /// -/// Модель системы +/// Модель системы - источника данных /// public class DataSourceSystemDto { @@ -10,10 +10,10 @@ public class DataSourceSystemDto /// public Guid SystemId { get; set; } - /// - /// Наименование - /// - public required string Name { get; set; } = string.Empty; + /// + /// Наименование + /// + public required string Name { get; set; } = string.Empty; /// /// Описание From 10aa5dd36f22690e58677a6e8b5d36b3a6d14572 Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Fri, 13 Dec 2024 15:30:11 +0500 Subject: [PATCH 6/7] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=20=D1=80=D0=B5=D0=B2=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/TechMessagesController.cs | 2 +- Persistence.Client/Clients/ChangeLogClient.cs | 12 +++++++----- .../Clients/DataSourceSystemClient.cs | 6 ++++-- .../Clients/Interfaces/ITechMessagesClient.cs | 2 +- .../Interfaces/Refit/IRefitTechMessagesClient.cs | 2 +- Persistence.Client/Clients/SetpointClient.cs | 14 ++++++++------ Persistence.Client/Clients/TechMessagesClient.cs | 14 ++++++++------ Persistence.Client/Clients/TimeSeriesClient.cs | 10 ++++++---- .../Clients/TimestampedSetClient.cs | 12 +++++++----- Persistence.Client/Clients/WitsDataClient.cs | 10 ++++++---- .../Controllers/TechMessagesControllerTest.cs | 12 ++++++------ .../DataSourceSystemCachedRepository.cs | 6 ++++-- .../Repositories/DataSourceSystemRepository.cs | 6 +++--- .../Repositories/TechMessagesRepository.cs | 16 +++++++++------- .../Repositories/IDataSourceSystemRepository.cs | 12 ++++++------ 15 files changed, 77 insertions(+), 59 deletions(-) diff --git a/Persistence.API/Controllers/TechMessagesController.cs b/Persistence.API/Controllers/TechMessagesController.cs index 12b23b3..5945208 100644 --- a/Persistence.API/Controllers/TechMessagesController.cs +++ b/Persistence.API/Controllers/TechMessagesController.cs @@ -82,7 +82,7 @@ public class TechMessagesController : ControllerBase { var result = await techMessagesRepository.GetDatesRangeAsync(token); - return Ok(result); + return result == null ? NoContent() : Ok(result); } /// diff --git a/Persistence.Client/Clients/ChangeLogClient.cs b/Persistence.Client/Clients/ChangeLogClient.cs index 00aee71..bd3e49e 100644 --- a/Persistence.Client/Clients/ChangeLogClient.cs +++ b/Persistence.Client/Clients/ChangeLogClient.cs @@ -16,7 +16,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient public async Task ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token) { - var result = await ExecuteGetResponse( + 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> GetByDate(Guid idDiscriminator, DateTimeOffset moment, SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token); return result; @@ -33,7 +33,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient public async Task> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token); return result; @@ -89,7 +89,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient public async Task GetDatesRange(Guid idDiscriminator, CancellationToken token) { - var result = await ExecuteGetResponse( + 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); + } } diff --git a/Persistence.Client/Clients/DataSourceSystemClient.cs b/Persistence.Client/Clients/DataSourceSystemClient.cs index fbec180..f68f0c3 100644 --- a/Persistence.Client/Clients/DataSourceSystemClient.cs +++ b/Persistence.Client/Clients/DataSourceSystemClient.cs @@ -22,7 +22,7 @@ public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient public async Task> Get(CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await dataSourceSystemClient.Get(token), token); return result; @@ -31,5 +31,7 @@ public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient public void Dispose() { dataSourceSystemClient.Dispose(); - } + + GC.SuppressFinalize(this); + } } diff --git a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs index 3cd0d92..2d6abe9 100644 --- a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs @@ -44,7 +44,7 @@ public interface ITechMessagesClient : IDisposable /// Получить статистику по системам /// /// - /// + /// /// /// Task> GetStatistics(IEnumerable systemIds, IEnumerable categoryIds, CancellationToken token); diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs index 6937ff7..b1b90b2 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs @@ -25,6 +25,6 @@ namespace Persistence.Client.Clients.Interfaces.Refit Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); [Get($"{BaseRoute}/statistics")] - Task>> GetStatistics([Query] IEnumerable systemIds, [Query] IEnumerable categoryIds, CancellationToken token); + Task>> GetStatistics([Query(CollectionFormat.Multi)] IEnumerable systemIds, [Query(CollectionFormat.Multi)] IEnumerable categoryIds, CancellationToken token); } } diff --git a/Persistence.Client/Clients/SetpointClient.cs b/Persistence.Client/Clients/SetpointClient.cs index b1df4b4..3dba7a0 100644 --- a/Persistence.Client/Clients/SetpointClient.cs +++ b/Persistence.Client/Clients/SetpointClient.cs @@ -17,7 +17,7 @@ public class SetpointClient : BaseClient, ISetpointClient public async Task> GetCurrent(IEnumerable setpointKeys, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token); return result; @@ -25,7 +25,7 @@ public class SetpointClient : BaseClient, ISetpointClient public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token); return result; @@ -33,7 +33,7 @@ public class SetpointClient : BaseClient, ISetpointClient public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) { - var result = await ExecuteGetResponse>>( + var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetLog(setpointKeys, token), token); return result; @@ -41,7 +41,7 @@ public class SetpointClient : BaseClient, ISetpointClient public async Task GetDatesRangeAsync(CancellationToken token) { - var result = await ExecuteGetResponse( + var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetDatesRangeAsync(token), token); return result; @@ -49,7 +49,7 @@ public class SetpointClient : BaseClient, ISetpointClient public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetPart(dateBegin, take, token), token); return result; @@ -64,5 +64,7 @@ public class SetpointClient : BaseClient, ISetpointClient public void Dispose() { refitSetpointClient.Dispose(); - } + + GC.SuppressFinalize(this); + } } diff --git a/Persistence.Client/Clients/TechMessagesClient.cs b/Persistence.Client/Clients/TechMessagesClient.cs index d097451..5c90359 100644 --- a/Persistence.Client/Clients/TechMessagesClient.cs +++ b/Persistence.Client/Clients/TechMessagesClient.cs @@ -18,7 +18,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient public async Task> GetPage(PaginationRequest request, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetPage(request, token), token); return result; @@ -34,7 +34,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient public async Task> GetSystems(CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetSystems(token), token); return result; @@ -42,7 +42,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient public async Task GetDatesRangeAsync(CancellationToken token) { - var result = await ExecuteGetResponse( + var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token); return result; @@ -50,7 +50,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token); return result; @@ -58,7 +58,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient public async Task> GetStatistics(IEnumerable systemIds, IEnumerable categoryIds, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetStatistics(systemIds, categoryIds, token), token); return result; @@ -67,5 +67,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient public void Dispose() { refitTechMessagesClient.Dispose(); - } + + GC.SuppressFinalize(this); + } } diff --git a/Persistence.Client/Clients/TimeSeriesClient.cs b/Persistence.Client/Clients/TimeSeriesClient.cs index a3fba7d..416ae84 100644 --- a/Persistence.Client/Clients/TimeSeriesClient.cs +++ b/Persistence.Client/Clients/TimeSeriesClient.cs @@ -24,7 +24,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where public async Task> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token); return result; @@ -32,7 +32,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where public async Task> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token); return result; @@ -40,7 +40,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where public async Task GetDatesRange(CancellationToken token) { - var result = await ExecuteGetResponse( + var result = await ExecuteGetResponse( async () => await timeSeriesClient.GetDatesRange(token), token); return result; @@ -49,5 +49,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where public void Dispose() { timeSeriesClient.Dispose(); - } + + GC.SuppressFinalize(this); + } } diff --git a/Persistence.Client/Clients/TimestampedSetClient.cs b/Persistence.Client/Clients/TimestampedSetClient.cs index 4d40d8b..e82abee 100644 --- a/Persistence.Client/Clients/TimestampedSetClient.cs +++ b/Persistence.Client/Clients/TimestampedSetClient.cs @@ -24,7 +24,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient public async Task> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable? columnNames, int skip, int take, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token); return result; @@ -32,7 +32,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient public async Task> GetLast(Guid idDiscriminator, IEnumerable? columnNames, int take, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token); return result; @@ -40,7 +40,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient public async Task Count(Guid idDiscriminator, CancellationToken token) { - var result = await ExecuteGetResponse( + 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 GetDatesRange(Guid idDiscriminator, CancellationToken token) { - var result = await ExecuteGetResponse( + 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); + } } diff --git a/Persistence.Client/Clients/WitsDataClient.cs b/Persistence.Client/Clients/WitsDataClient.cs index ad58be1..acd8bbf 100644 --- a/Persistence.Client/Clients/WitsDataClient.cs +++ b/Persistence.Client/Clients/WitsDataClient.cs @@ -24,7 +24,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient public async Task GetDatesRangeAsync(Guid discriminatorId, CancellationToken token) { - var result = await ExecuteGetResponse( + var result = await ExecuteGetResponse( async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token); return result; @@ -32,7 +32,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient public async Task> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token); return result; @@ -40,7 +40,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token) { - var result = await ExecuteGetResponse>( + var result = await ExecuteGetResponse( async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token); return result; @@ -49,5 +49,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient public void Dispose() { refitWitsDataClient.Dispose(); - } + + GC.SuppressFinalize(this); + } } diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index 242615a..b01f9e9 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -99,7 +99,7 @@ namespace Persistence.IntegrationTests.Controllers try { //act - var response = await techMessagesClient.AddRange(systemId, dtos, new CancellationToken()); + var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None); } catch (Exception ex) { @@ -114,7 +114,7 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); //act var response = await techMessagesClient.GetSystems(CancellationToken.None); @@ -128,7 +128,7 @@ namespace Persistence.IntegrationTests.Controllers public async Task GetSystems_AfterSave_returns_success() { //arrange - var dtos = await InsertRange(Guid.NewGuid()); + await InsertRange(Guid.NewGuid()); //act var response = await techMessagesClient.GetSystems(CancellationToken.None); @@ -145,13 +145,13 @@ namespace Persistence.IntegrationTests.Controllers //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); - dbContext.CleanupDbSet(); + dbContext.CleanupDbSet(); - var imortantIds = new [] { 1 }; + var categoryIds = new [] { 1, 2 }; var systemIds = new [] { Guid.NewGuid() }; //act - var response = await techMessagesClient.GetStatistics(systemIds, imortantIds, CancellationToken.None); + var response = await techMessagesClient.GetStatistics(systemIds, categoryIds, CancellationToken.None); //assert Assert.NotNull(response); diff --git a/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs b/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs index 11a08dd..b95790e 100644 --- a/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs +++ b/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs @@ -8,6 +8,7 @@ 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) { @@ -19,11 +20,12 @@ public class DataSourceSystemCachedRepository : DataSourceSystemRepository memoryCache.Remove(SystemCacheKey); } - public override async Task> Get(CancellationToken token) { - var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f => + var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async (cacheEntry) => { + cacheEntry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow; + var dtos = await base.Get(token); return dtos; diff --git a/Persistence.Repository/Repositories/DataSourceSystemRepository.cs b/Persistence.Repository/Repositories/DataSourceSystemRepository.cs index 9fade43..5862ea3 100644 --- a/Persistence.Repository/Repositories/DataSourceSystemRepository.cs +++ b/Persistence.Repository/Repositories/DataSourceSystemRepository.cs @@ -25,14 +25,14 @@ public class DataSourceSystemRepository : IDataSourceSystemRepository { var entity = dataSourceSystemDto.Adapt(); - await db.Set().AddAsync(entity); + await db.Set().AddAsync(entity, token); await db.SaveChangesAsync(token); } - public virtual async Task> Get(CancellationToken token) + public virtual async Task> Get(CancellationToken token) { var query = GetQueryReadOnly(); - var entities = await query.ToListAsync(token); + var entities = await query.ToArrayAsync(token); var dtos = entities.Select(e => e.Adapt()); return dtos; diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index f542265..a2394ee 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -53,10 +53,10 @@ namespace Persistence.Repository.Repositories { var query = GetQueryReadOnly(); var result = await query - .Where(e => systems.Count() == 0 || systems.Contains(e.System.SystemId)) - .GroupBy(e => e.System.Name, (key, group) => new + .Where(e => !systems.Any() || systems.Contains(e.System.SystemId)) + .GroupBy(e => e.System.SystemId, (key, group) => new { - System = key, + System = group.FirstOrDefault()!.System.Name, Categories = group .Where(g => categoryIds.Count() == 0 || categoryIds.Contains(g.CategoryId)) }) @@ -81,14 +81,16 @@ namespace Persistence.Repository.Repositories public async Task AddRange(Guid systemId, IEnumerable dtos, Guid userId, CancellationToken token) { + await CreateSystemIfNotExist(systemId, token); - var entities = new List(); + var entities = new List(); foreach (var dto in dtos) { var entity = dto.Adapt(); - await CreateSystemIfNotExist(systemId, token); - entity.SystemId = systemId; + await CreateSystemIfNotExist(systemId, token); + + entity.SystemId = systemId; entities.Add(entity); } @@ -116,7 +118,7 @@ namespace Persistence.Repository.Repositories { var systems = await sourceSystemRepository.Get(token); - return systems ?? []; + return systems!; } public async Task GetDatesRangeAsync(CancellationToken token) diff --git a/Persistence/Repositories/IDataSourceSystemRepository.cs b/Persistence/Repositories/IDataSourceSystemRepository.cs index 1d964eb..d6cf29c 100644 --- a/Persistence/Repositories/IDataSourceSystemRepository.cs +++ b/Persistence/Repositories/IDataSourceSystemRepository.cs @@ -3,7 +3,7 @@ namespace Persistence.Repositories; /// -/// Интерфейс по работе с системами +/// Интерфейс по работе с системами - источниками данных /// public interface IDataSourceSystemRepository { @@ -14,9 +14,9 @@ public interface IDataSourceSystemRepository /// public Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token); - /// - /// Получить список систем - /// - /// - public Task> Get(CancellationToken token); + /// + /// Получить список систем + /// + /// + public Task> Get(CancellationToken token); } From 591ecf53774287728c6d9e562a3cbdef9a9a1b10 Mon Sep 17 00:00:00 2001 From: Roman Efremov Date: Fri, 13 Dec 2024 17:30:35 +0500 Subject: [PATCH 7/7] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=20=D1=80=D0=B5=D0=B2=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/TechMessagesController.cs | 2 +- Persistence.Client/Clients/Base/BaseClient.cs | 8 ++++---- Persistence.Client/Clients/ChangeLogClient.cs | 2 +- .../Clients/DataSourceSystemClient.cs | 2 +- .../Clients/Interfaces/ITechMessagesClient.cs | 2 +- .../Interfaces/Refit/IRefitTechMessagesClient.cs | 2 +- Persistence.Client/Clients/SetpointClient.cs | 10 +++++----- Persistence.Client/Clients/TechMessagesClient.cs | 10 +++++----- Persistence.Client/Clients/TimeSeriesClient.cs | 4 ++-- Persistence.Client/Clients/TimestampedSetClient.cs | 4 ++-- Persistence.Client/Clients/WitsDataClient.cs | 6 +++--- .../Controllers/TechMessagesControllerTest.cs | 14 ++++++-------- .../DataSourceSystemCachedRepository.cs | 2 +- .../Repositories/TechMessagesRepository.cs | 8 ++++++-- .../Repositories/ITechMessagesRepository.cs | 2 +- 15 files changed, 40 insertions(+), 38 deletions(-) diff --git a/Persistence.API/Controllers/TechMessagesController.cs b/Persistence.API/Controllers/TechMessagesController.cs index 5945208..50481a0 100644 --- a/Persistence.API/Controllers/TechMessagesController.cs +++ b/Persistence.API/Controllers/TechMessagesController.cs @@ -78,7 +78,7 @@ public class TechMessagesController : ControllerBase /// /// [HttpGet("range")] - public async Task> GetDatesRangeAsync(CancellationToken token) + public async Task> GetDatesRangeAsync(CancellationToken token) { var result = await techMessagesRepository.GetDatesRangeAsync(token); diff --git a/Persistence.Client/Clients/Base/BaseClient.cs b/Persistence.Client/Clients/Base/BaseClient.cs index 2332cbd..c29cf14 100644 --- a/Persistence.Client/Clients/Base/BaseClient.cs +++ b/Persistence.Client/Clients/Base/BaseClient.cs @@ -12,11 +12,11 @@ public abstract class BaseClient this.logger = logger; } - public async Task ExecuteGetResponse(Func>> getMethod, CancellationToken token) + public async Task ExecuteGetResponse(Func>> 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; } diff --git a/Persistence.Client/Clients/ChangeLogClient.cs b/Persistence.Client/Clients/ChangeLogClient.cs index bd3e49e..78c71a7 100644 --- a/Persistence.Client/Clients/ChangeLogClient.cs +++ b/Persistence.Client/Clients/ChangeLogClient.cs @@ -36,7 +36,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient var result = await ExecuteGetResponse( async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token); - return result; + return result!; } public async Task Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token) diff --git a/Persistence.Client/Clients/DataSourceSystemClient.cs b/Persistence.Client/Clients/DataSourceSystemClient.cs index f68f0c3..25ec605 100644 --- a/Persistence.Client/Clients/DataSourceSystemClient.cs +++ b/Persistence.Client/Clients/DataSourceSystemClient.cs @@ -25,7 +25,7 @@ public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient var result = await ExecuteGetResponse( async () => await dataSourceSystemClient.Get(token), token); - return result; + return result!; } public void Dispose() diff --git a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs index 2d6abe9..5545dad 100644 --- a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs @@ -21,7 +21,7 @@ public interface ITechMessagesClient : IDisposable /// /// /// - Task GetDatesRangeAsync(CancellationToken token); + Task GetDatesRangeAsync(CancellationToken token); /// /// Получить список технологических сообщений в виде страницы diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs index b1b90b2..3e4cd10 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs @@ -19,7 +19,7 @@ namespace Persistence.Client.Clients.Interfaces.Refit Task>> GetSystems(CancellationToken token); [Get($"{BaseRoute}/range")] - Task> GetDatesRangeAsync(CancellationToken token); + Task> GetDatesRangeAsync(CancellationToken token); [Get($"{BaseRoute}/part")] Task>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token); diff --git a/Persistence.Client/Clients/SetpointClient.cs b/Persistence.Client/Clients/SetpointClient.cs index 3dba7a0..ea6d767 100644 --- a/Persistence.Client/Clients/SetpointClient.cs +++ b/Persistence.Client/Clients/SetpointClient.cs @@ -20,7 +20,7 @@ public class SetpointClient : BaseClient, ISetpointClient var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token); - return result; + return result!; } public async Task> GetHistory(IEnumerable setpointKeys, DateTimeOffset historyMoment, CancellationToken token) @@ -28,7 +28,7 @@ public class SetpointClient : BaseClient, ISetpointClient var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token); - return result; + return result!; } public async Task>> GetLog(IEnumerable setpointKeys, CancellationToken token) @@ -36,7 +36,7 @@ public class SetpointClient : BaseClient, ISetpointClient var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetLog(setpointKeys, token), token); - return result; + return result!; } public async Task GetDatesRangeAsync(CancellationToken token) @@ -44,7 +44,7 @@ public class SetpointClient : BaseClient, ISetpointClient var result = await ExecuteGetResponse( async () => await refitSetpointClient.GetDatesRangeAsync(token), token); - return result; + return result!; } public async Task> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token) @@ -52,7 +52,7 @@ public class SetpointClient : BaseClient, ISetpointClient 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) diff --git a/Persistence.Client/Clients/TechMessagesClient.cs b/Persistence.Client/Clients/TechMessagesClient.cs index 5c90359..f69c110 100644 --- a/Persistence.Client/Clients/TechMessagesClient.cs +++ b/Persistence.Client/Clients/TechMessagesClient.cs @@ -21,7 +21,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetPage(request, token), token); - return result; + return result!; } public async Task AddRange(Guid systemId, IEnumerable dtos, CancellationToken token) @@ -37,10 +37,10 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetSystems(token), token); - return result; + return result!; } - public async Task GetDatesRangeAsync(CancellationToken token) + public async Task GetDatesRangeAsync(CancellationToken token) { var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token); @@ -53,7 +53,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token); - return result; + return result!; } public async Task> GetStatistics(IEnumerable systemIds, IEnumerable categoryIds, CancellationToken token) @@ -61,7 +61,7 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient var result = await ExecuteGetResponse( async () => await refitTechMessagesClient.GetStatistics(systemIds, categoryIds, token), token); - return result; + return result!; } public void Dispose() diff --git a/Persistence.Client/Clients/TimeSeriesClient.cs b/Persistence.Client/Clients/TimeSeriesClient.cs index 416ae84..72b8ed8 100644 --- a/Persistence.Client/Clients/TimeSeriesClient.cs +++ b/Persistence.Client/Clients/TimeSeriesClient.cs @@ -27,7 +27,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where var result = await ExecuteGetResponse( async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token); - return result; + return result!; } public async Task> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default) @@ -35,7 +35,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where var result = await ExecuteGetResponse( async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token); - return result; + return result!; } public async Task GetDatesRange(CancellationToken token) diff --git a/Persistence.Client/Clients/TimestampedSetClient.cs b/Persistence.Client/Clients/TimestampedSetClient.cs index e82abee..3009488 100644 --- a/Persistence.Client/Clients/TimestampedSetClient.cs +++ b/Persistence.Client/Clients/TimestampedSetClient.cs @@ -27,7 +27,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient var result = await ExecuteGetResponse( async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token); - return result; + return result!; } public async Task> GetLast(Guid idDiscriminator, IEnumerable? columnNames, int take, CancellationToken token) @@ -35,7 +35,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient var result = await ExecuteGetResponse( async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token); - return result; + return result!; } public async Task Count(Guid idDiscriminator, CancellationToken token) diff --git a/Persistence.Client/Clients/WitsDataClient.cs b/Persistence.Client/Clients/WitsDataClient.cs index acd8bbf..73e5873 100644 --- a/Persistence.Client/Clients/WitsDataClient.cs +++ b/Persistence.Client/Clients/WitsDataClient.cs @@ -27,7 +27,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient var result = await ExecuteGetResponse( async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token); - return result; + return result!; } public async Task> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default) @@ -35,7 +35,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient var result = await ExecuteGetResponse( async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token); - return result; + return result!; } public async Task> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token) @@ -43,7 +43,7 @@ public class WitsDataClient : BaseClient, IWitsDataClient var result = await ExecuteGetResponse( async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token); - return result; + return result!; } public void Dispose() diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index b01f9e9..c51804a 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -180,20 +180,18 @@ namespace Persistence.IntegrationTests.Controllers } [Fact] - public async Task GetDatesRange_returns_success() + public async Task GetDatesRange_returns_NoContent() { //arrange memoryCache.Remove(SystemCacheKey); dbContext.CleanupDbSet(); dbContext.CleanupDbSet(); - //act - var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); - - //assert - Assert.NotNull(response); - Assert.Equal(DateTimeOffset.MinValue, response?.From); - Assert.Equal(DateTimeOffset.MaxValue, response?.To); + //act + var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None); + + //assert + Assert.Null(response); } [Fact] diff --git a/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs b/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs index b95790e..5869992 100644 --- a/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs +++ b/Persistence.Repository/Repositories/DataSourceSystemCachedRepository.cs @@ -31,6 +31,6 @@ public class DataSourceSystemCachedRepository : DataSourceSystemRepository return dtos; }); - return systems ?? []; + return systems!; } } diff --git a/Persistence.Repository/Repositories/TechMessagesRepository.cs b/Persistence.Repository/Repositories/TechMessagesRepository.cs index a2394ee..74aff0a 100644 --- a/Persistence.Repository/Repositories/TechMessagesRepository.cs +++ b/Persistence.Repository/Repositories/TechMessagesRepository.cs @@ -58,7 +58,7 @@ namespace Persistence.Repository.Repositories { System = group.FirstOrDefault()!.System.Name, Categories = group - .Where(g => categoryIds.Count() == 0 || categoryIds.Contains(g.CategoryId)) + .Where(g => !categoryIds.Any() || categoryIds.Contains(g.CategoryId)) }) .ToArrayAsync(token); @@ -121,7 +121,7 @@ namespace Persistence.Repository.Repositories return systems!; } - public async Task GetDatesRangeAsync(CancellationToken token) + public async Task GetDatesRangeAsync(CancellationToken token) { var query = GetQueryReadOnly() .GroupBy(e => 1) @@ -130,7 +130,11 @@ namespace Persistence.Repository.Repositories 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, diff --git a/Persistence/Repositories/ITechMessagesRepository.cs b/Persistence/Repositories/ITechMessagesRepository.cs index 11c48fc..ebb7563 100644 --- a/Persistence/Repositories/ITechMessagesRepository.cs +++ b/Persistence/Repositories/ITechMessagesRepository.cs @@ -54,6 +54,6 @@ namespace Persistence.Repositories /// /// /// - Task GetDatesRangeAsync(CancellationToken token); + Task GetDatesRangeAsync(CancellationToken token); } }