feat(templateDistributor, BLL): доделал распределение шаблонов. Сохраняет в БД + ставит задания роботам на обновление. MqService - может принимать список объектов для отправки, доработана кодировка отправки сообщений.

This commit is contained in:
Mikhail Trubnikov
2026-01-22 10:35:27 +10:00
parent e5bc42741c
commit b7fca08d28
8 changed files with 132 additions and 19 deletions

View File

@@ -5,10 +5,13 @@ using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace PARR.API.Controllers.V1
@@ -22,16 +25,19 @@ namespace PARR.API.Controllers.V1
private readonly IMqService mqService;
private readonly MqSettings mqSettings;
private readonly IValidator<DistributeRequest> validator;
private readonly IClientService clientService;
public DistributorController(
IMqService mqService,
MqSettings mqSettings,
IValidator<DistributeRequest> validator
IValidator<DistributeRequest> validator,
IClientService clientService
)
{
this.mqService = mqService;
this.mqSettings = mqSettings;
this.validator = validator;
this.clientService = clientService;
}
@@ -48,12 +54,23 @@ namespace PARR.API.Controllers.V1
var requestToMq = new TemplateDistributorMq
{
JobGroupId = request.JobGroupId
JobGroupId = request.JobGroupId,
Initiator = new HistoryInitiator
{
InitiatorComment = "Через API отправлен запрос на распределение шаблонов",
InitiatorIp = clientService.GetClientIp()?.ToString(),
InitiatorParrComponentId = ParrComponentsEnum.Api
}
};
var msg = JsonSerializer.Serialize(requestToMq);
//var jsonOptions = new JsonSerializerOptions
//{
// Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
//};
//var msg = JsonSerializer.Serialize(requestToMq, jsonOptions);
var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new[] { msg });
//var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new[] { msg });
var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new List<object> { requestToMq });
if (sendResult.IsSuccess)
return Created("", new Response<string?>(null, true, new List<ErrorModel>(), "Отправлен запрос на перераспределение регламентных работ."));

View File

@@ -1,4 +1,6 @@
namespace PARR.BLL.Domain.Mq
using PARR.Common.Domain;
namespace PARR.BLL.Domain.Mq
{
/// <summary>
/// Модель в MQ, распределить шаблоны для JobGroupId (для TemplateDistributor)
@@ -6,5 +8,7 @@
public class TemplateDistributorMq
{
public Guid JobGroupId { get; set; }
public required HistoryInitiator Initiator { get; set; }
}
}

View File

@@ -5,6 +5,8 @@ using PARR.BLL.Services.Interfaces;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace PARR.BLL.Services.Implementations
{
@@ -17,6 +19,11 @@ namespace PARR.BLL.Services.Implementations
// реализация для RabbitMQ.Client 7.1.2
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
public MqServiceV2(ILogger<MqServiceV2> logger)
{
this.logger = logger;
@@ -108,6 +115,12 @@ namespace PARR.BLL.Services.Implementations
}
}
public async Task<MqSendResult> SendAsync(IMqSettings mqSettings, List<object> msgObjectList)
{
var msgStringList = msgObjectList.Select(t => JsonSerializer.Serialize(t, jsonOptions)).ToArray();
return await SendAsync(mqSettings, msgStringList);
}
public async Task<MqSendResult> SendAsync(IMqSettings mqSettings, string[] msgList)
{
@@ -136,7 +149,8 @@ namespace PARR.BLL.Services.Implementations
props.DeliveryMode = DeliveryModes.Persistent;
//время жизни, мс
//props.Expiration = "60000";
props.ContentType = "text/plain";//"application/json";
//props.ContentType = "text/plain";//"application/json";
props.ContentType = "text/plain; charset=utf-8";//"application/json";
channel.BasicReturnAsync += async (sender, ea) =>
{

View File

@@ -8,6 +8,22 @@ namespace PARR.BLL.Services.Interfaces
public interface IMqService : IAsyncDisposable // IDisposable
{
Task<bool> InitConsumerAsync(IMqSettings mqSettings, MqMessageHandlerDelegate messageHandler);
/// <summary>
/// Отправить сообщение в очередь используя список строк
/// !!! Избавиться от этого метода, вместо него использовать со списком объектов !!!
/// </summary>
/// <param name="mqSettings"></param>
/// <param name="msgList"></param>
/// <returns></returns>
Task<MqSendResult> SendAsync(IMqSettings mqSettings, string[] msgList);
/// <summary>
/// Отправить сообщение в очередь используя список объектов
/// </summary>
/// <param name="mqSettings"></param>
/// <param name="msgObjectList"></param>
/// <returns></returns>
Task<MqSendResult> SendAsync(IMqSettings mqSettings, List<object> msgObjectList);
}
}

View File

@@ -1,4 +1,6 @@
namespace PARR.TemplateDistributor
using PARR.BLL.Domain.Mq;
namespace PARR.TemplateDistributor
{
public interface ITemplateDistributor
{
@@ -7,6 +9,6 @@
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task DistributeAsync(Guid jobGroupId);
Task DistributeAsync(TemplateDistributorMq mqResponse);
}
}

View File

@@ -65,8 +65,7 @@ namespace PARR.TemplateDistributor
if (service == null)
throw new Exception($"Не найден сервис: {nameof(ITemplateDistributor)}");
await service.DistributeAsync(query.JobGroupId);
await service.DistributeAsync(query);
}
}

