feat(core): TaskManagementService - отправка сообщений
This commit is contained in:
@@ -1,8 +1,14 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using PARR.API.Contracts.V1;
|
using PARR.API.Contracts.V1;
|
||||||
|
using PARR.API.Contracts.V1.Responses.Base;
|
||||||
using PARR.API.Controllers.V1.Base;
|
using PARR.API.Controllers.V1.Base;
|
||||||
|
using PARR.API.Services.Interfaces;
|
||||||
|
using PARR.API.Settings;
|
||||||
|
using PARR.Core.Services.Task.Interfaces;
|
||||||
using PARR.Domain.Common.Roles;
|
using PARR.Domain.Common.Roles;
|
||||||
|
using PARR.Domain.Entities.Base.History;
|
||||||
|
using PARR.Domain.Enums;
|
||||||
|
|
||||||
namespace PARR.API.Controllers.V1.Statistics
|
namespace PARR.API.Controllers.V1.Statistics
|
||||||
{
|
{
|
||||||
@@ -12,9 +18,22 @@ namespace PARR.API.Controllers.V1.Statistics
|
|||||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||||
public class StatWorkloadController : BaseApiController
|
public class StatWorkloadController : BaseApiController
|
||||||
{
|
{
|
||||||
public StatWorkloadController()
|
private readonly ITaskManagementService taskManagementService;
|
||||||
{
|
private readonly IClientService clientService;
|
||||||
|
private readonly MqSettings mqSettings;
|
||||||
|
private readonly ILogger<StatWorkloadController> logger;
|
||||||
|
|
||||||
|
public StatWorkloadController(
|
||||||
|
ITaskManagementService taskManagementService,
|
||||||
|
IClientService clientService,
|
||||||
|
MqSettings mqSettings,
|
||||||
|
ILogger<StatWorkloadController> logger
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.taskManagementService = taskManagementService;
|
||||||
|
this.clientService = clientService;
|
||||||
|
this.mqSettings = mqSettings;
|
||||||
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -25,8 +44,31 @@ namespace PARR.API.Controllers.V1.Statistics
|
|||||||
[HttpPost(ApiRoutes.Workload.Build)]
|
[HttpPost(ApiRoutes.Workload.Build)]
|
||||||
public async Task<IActionResult> Build()
|
public async Task<IActionResult> Build()
|
||||||
{
|
{
|
||||||
|
var initiator = new HistoryInitiator
|
||||||
|
{
|
||||||
|
InitiatorIp = clientService.GetClientIp()?.ToString(),
|
||||||
|
InitiatorParrComponentId = ParrComponentsEnum.Api,
|
||||||
|
InitiatorComment = "Отправлен запрос из API на формирование отчета о загруженности"
|
||||||
|
};
|
||||||
|
|
||||||
return Ok();
|
try
|
||||||
|
{
|
||||||
|
mqSettings.Tasks.TryGetValue(TaskTypeEnum.Workload, out var queueSettings);
|
||||||
|
|
||||||
|
if (queueSettings == null)
|
||||||
|
{
|
||||||
|
logger.LogError("Не удалось получить настройки очереди для TaskType: {TaskType}", TaskTypeEnum.Workload);
|
||||||
|
throw new InvalidOperationException($"Не удалось получить настройки очереди для TaskTypeEnum.Workload");
|
||||||
|
}
|
||||||
|
|
||||||
|
var taskId = await taskManagementService.CreateTaskAsync<object?>(TaskTypeEnum.Workload, default, initiator, queueSettings);
|
||||||
|
|
||||||
|
return Ok(new Response<string?>(null, true, null!, $"Создана задача {taskId} на формирование отчета"));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = ex.Message } }));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ using Microsoft.Extensions.Configuration;
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using PARR.Core.Common.Implementations;
|
using PARR.Core.Common.Implementations;
|
||||||
using PARR.Core.Common.Interfaces;
|
using PARR.Core.Common.Interfaces;
|
||||||
|
using PARR.Core.Services.Task.Implementations;
|
||||||
|
using PARR.Core.Services.Task.Interfaces;
|
||||||
using PARR.Domain.Settings;
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
namespace PARR.Core
|
namespace PARR.Core
|
||||||
@@ -37,6 +39,7 @@ namespace PARR.Core
|
|||||||
|
|
||||||
#region Services
|
#region Services
|
||||||
|
|
||||||
|
services.AddScoped<ITaskManagementService, TaskManagementService>();
|
||||||
//services.AddScoped<IUserService, UserService>();
|
//services.AddScoped<IUserService, UserService>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -8,7 +8,6 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Infrastructure\" />
|
<Folder Include="Infrastructure\" />
|
||||||
<Folder Include="Services\" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.Core.Common.Interfaces.RabbitServices;
|
||||||
using PARR.Core.Repositories.Interfaces.TaskRepositories;
|
using PARR.Core.Repositories.Interfaces.TaskRepositories;
|
||||||
|
using PARR.Core.Services.Task.Interfaces;
|
||||||
|
using PARR.Domain.Common.Rabbit.Messages;
|
||||||
using PARR.Domain.Entities.Base.History;
|
using PARR.Domain.Entities.Base.History;
|
||||||
using PARR.Domain.Entities.TaskEntities;
|
using PARR.Domain.Entities.TaskEntities;
|
||||||
using PARR.Domain.Enums;
|
using PARR.Domain.Enums;
|
||||||
@@ -8,29 +11,32 @@ using PARR.Domain.Settings;
|
|||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace PARR.DAL.TaskServices
|
namespace PARR.Core.Services.Task.Implementations
|
||||||
{
|
{
|
||||||
internal class TaskManagementService : ITaskManagementService
|
internal class TaskManagementService : ITaskManagementService
|
||||||
{
|
{
|
||||||
private readonly ILogger<TaskManagementService> logger;
|
private readonly ILogger<TaskManagementService> logger;
|
||||||
private readonly ITaskTypeRepository taskTypeService;
|
private readonly ITaskTypeRepository taskTypeRepository;
|
||||||
private readonly ITaskRepository taskService;
|
private readonly ITaskRepository taskRepository;
|
||||||
|
private readonly IRabbitService rabbitService;
|
||||||
|
|
||||||
public TaskManagementService(
|
public TaskManagementService(
|
||||||
ILogger<TaskManagementService> logger,
|
ILogger<TaskManagementService> logger,
|
||||||
ITaskTypeRepository taskTypeService,
|
ITaskTypeRepository taskTypeRepository,
|
||||||
ITaskRepository taskService
|
ITaskRepository taskRepository,
|
||||||
|
IRabbitService rabbitService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.taskTypeService = taskTypeService;
|
this.taskTypeRepository = taskTypeRepository;
|
||||||
this.taskService = taskService;
|
this.taskRepository = taskRepository;
|
||||||
|
this.rabbitService = rabbitService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<Guid> CreateTaskAsync<T>(TaskTypeEnum typeCode, T payload, IHistoryInitiator initiator, IMqSettings mqSettings)
|
public async Task<Guid> CreateTaskAsync<T>(TaskTypeEnum typeCode, T payload, IHistoryInitiator initiator, IMqSettings mqSettings)
|
||||||
{
|
{
|
||||||
var taskType = await taskTypeService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Code == typeCode);
|
var taskType = await taskTypeRepository.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Code == typeCode);
|
||||||
|
|
||||||
if (taskType == null)
|
if (taskType == null)
|
||||||
{
|
{
|
||||||
@@ -45,10 +51,7 @@ namespace PARR.DAL.TaskServices
|
|||||||
|
|
||||||
if (existingTask != null)
|
if (existingTask != null)
|
||||||
{
|
{
|
||||||
logger.LogInformation(
|
logger.LogInformation("Задача типа {TypeCode} уже активна (id: {ExistingId}). Возвращаем существующую.", typeCode, existingTask.Id);
|
||||||
"Задача типа {TypeCode} уже активна (id: {ExistingId}). Возвращаем существующую.",
|
|
||||||
typeCode, existingTask.Id);
|
|
||||||
|
|
||||||
return existingTask.Id;
|
return existingTask.Id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -63,26 +66,30 @@ namespace PARR.DAL.TaskServices
|
|||||||
StatusCode = TaskItemStatusEnum.Pending,
|
StatusCode = TaskItemStatusEnum.Pending,
|
||||||
Payload = payloadStr,
|
Payload = payloadStr,
|
||||||
RetryCount = 0,
|
RetryCount = 0,
|
||||||
ProcessedAt = null,
|
ProcessedAt = null
|
||||||
InitiatorIp = initiator.InitiatorIp,
|
|
||||||
InitiatorParrComponentId = initiator.InitiatorParrComponentId,
|
|
||||||
InitiatorComment = initiator.InitiatorComment
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!await taskService.CreateAsync(task) || !await taskService.CommitAsync())
|
if (!await taskRepository.CreateAsync(task) || !await taskRepository.CommitAsync(initiator))
|
||||||
{
|
{
|
||||||
logger.LogError("Ошибка при сохранении задачи в БД");
|
logger.LogError("Ошибка при сохранении задачи в БД");
|
||||||
return default;
|
throw new DbUpdateException("Ошибка при сохранении задачи в БД");
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogInformation("Задача {TaskId} типа {TypeCode} сохранена в БД со статусом Pending", task.Id, typeCode);
|
logger.LogInformation("Задача {TaskId} типа {TypeCode} сохранена в БД со статусом Pending", task.Id, typeCode);
|
||||||
|
|
||||||
// Публикуме задачу в очередь. Если вдруг даже не получится,
|
var message = new TaskMessage { TaskId = task.Id, TypeCode = task.TypeCode };
|
||||||
// задача останется в БД со статусом pending, и Reconciliation Task позже ее возмет в работу
|
|
||||||
|
|
||||||
// todo: опубликовать в очередь
|
var sendResult = await rabbitService.SendAsync(mqSettings, new List<object> { message });
|
||||||
// вопросы, зачем scoped? может можно AddTransient?
|
if (sendResult.IsSuccess)
|
||||||
// нужно придумать шаблонную модель для очереди
|
{
|
||||||
|
logger.LogDebug("Задача {TaskId} типа {TypeCode} отправлена в очередь {QueueName}", task.Id, typeCode, mqSettings.QueueName);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Не пробрасываем исключение дальше — задача создана, просто не в очереди.
|
||||||
|
// задача останется в БД со статусом pending, и Reconciliation Task позже ее возмет в работу
|
||||||
|
logger.LogError("Не удалось опубликовать задачу {TaskId} в очередь. Задача осталась в БД со статусом Pending.", task.Id);
|
||||||
|
}
|
||||||
|
|
||||||
return task.Id;
|
return task.Id;
|
||||||
}
|
}
|
||||||
@@ -95,7 +102,7 @@ namespace PARR.DAL.TaskServices
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private async Task<TaskItem?> GetActiveSingletonTaskAsync(TaskTypeEnum typeCode)
|
private async Task<TaskItem?> GetActiveSingletonTaskAsync(TaskTypeEnum typeCode)
|
||||||
{
|
{
|
||||||
return await taskService.Get().AsNoTracking()
|
return await taskRepository.Get().AsNoTracking()
|
||||||
.FirstOrDefaultAsync(t => t.TypeCode == typeCode && (
|
.FirstOrDefaultAsync(t => t.TypeCode == typeCode && (
|
||||||
t.StatusCode == TaskItemStatusEnum.Pending
|
t.StatusCode == TaskItemStatusEnum.Pending
|
||||||
|| t.StatusCode == TaskItemStatusEnum.Processing
|
|| t.StatusCode == TaskItemStatusEnum.Processing
|
||||||
@@ -109,13 +116,16 @@ namespace PARR.DAL.TaskServices
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
/// <param name="payload"></param>
|
/// <param name="payload"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private string PayloadToString<T>(T payload)
|
private string? PayloadToString<T>(T payload)
|
||||||
{
|
{
|
||||||
var jsonOptions = new JsonSerializerOptions
|
var jsonOptions = new JsonSerializerOptions
|
||||||
{
|
{
|
||||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (payload == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
return JsonSerializer.Serialize(payload, jsonOptions);
|
return JsonSerializer.Serialize(payload, jsonOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
using PARR.Domain.Enums;
|
using PARR.Domain.Enums;
|
||||||
using PARR.Domain.Settings;
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
namespace PARR.DAL.TaskServices
|
namespace PARR.Core.Services.Task.Interfaces
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Управления задачами (очередями)
|
/// Управления задачами (очередями)
|
||||||
@@ -22,7 +22,6 @@ using PARR.DAL.Services.Interfaces;
|
|||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
using PARR.DAL.Services.Interfaces.Schedule;
|
using PARR.DAL.Services.Interfaces.Schedule;
|
||||||
using PARR.DAL.Services.Interfaces.Unit;
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
using PARR.DAL.TaskServices;
|
|
||||||
using PARR.Domain.Settings;
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
namespace PARR.DAL
|
namespace PARR.DAL
|
||||||
@@ -154,8 +153,6 @@ namespace PARR.DAL
|
|||||||
services.AddScoped<ITaskRepository, TaskRepository>();
|
services.AddScoped<ITaskRepository, TaskRepository>();
|
||||||
services.AddScoped<ITaskTypeRepository, TaskTypeRepository>();
|
services.AddScoped<ITaskTypeRepository, TaskTypeRepository>();
|
||||||
|
|
||||||
services.AddTransient<ITaskManagementService, TaskManagementService>();
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
//services.AddTransient<INextRunModifierService, NextRunModifierService>();
|
//services.AddTransient<INextRunModifierService, NextRunModifierService>();
|
||||||
|
|||||||
@@ -99,6 +99,9 @@ namespace PARR.DAL.Repositories.Base
|
|||||||
/// <param name="initiator"></param>
|
/// <param name="initiator"></param>
|
||||||
private void SetInitiator(IHistoryInitiator? initiator)
|
private void SetInitiator(IHistoryInitiator? initiator)
|
||||||
{
|
{
|
||||||
|
if (initiator == null)
|
||||||
|
return;
|
||||||
|
|
||||||
logger.LogDebug("Устанавливаю инициатора для изменений");
|
logger.LogDebug("Устанавливаю инициатора для изменений");
|
||||||
|
|
||||||
// Задаем инициатора только для новых и измененных записей
|
// Задаем инициатора только для новых и измененных записей
|
||||||
|
|||||||
16
PARR.Domain/Common/Rabbit/Messages/TaskMessage.cs
Normal file
16
PARR.Domain/Common/Rabbit/Messages/TaskMessage.cs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
using PARR.Domain.Enums;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace PARR.Domain.Common.Rabbit.Messages
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Модель для отправки сообщений через ITaskManagement
|
||||||
|
/// </summary>
|
||||||
|
public record TaskMessage
|
||||||
|
{
|
||||||
|
public Guid TaskId { get; init; }
|
||||||
|
|
||||||
|
[JsonConverter(typeof(JsonStringEnumConverter))]
|
||||||
|
public TaskTypeEnum TypeCode { get; init; }
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user