feat(api, Core, Domain, Dal): Для entity моделей, для DateModified создан атрибут ManualControl - отключает автоматическое управление датой. TaskReconciliationService - сервис по управлению задачами в статусах ошибки, зависла. ITaskMqSettingsProvider - провайдер для управления настройками MQ в зависимости от TaskType
This commit is contained in:
@@ -6,6 +6,7 @@ using PARR.API.Controllers.V1.Base;
|
|||||||
using PARR.API.Services.Interfaces;
|
using PARR.API.Services.Interfaces;
|
||||||
using PARR.API.Settings;
|
using PARR.API.Settings;
|
||||||
using PARR.Core.Services.Task.Interfaces;
|
using PARR.Core.Services.Task.Interfaces;
|
||||||
|
using PARR.Core.Services.Task.Providers;
|
||||||
using PARR.Domain.Common.Roles;
|
using PARR.Domain.Common.Roles;
|
||||||
using PARR.Domain.Entities.Base.History;
|
using PARR.Domain.Entities.Base.History;
|
||||||
using PARR.Domain.Enums;
|
using PARR.Domain.Enums;
|
||||||
@@ -20,20 +21,23 @@ namespace PARR.API.Controllers.V1.Statistics
|
|||||||
{
|
{
|
||||||
private readonly ITaskManagementService taskManagementService;
|
private readonly ITaskManagementService taskManagementService;
|
||||||
private readonly IClientService clientService;
|
private readonly IClientService clientService;
|
||||||
private readonly MqSettings mqSettings;
|
//private readonly MqSettings mqSettings;
|
||||||
private readonly ILogger<StatWorkloadController> logger;
|
private readonly ILogger<StatWorkloadController> logger;
|
||||||
|
private readonly ITaskMqSettingsProvider taskMqSettingsProvider;
|
||||||
|
|
||||||
public StatWorkloadController(
|
public StatWorkloadController(
|
||||||
ITaskManagementService taskManagementService,
|
ITaskManagementService taskManagementService,
|
||||||
IClientService clientService,
|
IClientService clientService,
|
||||||
MqSettings mqSettings,
|
//MqSettings mqSettings,
|
||||||
ILogger<StatWorkloadController> logger
|
ILogger<StatWorkloadController> logger,
|
||||||
|
ITaskMqSettingsProvider taskMqSettingsProvider
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.taskManagementService = taskManagementService;
|
this.taskManagementService = taskManagementService;
|
||||||
this.clientService = clientService;
|
this.clientService = clientService;
|
||||||
this.mqSettings = mqSettings;
|
//this.mqSettings = mqSettings;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
|
this.taskMqSettingsProvider = taskMqSettingsProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -55,13 +59,14 @@ namespace PARR.API.Controllers.V1.Statistics
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
mqSettings.Tasks.TryGetValue(TaskTypeEnum.Workload, out var queueSettings);
|
//mqSettings.Tasks.TryGetValue(TaskTypeEnum.Workload, out var queueSettings);
|
||||||
|
|
||||||
if (queueSettings == null)
|
//if (queueSettings == null)
|
||||||
{
|
//{
|
||||||
logger.LogError("Не удалось получить настройки очереди для TaskType: {TaskType}", TaskTypeEnum.Workload);
|
// logger.LogError("Не удалось получить настройки очереди для TaskType: {TaskType}", TaskTypeEnum.Workload);
|
||||||
throw new InvalidOperationException($"Не удалось получить настройки очереди для TaskTypeEnum.Workload");
|
// throw new InvalidOperationException($"Не удалось получить настройки очереди для TaskTypeEnum.Workload");
|
||||||
}
|
//}
|
||||||
|
var queueSettings = taskMqSettingsProvider.GetSettings(TaskTypeEnum.Workload);
|
||||||
|
|
||||||
var taskId = await taskManagementService.CreateTaskAsync<object?>(TaskTypeEnum.Workload, default, initiator, queueSettings);
|
var taskId = await taskManagementService.CreateTaskAsync<object?>(TaskTypeEnum.Workload, default, initiator, queueSettings);
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,11 @@ using FluentValidation;
|
|||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using PARR.API.Authentication;
|
using PARR.API.Authentication;
|
||||||
using PARR.API.Installers;
|
using PARR.API.Installers;
|
||||||
|
using PARR.API.Settings;
|
||||||
using PARR.Core;
|
using PARR.Core;
|
||||||
using PARR.DAL;
|
using PARR.DAL;
|
||||||
|
using PARR.Domain.Enums;
|
||||||
|
using PARR.Domain.Settings;
|
||||||
using PARR.Infrastructure;
|
using PARR.Infrastructure;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
@@ -21,14 +24,30 @@ builder.Host.UseSerilog((context, config) =>
|
|||||||
config.ReadFrom.Configuration(builder.Configuration);
|
config.ReadFrom.Configuration(builder.Configuration);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
builder.Services.InstallSettings(builder.Configuration);
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
builder.Services.InstallDalServices(builder.Configuration);
|
builder.Services.InstallDalServices(builder.Configuration);
|
||||||
//---- new ----
|
//---- new ----
|
||||||
builder.Services.AddCoreServices(builder.Configuration);
|
builder.Services.AddCoreServices(builder.Configuration);
|
||||||
|
builder.Services.AddTaskManagement(mqSettingsFactory: (provider, taskType) =>
|
||||||
|
{
|
||||||
|
var taskSettingsMq = provider.GetRequiredService<MqSettings>();
|
||||||
|
|
||||||
|
// swith для примера
|
||||||
|
//return taskType switch
|
||||||
|
//{
|
||||||
|
// TaskTypeEnum.Workload => MqSettingsBase{ },
|
||||||
|
// _ => throw new ArgumentException($"Неизвестный тип задания {taskType}. Не смог для него получить настройки")
|
||||||
|
//};
|
||||||
|
|
||||||
|
if (taskSettingsMq.Tasks.TryGetValue(taskType, out var settings))
|
||||||
|
return settings;
|
||||||
|
|
||||||
|
throw new ArgumentException($"Настройки для типа задания {taskType} не найдены в конфигурации.");
|
||||||
|
});
|
||||||
builder.Services.AddInfrastructureServices(builder.Configuration);
|
builder.Services.AddInfrastructureServices(builder.Configuration);
|
||||||
//---- --- ----
|
//---- --- ----
|
||||||
builder.Services.InstallApiServices(builder.Configuration);
|
builder.Services.InstallApiServices(builder.Configuration);
|
||||||
builder.Services.InstallSettings(builder.Configuration);
|
|
||||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
|
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
|
||||||
|
|
||||||
// Dal configuration
|
// Dal configuration
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ using PARR.Core.Services.Task.Handlers;
|
|||||||
using PARR.Core.Services.Task.Handlers.Factory;
|
using PARR.Core.Services.Task.Handlers.Factory;
|
||||||
using PARR.Core.Services.Task.Implementations;
|
using PARR.Core.Services.Task.Implementations;
|
||||||
using PARR.Core.Services.Task.Interfaces;
|
using PARR.Core.Services.Task.Interfaces;
|
||||||
|
using PARR.Core.Services.Task.Providers;
|
||||||
using PARR.Core.Services.Workload.Implementations;
|
using PARR.Core.Services.Workload.Implementations;
|
||||||
using PARR.Core.Services.Workload.Interfaces;
|
using PARR.Core.Services.Workload.Interfaces;
|
||||||
|
using PARR.Domain.Enums;
|
||||||
using PARR.Domain.Settings;
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
namespace PARR.Core
|
namespace PARR.Core
|
||||||
@@ -43,15 +45,20 @@ namespace PARR.Core
|
|||||||
|
|
||||||
#region Task
|
#region Task
|
||||||
|
|
||||||
// Регистрация хендлеров (нужно регистировать каждый отдельно)
|
// ---------> Регистрируем в AddTaskManagement <---------
|
||||||
services.AddScoped<WorkloadReportHandler>();
|
|
||||||
services.AddScoped<BaseTaskHandler>(sp => sp.GetRequiredService<WorkloadReportHandler>());// регим для фабрики
|
|
||||||
// Еще хэндлеры...
|
|
||||||
|
|
||||||
// Фабрика хэндлеров
|
//// Регистрация хендлеров (нужно регистировать каждый отдельно)
|
||||||
services.AddScoped<ITaskHandlerFactory, TaskHandlerFactory>();
|
//services.AddScoped<WorkloadReportHandler>();
|
||||||
|
//services.AddScoped<BaseTaskHandler>(sp => sp.GetRequiredService<WorkloadReportHandler>());// регим для фабрики
|
||||||
|
//// Еще хэндлеры...
|
||||||
|
|
||||||
services.AddScoped<ITaskManagementService, TaskManagementService>();
|
//// Фабрика хэндлеров
|
||||||
|
//services.AddScoped<ITaskHandlerFactory, TaskHandlerFactory>();
|
||||||
|
|
||||||
|
//services.AddScoped<ITaskManagementService, TaskManagementService>();
|
||||||
|
|
||||||
|
//// Провайдер настроек MQ
|
||||||
|
//services.AddSingleton<ITaskMqSettingsProvider, TaskMqSettingsProvider>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -71,6 +78,35 @@ namespace PARR.Core
|
|||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Регистрация сервисов по управлению задчами (Task)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="services"></param>
|
||||||
|
/// <param name="mqSettingsFactory">Настройки MQ для всех TaskTypeEnum</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
/// <exception cref="ArgumentNullException"></exception>
|
||||||
|
public static IServiceCollection AddTaskManagement(this IServiceCollection services, Func<IServiceProvider, TaskTypeEnum, IMqSettings> mqSettingsFactory)
|
||||||
|
{
|
||||||
|
if (mqSettingsFactory == null)
|
||||||
|
throw new ArgumentNullException(nameof(mqSettingsFactory), "Ты забыл зарегистрировать настройки MQ для Task! Бестолочь! :)");
|
||||||
|
|
||||||
|
// Регистрация хендлеров (нужно регистировать каждый отдельно)
|
||||||
|
services.AddScoped<WorkloadReportHandler>();
|
||||||
|
services.AddScoped<BaseTaskHandler>(sp => sp.GetRequiredService<WorkloadReportHandler>());// регим для фабрики хэндлеров
|
||||||
|
// Еще хэндлеры...
|
||||||
|
|
||||||
|
// Фабрика хэндлеров
|
||||||
|
services.AddScoped<ITaskHandlerFactory, TaskHandlerFactory>();
|
||||||
|
|
||||||
|
services.AddScoped<ITaskManagementService, TaskManagementService>();
|
||||||
|
|
||||||
|
// Провайдер настроек MQ
|
||||||
|
services.AddTransient<Func<TaskTypeEnum, IMqSettings>>(sp => (taskType) => mqSettingsFactory(sp, taskType)); // регим фабрику настроек для ITaskMqSettingsProvider
|
||||||
|
services.AddSingleton<ITaskMqSettingsProvider, TaskMqSettingsProvider>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private static IServiceCollection AddBllMapping(this IServiceCollection services)
|
private static IServiceCollection AddBllMapping(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -97,7 +97,12 @@ namespace PARR.Core.Services.Task.Handlers
|
|||||||
private async Task<bool> TryCaptureTaskAsync(TaskItem task)
|
private async Task<bool> TryCaptureTaskAsync(TaskItem task)
|
||||||
{
|
{
|
||||||
if (task.StatusCode != TaskItemStatusEnum.Pending)
|
if (task.StatusCode != TaskItemStatusEnum.Pending)
|
||||||
|
{
|
||||||
|
// Логируем, но не считаем ошибкой
|
||||||
|
logger.LogDebug("Задача {TaskId} не в Pending (статус {Status}), пропускаем", task.Id, task.StatusCode);
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// Атомарный захват задачи
|
// Атомарный захват задачи
|
||||||
var affectedRows = await taskRepository.TaskCaptureAsync(task.Id);
|
var affectedRows = await taskRepository.TaskCaptureAsync(task.Id);
|
||||||
@@ -112,6 +117,8 @@ namespace PARR.Core.Services.Task.Handlers
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.LogDebug("Задача {TaskId} уже захвачена другим воркером", task.Id);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,6 +228,10 @@ namespace PARR.Core.Services.Task.Handlers
|
|||||||
// Вариант: сохранить флаг, а воркер после ProcessAsync проверит и отправит
|
// Вариант: сохранить флаг, а воркер после ProcessAsync проверит и отправит
|
||||||
// Это будет реализовано в BackgroundService
|
// Это будет реализовано в BackgroundService
|
||||||
|
|
||||||
|
//todo: !!! Вот это делаем дальше!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||||
|
|
||||||
|
// тоже самое в WorkloadCacheBuilderService
|
||||||
|
|
||||||
//todo:!!!!!!!!!
|
//todo:!!!!!!!!!
|
||||||
await System.Threading.Tasks.Task.Delay(50);
|
await System.Threading.Tasks.Task.Delay(50);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ namespace PARR.Core.Services.Task.Handlers
|
|||||||
|
|
||||||
//todo: тут логика построения отчета
|
//todo: тут логика построения отчета
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
await System.Threading.Tasks.Task.CompletedTask;
|
await System.Threading.Tasks.Task.CompletedTask;
|
||||||
|
|
||||||
// return HandlerResult.Success();
|
// return HandlerResult.Success();
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.Core.Common.Interfaces.RabbitServices;
|
||||||
|
using PARR.Core.Repositories.Interfaces.TaskRepositories;
|
||||||
|
using PARR.Core.Services.Task.Interfaces;
|
||||||
|
using PARR.Core.Services.Task.Models;
|
||||||
|
using PARR.Core.Services.Task.Providers;
|
||||||
|
using PARR.Domain.Common.Rabbit.Messages;
|
||||||
|
using PARR.Domain.Entities.TaskEntities;
|
||||||
|
using PARR.Domain.Enums;
|
||||||
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
|
namespace PARR.Core.Services.Task.Implementations
|
||||||
|
{
|
||||||
|
internal class TaskReconciliationService : ITaskReconciliationService
|
||||||
|
{
|
||||||
|
private readonly ILogger<TaskReconciliationService> logger;
|
||||||
|
private readonly ITaskTypeRepository taskTypeRepository;
|
||||||
|
private readonly ITaskRepository taskRepository;
|
||||||
|
private readonly ITaskErrorRepository taskErrorRepository;
|
||||||
|
private readonly IReconciliationSettings reconciliationSettings;
|
||||||
|
private readonly IRabbitService rabbitService;
|
||||||
|
private readonly ITaskMqSettingsProvider taskMqSettingsProvider;
|
||||||
|
|
||||||
|
public TaskReconciliationService(
|
||||||
|
ILogger<TaskReconciliationService> logger,
|
||||||
|
ITaskTypeRepository taskTypeRepository,
|
||||||
|
ITaskRepository taskRepository,
|
||||||
|
ITaskErrorRepository taskErrorRepository,
|
||||||
|
IReconciliationSettings reconciliationSettings,
|
||||||
|
IRabbitService rabbitService,
|
||||||
|
ITaskMqSettingsProvider taskMqSettingsProvider
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.logger = logger;
|
||||||
|
this.taskTypeRepository = taskTypeRepository;
|
||||||
|
this.taskRepository = taskRepository;
|
||||||
|
this.taskErrorRepository = taskErrorRepository;
|
||||||
|
this.reconciliationSettings = reconciliationSettings;
|
||||||
|
this.rabbitService = rabbitService;
|
||||||
|
this.taskMqSettingsProvider = taskMqSettingsProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ReconciliationReport> RunAsync()
|
||||||
|
{
|
||||||
|
var report = new ReconciliationReport
|
||||||
|
{
|
||||||
|
StartedAt = DateTimeOffset.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
logger.LogInformation("Начало выполнения Reconciliation Job.");
|
||||||
|
|
||||||
|
// Загружаем все типы задач (для получения максимальной длительности)
|
||||||
|
var taskTypes = await taskTypeRepository.Get().AsNoTracking().ToDictionaryAsync(t => t.Code, t => t);
|
||||||
|
|
||||||
|
if (taskTypes.Count == 0)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Типы задач не настроены в БД (таблица {TaskTypes})", nameof(TaskType));
|
||||||
|
report.Messages.Add("TaskTypes пустые. Не настроены в БД.");
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Для каждого типа ищем зависшие задачи
|
||||||
|
foreach (var taskType in taskTypes.Values)
|
||||||
|
{
|
||||||
|
var stuckTasks = await FindStuckTasksAsync(taskType);
|
||||||
|
report.CheckedCount += stuckTasks.Count;
|
||||||
|
|
||||||
|
foreach (var task in stuckTasks)
|
||||||
|
{
|
||||||
|
await ProcessStuckTaskAsync(task, taskType, report);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
report.CompletedAt = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
if (report.HasChanged)
|
||||||
|
logger.LogInformation("Reconciliation Job завершен. Проверено: {Checked}, Исправлено: {Fixed}, Retry: {Retried}, Failed: {Failed}. Длительность: {Duration}",
|
||||||
|
report.CheckedCount, report.FixedCount, report.RetriedCount, report.FailedCount, report.Duration);
|
||||||
|
else
|
||||||
|
logger.LogDebug("Reconciliation Job завершен. Зависших задач не найдено");
|
||||||
|
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Поиск зависших задач для конкретного типа.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="taskType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<List<TaskItem>> FindStuckTasksAsync(TaskType taskType)
|
||||||
|
{
|
||||||
|
// Вычисляем порог: задача зависла, если выполняется дольше чем MaxExecutionTimeMinutes
|
||||||
|
var timeoutThreshold = DateTimeOffset.UtcNow.AddMinutes(-taskType.MaxExecutionTimeMinutes);
|
||||||
|
|
||||||
|
logger.LogDebug("Поиск зависших задач типа {Type}. Порог: {Threshold}", taskType.Code, timeoutThreshold);
|
||||||
|
|
||||||
|
return await taskRepository.Get()
|
||||||
|
.Where(t =>
|
||||||
|
t.TypeCode == taskType.Code && t.DateModified < timeoutThreshold &&
|
||||||
|
(
|
||||||
|
// Зависла в Processing
|
||||||
|
t.StatusCode == TaskItemStatusEnum.Processing
|
||||||
|
//Зависли в Pending
|
||||||
|
|| (t.StatusCode == TaskItemStatusEnum.Pending && t.RetryCount > 0)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.OrderBy(t => t.DateModified) // Сначала самые старые
|
||||||
|
.Take(reconciliationSettings.MaxTaskPerRun) // Защита от перегрузки
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Обработка одной зависшей задачи.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="task"></param>
|
||||||
|
/// <param name="taskType"></param>
|
||||||
|
/// <param name="report"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async System.Threading.Tasks.Task ProcessStuckTaskAsync(TaskItem task, TaskType taskType, ReconciliationReport report)
|
||||||
|
{
|
||||||
|
logger.LogWarning("Обнаружена одна зависшая задача {TaskId} (тип {Type}). Последнее обновление: {LastModified}", task.Id, task.TypeCode, task.DateModified);
|
||||||
|
|
||||||
|
// Записываем ошибку в историю
|
||||||
|
var error = new TaskError
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
TaskId = task.Id,
|
||||||
|
AttemptNumber = task.RetryCount + 1, // показываем планируемую попытку
|
||||||
|
ErrorMessage = $"Превышен порог выполнения задачи. LastDateModified: {task.DateModified}"
|
||||||
|
};
|
||||||
|
|
||||||
|
await taskErrorRepository.CreateAsync(error);
|
||||||
|
await taskErrorRepository.CommitAsync();
|
||||||
|
|
||||||
|
// Если лимит исчерпан - ставим Failed
|
||||||
|
if (task.RetryCount >= taskType.MaxRetries)
|
||||||
|
{
|
||||||
|
task.StatusCode = TaskItemStatusEnum.Failed;
|
||||||
|
task.ProcessedAt = DateTimeOffset.UtcNow;
|
||||||
|
task.DateModified = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
await taskRepository.CommitAsync();
|
||||||
|
|
||||||
|
report.FailedCount++;
|
||||||
|
report.Messages.Add($"Задача {task.Id}: закончились попытки.");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Сначала пытаемся отправить в очередь
|
||||||
|
var mqSettings = taskMqSettingsProvider.GetSettings(taskType.Code);
|
||||||
|
|
||||||
|
var message = new TaskMessage { TaskId = task.Id, TypeCode = task.TypeCode };
|
||||||
|
var sendResult = await rabbitService.SendAsync(mqSettings, new List<object> { message });
|
||||||
|
|
||||||
|
if (!sendResult.IsSuccess)
|
||||||
|
{
|
||||||
|
// Очередь недоступна — НЕ меняем БД, НЕ тратим RetryCount
|
||||||
|
// Задача останется в текущем статусе и будет найдена в следующий раз
|
||||||
|
|
||||||
|
logger.LogError("Не удалось отправить задачу {TaskId} в очередь. Повторим в следующей итерации.", task.Id);
|
||||||
|
report.Messages.Add($"Задача {task.Id}: не смогла отправиться в очередь, обработается в следующей итерации.");
|
||||||
|
return; // Выходим без сохранения изменений
|
||||||
|
}
|
||||||
|
|
||||||
|
// Очередь успешна - обновляем БД
|
||||||
|
// Ставим задачу в ожидание
|
||||||
|
task.StatusCode = TaskItemStatusEnum.Pending;
|
||||||
|
|
||||||
|
// Может получиться так, что воркер возьмет задачу быстрее, чем в БД у нее установится статус Pending.
|
||||||
|
// Если это произойдет, ничего страшного, воркер это не отработает. Задача опять попадет в ProcessStuckTaskAsync и повторно отправится в очередь.
|
||||||
|
|
||||||
|
task.RetryCount++;
|
||||||
|
task.DateModified = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
await taskRepository.CommitAsync();
|
||||||
|
|
||||||
|
report.RetriedCount++;
|
||||||
|
report.Messages.Add($"Задача {task.Id}: опубликована в очередь, попытка #{task.RetryCount}");
|
||||||
|
report.FixedCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using PARR.Core.Services.Task.Models;
|
||||||
|
|
||||||
|
namespace PARR.Core.Services.Task.Interfaces
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Сервис для проверки и исправления зависших задач.
|
||||||
|
/// Запускается фоновой задачей по расписанию.
|
||||||
|
/// </summary>
|
||||||
|
internal interface ITaskReconciliationService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Выполнить один проход проверки
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<ReconciliationReport> RunAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
55
PARR.Core/Services/Task/Models/ReconciliationReport.cs
Normal file
55
PARR.Core/Services/Task/Models/ReconciliationReport.cs
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
namespace PARR.Core.Services.Task.Models
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Отчет о выполнении Reconciliation Job.
|
||||||
|
/// Используется для мониторинга и логирования.
|
||||||
|
/// </summary>
|
||||||
|
internal class ReconciliationReport
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Время начала выполнения
|
||||||
|
/// </summary>
|
||||||
|
public DateTimeOffset StartedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Время завершения выполнения
|
||||||
|
/// </summary>
|
||||||
|
public DateTimeOffset CompletedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сколько задач проверено
|
||||||
|
/// </summary>
|
||||||
|
public int CheckedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сколько задач исправлено (переведено в retry или failed)
|
||||||
|
/// </summary>
|
||||||
|
public int FixedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сколько задач отправлено на retry
|
||||||
|
/// </summary>
|
||||||
|
public int RetriedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сколько задач переведено в финальный failed
|
||||||
|
/// </summary>
|
||||||
|
public int FailedCount { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сообщения/ошибки (для логирования)
|
||||||
|
/// </summary>
|
||||||
|
public List<string> Messages { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Длительность выполнения
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan Duration => CompletedAt - StartedAt;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Были ли какие-то действия (повторные отправки, перевод в ошибку)
|
||||||
|
/// </summary>
|
||||||
|
public bool HasChanged => FixedCount > 0;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
18
PARR.Core/Services/Task/Providers/ITaskMqSettingsProvider.cs
Normal file
18
PARR.Core/Services/Task/Providers/ITaskMqSettingsProvider.cs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
using PARR.Domain.Enums;
|
||||||
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
|
namespace PARR.Core.Services.Task.Providers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Провайдер настроек очереди для задач Tasks
|
||||||
|
/// </summary>
|
||||||
|
public interface ITaskMqSettingsProvider
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Получить настройки очереди для типа задач
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="typeCode"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
IMqSettings GetSettings(TaskTypeEnum typeCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
22
PARR.Core/Services/Task/Providers/TaskMqSettingsProvider.cs
Normal file
22
PARR.Core/Services/Task/Providers/TaskMqSettingsProvider.cs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
using PARR.Domain.Enums;
|
||||||
|
using PARR.Domain.Settings;
|
||||||
|
|
||||||
|
namespace PARR.Core.Services.Task.Providers
|
||||||
|
{
|
||||||
|
internal class TaskMqSettingsProvider : ITaskMqSettingsProvider
|
||||||
|
{
|
||||||
|
private readonly Func<TaskTypeEnum, IMqSettings> settingsFactory;
|
||||||
|
|
||||||
|
public TaskMqSettingsProvider(
|
||||||
|
Func<TaskTypeEnum, IMqSettings> settingsFactory
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.settingsFactory = settingsFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IMqSettings GetSettings(TaskTypeEnum typeCode)
|
||||||
|
{
|
||||||
|
return settingsFactory(typeCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,16 +58,20 @@ namespace PARR.Core.Services.Workload.Implementations
|
|||||||
|
|
||||||
var result = await handler.ProcessAsync(queueMessage.TaskId);
|
var result = await handler.ProcessAsync(queueMessage.TaskId);
|
||||||
|
|
||||||
// Если ошибка и есть retry — отправляем в очередь с задержкой
|
//// Если ошибка и есть retry — отправляем в очередь с задержкой
|
||||||
if (!result.IsSuccess && handler is BaseTaskHandler baseHandler)
|
//if (!result.IsSuccess && handler is BaseTaskHandler baseHandler)
|
||||||
{
|
//{
|
||||||
// TODO:
|
// // TODO:
|
||||||
// Если ошибка и есть retry — отправляем в очередь с задержкой
|
// // Если ошибка и есть retry — отправляем в очередь с задержкой
|
||||||
// (это упрощенная реализация, в идеале — через ITaskQueueService)
|
// // (это упрощенная реализация, в идеале — через ITaskQueueService)
|
||||||
|
|
||||||
// Здесь нужна логика retry с задержкой
|
// // Здесь нужна логика retry с задержкой
|
||||||
// Можно реализовать через отдельный сервис
|
// // Можно реализовать через отдельный сервис
|
||||||
}
|
|
||||||
|
// //todo: !!! Вот это делаем дальше!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ->
|
||||||
|
// // тоже самое в BaseTaskHandler
|
||||||
|
|
||||||
|
//}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata.Internal;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using PARR.Core.Repositories.Base;
|
using PARR.Core.Repositories.Base;
|
||||||
using PARR.DAL.Context;
|
using PARR.DAL.Context;
|
||||||
using PARR.Domain.Common.Pagination;
|
using PARR.Domain.Common.Pagination;
|
||||||
|
using PARR.Domain.Entities.Attributes;
|
||||||
using PARR.Domain.Entities.Base;
|
using PARR.Domain.Entities.Base;
|
||||||
using PARR.Domain.Entities.Base.History;
|
using PARR.Domain.Entities.Base.History;
|
||||||
using PARR.Domain.Entities.Base.History.Base;
|
using PARR.Domain.Entities.Base.History.Base;
|
||||||
@@ -133,10 +135,28 @@ namespace PARR.DAL.Repositories.Base
|
|||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
private void DateModifiedResolver(EntityEntry obj)
|
private void DateModifiedResolver(EntityEntry obj)
|
||||||
{
|
{
|
||||||
if (obj.Entity is IBaseEntityDateModified)
|
if (obj.Entity is IBaseEntityDateModified entity)
|
||||||
|
{
|
||||||
|
//logger.LogDebug("Обновляю DateModified для сущности типа {EntityType}", obj.Entity.GetType().Name);
|
||||||
|
//(obj.Entity as IBaseEntityDateModified)!.DateModified = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
var entityType = entity.GetType();
|
||||||
|
|
||||||
|
//Ищем DateModified
|
||||||
|
var properyInfo = entityType.GetProperty(nameof(IBaseEntityDateModified.DateModified));
|
||||||
|
|
||||||
|
// Проверяем наличие атрибута ManualControlAttribute на этом свойстве
|
||||||
|
bool isManual = properyInfo?.GetCustomAttributes(typeof(ManualControlAttribute), false).Any() ?? false;
|
||||||
|
|
||||||
|
if (!isManual)
|
||||||
{
|
{
|
||||||
logger.LogDebug("Обновляю DateModified для сущности типа {EntityType}", obj.Entity.GetType().Name);
|
logger.LogDebug("Обновляю DateModified для сущности типа {EntityType}", obj.Entity.GetType().Name);
|
||||||
(obj.Entity as IBaseEntityDateModified)!.DateModified = DateTimeOffset.UtcNow;
|
entity.DateModified = DateTimeOffset.UtcNow;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logger.LogDebug("Пропуск обновления DateModified (ManualControl) для {EntityType}", entityType.Name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
11
PARR.Domain/Entities/Attributes/ManualControlAttribute.cs
Normal file
11
PARR.Domain/Entities/Attributes/ManualControlAttribute.cs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
namespace PARR.Domain.Entities.Attributes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Отключает автоматическое управление DateModified.
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Property)]
|
||||||
|
public class ManualControlAttribute : Attribute
|
||||||
|
{
|
||||||
|
// позже, можно применять к другим свойствам, если придумаем зачем и реализуем логику
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,11 @@
|
|||||||
{
|
{
|
||||||
public interface IBaseEntityDateModified
|
public interface IBaseEntityDateModified
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Дата обновления объекта в БД.
|
||||||
|
/// Обновляется автоматически при комите.
|
||||||
|
/// Чтобы отключить автоматическое управление, применить атрибут [ManualControl]
|
||||||
|
/// </summary>
|
||||||
public DateTimeOffset? DateModified { get; set; }
|
public DateTimeOffset? DateModified { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using PARR.Domain.Constants;
|
using PARR.Domain.Constants;
|
||||||
|
using PARR.Domain.Entities.Attributes;
|
||||||
using PARR.Domain.Entities.Base;
|
using PARR.Domain.Entities.Base;
|
||||||
using PARR.Domain.Entities.Base.History;
|
using PARR.Domain.Entities.Base.History;
|
||||||
using PARR.Domain.Enums;
|
using PARR.Domain.Enums;
|
||||||
@@ -17,6 +18,7 @@ namespace PARR.Domain.Entities.TaskEntities
|
|||||||
|
|
||||||
public DateTimeOffset DateCreated { get; set; }
|
public DateTimeOffset DateCreated { get; set; }
|
||||||
|
|
||||||
|
[ManualControl]
|
||||||
public DateTimeOffset? DateModified { get; set; }
|
public DateTimeOffset? DateModified { get; set; }
|
||||||
|
|
||||||
public TaskTypeEnum TypeCode { get; set; }
|
public TaskTypeEnum TypeCode { get; set; }
|
||||||
|
|||||||
21
PARR.Domain/Settings/IReconciliationSettings.cs
Normal file
21
PARR.Domain/Settings/IReconciliationSettings.cs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
namespace PARR.Domain.Settings
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Настройки поиска зависших заданий (Task, Reconciliation Job)
|
||||||
|
/// </summary>
|
||||||
|
public interface IReconciliationSettings
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Интервал запуска проверки.
|
||||||
|
/// Рекомендуемое значение: 5-10 минут.
|
||||||
|
/// </summary>
|
||||||
|
TimeSpan CheckInterval { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Максимальное кол-во задач для обработки за один проход.
|
||||||
|
/// Защита от перегрузки при большом кол-ве зависших задач.
|
||||||
|
/// Рекомендуемое значение 100
|
||||||
|
/// </summary>
|
||||||
|
public int MaxTaskPerRun { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user