View File

@@ -1,12 +1,10 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.BLL.Domain.Mq;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.Contracts;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;
using System.Reflection.Metadata.Ecma335;
namespace PARR.TemplateDistributor
{
@@ -14,19 +12,27 @@ namespace PARR.TemplateDistributor
{
private readonly ILogger<TemplateDistributor> logger;
private readonly INextRunService nextRunService;
private readonly ITemplateService templateService;
private readonly IRobotConfigurationService robotConfigurationService;
public TemplateDistributor(
ILogger<TemplateDistributor> logger,
INextRunService nextRunService
INextRunService nextRunService,
ITemplateService templateService,
IRobotConfigurationService robotConfigurationService
)
{
this.logger = logger;
this.nextRunService = nextRunService;
this.templateService = templateService;
this.robotConfigurationService = robotConfigurationService;
}
public async Task DistributeAsync(Guid jobGroupId)
public async Task DistributeAsync(TemplateDistributorMq mqResponse)
{
var jobGroupId = mqResponse.JobGroupId;
// вызвать метод распределения, и получить новые даты
var distributedTemplates = await nextRunService.GetNextRunForJobGroupWithAutoDistributionAsync(jobGroupId);
@@ -37,6 +43,61 @@ namespace PARR.TemplateDistributor
}
// получить список шаблонов, сравнить их с распределенными, обновить даты, сохранить
var groupTemplates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Where(t => t.Job.GroupId == jobGroupId)
.ToListAsync();
if (!groupTemplates.Any())
{
logger.LogWarning("Для jobGroupId {jobGroupId} не найдено ни одного шаблона в БД. Прекращаю обновление.", jobGroupId);
return;
}
// создать словарь для быстрого поиска
var distributedDict = distributedTemplates.ToDictionary(t => t.Id);
int updatedCount = 0;
foreach (var templateDb in groupTemplates)
{
if (distributedDict.TryGetValue(templateDb.Id, out var distributedTemplate))
{
if (templateDb.NextRun != distributedTemplate.NextRun)
{
templateDb.NextRun = distributedTemplate.NextRun;
templateDb.LastRun = distributedTemplate.NextRunOld;
templateDb.DateModified = DateTimeOffset.UtcNow;
// ставим задание роботу - обновить расписания
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, templateDb);
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
updatedCount++;
}
}
else
{
logger.LogWarning("Шаблон с Id {templateId} не найден в распределённых данных.", templateDb.Id);
}
}
if (updatedCount > 0)
{
// сохранить изменения
if (await templateService.CommitAsync(mqResponse.Initiator))
{
logger.LogInformation("Обновлено {updatedCount} шаблонов в БД для jobGroupId {jobGroupId}. Для расписаний установлен статус: {taskStatus}", updatedCount, jobGroupId, TaskStatusEnum.Updating.ToString());
}
else
{
logger.LogError("Ошибка при обновлении записей в БД. jobGroupId {jobGroupId}, требовалось обновить шаблонов: {updatedCount}", jobGroupId, updatedCount);
}
}
else
{
logger.LogInformation("Для jobGroupId {jobGroupId} не найдено изменений. Ничего не обновлено.", jobGroupId);
}
}
}
}

View File

@@ -10,10 +10,10 @@
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
"Microsoft": "Debug",
"Microsoft.Hosting.Lifetime": "Debug"
}
},
"WriteTo": [