feat(api, core, dal, domain): В таблицу Tasks добавлено поле процент выполнения, так же добавлено это поле в response - статус формирования отчета. Создан интерфейс для отслеживания прогресса IProgressAsync. Из сервиса WorkloadService исключен ITaskManagementService.

This commit is contained in:
Mikhail Trubnikov
2026-05-20 14:26:25 +10:00
parent 8f61bbb73e
commit 68808e761b
17 changed files with 4160 additions and 41 deletions

View File

@@ -82,7 +82,7 @@ namespace PARR.Core.Services.Workload.Implementations
/// КЭШ рабочих групп и зон ответственности
/// </summary>
/// <returns></returns>
public async Task CreateTemplateCacheAsync()
public async Task CreateTemplateCacheAsync(IProgressAsync<int> progress)
{
var dtStart = DateTimeOffset.UtcNow;
@@ -97,10 +97,25 @@ namespace PARR.Core.Services.Workload.Implementations
logger.LogInformation("Получил из БД шаблонов {TemplateCount} шт.", templates.Count);
//Ставим сразу 5% - получили из БД
await progress.ReportAsync(5);
if (templates.Count == 0)
{
logger.LogWarning("Список шаблонов пуст, кэш не формируется");
await progress.ReportAsync(100);
return;
}
//2. Получить по каждому шаблону ЗО и РГ
var cacheData = new List<TemplateCache>();
int templateCount = 0;
int totalTemplates = templates.Count;
// последний отправленный процент
int lastReportedPercent = 5;
foreach (var template in templates)
{
var (workGroup, responseArea) = await ApplyShortcodesAsync(template);
@@ -116,8 +131,26 @@ namespace PARR.Core.Services.Workload.Implementations
cacheData.Add(cacheItem);
templateCount++;
#region Расчет и отрпавка прогресса
// Считаем текущий процент(0 - 100). Этап идёт от 5% до 95%
var currentPercent = 5 + (int)((templateCount * 90.0) / totalTemplates);
// Округляем вниз до кратного 5 (33→30, 37→35, 99→95)
var roundedPercent = (currentPercent / 5) * 5;
// Отправляем, только если прогресс реально изменился (защита от дублей)
if (roundedPercent > lastReportedPercent && roundedPercent <= 95)
{
await progress.ReportAsync(roundedPercent);
lastReportedPercent = roundedPercent;
}
#endregion
}
//95%
await progress.ReportAsync(95);
//3. Сохранить в Redis
logger.LogDebug("Для сохранения в Redis подготовлен массив из {Count} строк", cacheData.Count);
var hashKey = redisCacheService.GetKey(cacheTemplateKey);
@@ -127,6 +160,8 @@ namespace PARR.Core.Services.Workload.Implementations
await redisCacheService.SetHashFieldAsync(hashKey, item.Data.TemplateId.ToString(), item, cacheTemplateTtl);
}
await progress.ReportAsync(100);
var duration = DateTimeOffset.UtcNow - dtStart;
logger.LogInformation("Завершено формирование кэша. Key: {HashKey}, ttl: {Ttl}, кол-во записей: {CacheCount}. Продолжительность формирования КЭШ {Duration}", hashKey, cacheTemplateTtl, cacheData.Count, duration);
}

View File

@@ -1,9 +1,10 @@
using Microsoft.Extensions.Logging;
using AutoMapper;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.TaskRepositories;
using PARR.Core.Services.NextRunServices;
using PARR.Core.Services.TaskServices.Interfaces;
using PARR.Core.Services.TaskServices.Helpers;
using PARR.Core.Services.Workload.Interfaces;
using PARR.Core.Services.Workload.Models;
using PARR.Domain.DTOs.TaskDTO;
using PARR.Domain.DTOs.Workload;
using PARR.Domain.Enums;
@@ -14,19 +15,26 @@ namespace PARR.Core.Services.Workload.Implementations
private readonly ILogger<WorkloadService> logger;
private readonly WorkloadCacheService workloadCacheService;
private readonly INextRunService nextRunService;
private readonly ITaskManagementService taskManagementService;
private readonly ITaskRepository taskRepository;
private readonly IMapper mapper;
//private readonly ITaskManagementService taskManagementService;
public WorkloadService(
ILogger<WorkloadService> logger,
WorkloadCacheService workloadCacheService,
INextRunService nextRunService,
ITaskManagementService taskManagementService
ITaskRepository taskRepository,
IMapper mapper
//ITaskManagementService taskManagementService
)
{
this.logger = logger;
this.workloadCacheService = workloadCacheService;
this.nextRunService = nextRunService;
this.taskManagementService = taskManagementService;
this.taskRepository = taskRepository;
this.mapper = mapper;
//this.taskManagementService = taskManagementService;
}
@@ -122,14 +130,15 @@ namespace PARR.Core.Services.Workload.Implementations
// 1. проверить что выполнились все задания на обновление кэш
var activeTasks = await taskManagementService.GetActiveTasksAsync(TaskTypeEnum.Workload);
//var activeTasks = await taskManagementService.GetActiveTasksAsync(TaskTypeEnum.Workload);
var activeTasks = await TaskManagementHelpers.GetActiveTasksAsync(taskRepository, mapper, TaskTypeEnum.Workload);
if (activeTasks.Count > 0)
{
// идет формирование отчета
// задача может быт только одна, так как у нее такой тип
var task = activeTasks.First();
return new WorkloadCacheInfo { Status = WorkloadCacheInfo.StatusEnum.Processing, Date = task.DateCreated };
return new WorkloadCacheInfo { Status = WorkloadCacheInfo.StatusEnum.Processing, Date = task.DateCreated, ProgressPercent = task.ProgressPercent };
}
// 2. получить дату кэш