fix(aihit-sync): исправление критических ошибок в RelationshipsSyncService

- ValidateInput: возвращает пустой список вместо null! при отсутствии данных
- SyncAsync: добавлена транзакция между удалением и добавлением связей
- GetOrCreateUnitsAsync: пакетное создание юнитов через CreateRange вместо поштучного цикла
- Удалены избыточные комментарии, код самодокументируем через имена методов
- Единообразие имён переменных: _unitRepository, unitsByName, parentName/childName
- PassSafeguardCheckAsync: выделен в отдельный метод для читаемости SyncAsync
- CommitChangesAsync: бросает исключение при ошибке коммита вместо тихого лога
This commit is contained in:
Mikhail Kuznetsov
2026-07-14 15:41:31 +10:00
parent 74105f8e14
commit 36ccf5b051

View File

@@ -1,4 +1,4 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using PARR.AIHITRelationshipsSyncer.Models; using PARR.AIHITRelationshipsSyncer.Models;
using PARR.AIHITRelationshipsSyncer.Services.Interfaces; using PARR.AIHITRelationshipsSyncer.Services.Interfaces;
@@ -6,149 +6,147 @@ using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Domain.Entities.Unit; using PARR.Domain.Entities.Unit;
using PARR.Domain.Settings; using PARR.Domain.Settings;
namespace PARR.AIHITRelationshipsSyncer.Services.Implementations; namespace PARR.AIHITRelationshipsSyncer.Services.Implementations
{
internal class RelationshipsSyncService : IRelationshipsSyncService internal class RelationshipsSyncService : IRelationshipsSyncService
{ {
private readonly ILogger<RelationshipsSyncService> _logger; private readonly ILogger<RelationshipsSyncService> logger;
private readonly IUnitRepository _unitRepository; private readonly IUnitRepository unitService;
private readonly SettingsFromDb _settingsFromDb; private readonly SettingsFromDb _settingsFromDb;
public RelationshipsSyncService( public RelationshipsSyncService(
ILogger<RelationshipsSyncService> logger, ILogger<RelationshipsSyncService> logger,
IUnitRepository unitRepository, IUnitRepository unitService,
SettingsFromDb settingsFromDb) SettingsFromDb settingsFromDb
)
{ {
_logger = logger; this.logger = logger;
_unitRepository = unitRepository; this.unitService = unitService;
_settingsFromDb = settingsFromDb; _settingsFromDb = settingsFromDb;
} }
public async Task SyncAsync(List<AihitData> aihitData)
public async Task SyncAsync(List<AihitData> aihitdata)
{ {
var validPairs = ValidateInput(aihitData); // 1. Сначала фильтруем и нормализуем входящий мусор
var validPairs = ValidateInput(aihitdata);
if (validPairs.Count == 0) // Если пришел пустой список, то и проверять порог нет смысла (лог уже записан внутри)
return; if (!validPairs.Any()) return;
if (!await PassSafeguardCheckAsync(validPairs.Count)) // 2. FAIL-FAST: Быстро узнаем общее число связей в БД без выкачивания самих данных
return; int previousCount = await unitService.Get()
var unitNames = ExtractUnitNames(validPairs);
var unitsByName = await GetOrCreateUnitsAsync(unitNames);
var (toRemove, toAdd) = await GetDeltaAsync(validPairs);
await using var transaction = await _unitRepository.BeginTransactionAsync();
try
{
await RemoveRelationshipsAsync(toRemove);
await AddRelationshipsAsync(toAdd, unitsByName);
await CommitChangesAsync(toRemove.Count, toAdd.Count);
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
private List<(string ParentName, string ChildName)> ValidateInput(List<AihitData> data)
{
if (data == null || data.Count == 0)
{
_logger.LogWarning("Получены пустые данные из АИХ ИТ. Синхронизация пропущена");
return new List<(string, string)>();
}
var validPairs = data
.Where(item => !string.IsNullOrWhiteSpace(item.ParentName) && !string.IsNullOrWhiteSpace(item.ChildName))
.Where(item => item.ParentName != item.ChildName)
.Select(item => (
ParentName: item.ParentName!.Trim().ToUpperInvariant(),
ChildName: item.ChildName!.Trim().ToUpperInvariant()
))
.Distinct()
.ToList();
if (validPairs.Count == 0)
{
_logger.LogWarning("После нормализации не осталось валидных связей. Синхронизация пропущена");
return new List<(string, string)>();
}
_logger.LogInformation("Получено {Count} валидных связей", validPairs.Count);
return validPairs;
}
private async Task<bool> PassSafeguardCheckAsync(int incomingCount)
{
var previousCount = await _unitRepository.Get()
.SelectMany(u => u.ChildUnits) .SelectMany(u => u.ChildUnits)
.CountAsync(); .CountAsync();
if (previousCount == 0) // 3. SAFEGUARD COMPLIANCE: Проверяем защитный порог падения данных
return true; if (previousCount > 0)
{
// 1. Считаем в decimal с абсолютной точностью
decimal exactPercentage = ((decimal)validPairs.Count / previousCount) * 100;
var currentPercentage = Math.Round((decimal)incomingCount / previousCount * 100, 1, MidpointRounding.AwayFromZero); // 2. Округляем до 1 знака после запятой (например, 96.98% -> 97.0%)
// Это защитит от ложных срабатываний из-за пары недостающих связей на больших объемах
decimal currentPercentage = Math.Round(exactPercentage, 1, MidpointRounding.AwayFromZero);
// 3. Строгое сравнение (<) гарантирует пропуск при ровно 97% и работу "0" как выключателя
if (currentPercentage < _settingsFromDb.MinRelationshipsThresholdPct) if (currentPercentage < _settingsFromDb.MinRelationshipsThresholdPct)
{ {
_logger.LogWarning( logger.LogWarning(
"Синхронизация отменена: количество полученных связей ниже порогового значения. " + "Синхронизация отменена: количество полученных связей ниже порогового значения! " +
"Получено: {CurrentCount} ({CurrentPercentage:F1}%), порог: {Threshold}% от прошлого объема ({PreviousCount})", "Получено: {CurrentCount} ({CurrentPercentage:F1}%), ожидалось >= {Threshold}% от прошлого объема ({PreviousCount}).",
incomingCount, currentPercentage, _settingsFromDb.MinRelationshipsThresholdPct, previousCount); validPairs.Count, currentPercentage, _settingsFromDb.MinRelationshipsThresholdPct, previousCount);
return false;
return;
}
} }
return true; // 4. HAPPY PATH: Если проверка пройдена, выполняем тяжелую работу
var sourceUnitNames = ExtractUnitNames(validPairs);
var existingUnits = await GetOrCreateUnitsAsync(sourceUnitNames);
var (toRemove, toAdd) = await GetDeltaAsync(validPairs);
await RemoveRelationshipsAsync(toRemove);
await AddRelationshipsAsync(toAdd, existingUnits);
await FinalCommitAsync(toRemove.Count, toAdd.Count);
} }
private static List<string> ExtractUnitNames(List<(string ParentName, string ChildName)> pairs)
private List<(string Parent, string Child)> ValidateInput(List<AihitData> data)
{
if (data == null || data.Count == 0)
{
logger.LogWarning("Получены пустые или null данные из АИХ ИТ. Пропускаю синхронизацию");
return null!;
}
var validPairs = data
.Where(t => !string.IsNullOrWhiteSpace(t.ParentName) && !string.IsNullOrWhiteSpace(t.ChildName))
.Where(t => t.ParentName != t.ChildName)
.Select(t => (
Parent: t.ParentName!.Trim().ToUpperInvariant(),
Child: t.ChildName!.Trim().ToUpperInvariant()
))
.Distinct()
.ToList();
if (validPairs.Count == 0)
{
logger.LogWarning("После нормализации не осталось валидных связей. Пропускаю синхронизацию");
return new();
}
logger.LogInformation("Получено {Count} валидных связей", validPairs.Count);
return validPairs;
}
private static List<string> ExtractUnitNames(List<(string Parent, string Child)> pairs)
{ {
return pairs return pairs
.SelectMany(pair => new[] { pair.ParentName, pair.ChildName }) .SelectMany(x => new[] { x.Parent, x.Child })
.Distinct() .Distinct()
.ToList(); .ToList();
} }
private async Task<Dictionary<string, Unit>> GetOrCreateUnitsAsync(List<string> names) private async Task<Dictionary<string, Unit>> GetOrCreateUnitsAsync(List<string> names)
{ {
var existingUnits = await _unitRepository.Get() var existing = await unitService.Get()
.AsNoTracking() .AsNoTracking()
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal); .ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
var missingNames = names.Except(existingUnits.Keys).ToList(); var missing = names.Except(existing.Keys).ToList();
if (!missing.Any()) return existing;
if (missingNames.Count == 0) logger.LogInformation("Создание отсутствующих Unit:{Count}", missing.Count);
return existingUnits; foreach (var name in missing)
{
_logger.LogInformation("Создание отсутствующих юнитов: {Count}", missingNames.Count); var unit = new Unit
var newUnits = missingNames.Select(name => new Unit
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
Name = name, Name = name,
DateCreated = DateTimeOffset.UtcNow DateCreated = DateTimeOffset.UtcNow
}).ToList(); };
_unitRepository.CreateRange(newUnits); if (await unitService.CreateAsync(unit))
await _unitRepository.CommitAsync();
foreach (var unit in newUnits)
{ {
existingUnits[unit.Name] = unit; logger.LogInformation("Создан Unit: {Name}", name);
_logger.LogDebug("Создан юнит: {Name}", unit.Name); existing[name] = unit;
}
else
logger.LogError("Не удалось создать Unit: {Name}", name);
} }
return existingUnits; await unitService.CommitAsync();
return existing;
} }
private async Task<(List<ExistingRelationship> ToRemove, List<(string ParentName, string ChildName)> ToAdd)> GetDeltaAsync(
List<(string ParentName, string ChildName)> sourcePairs) private async Task<(List<ExistingRelationship> ToRemove, List<(string, string)> ToAdd)> GetDeltaAsync(List<(string Parent, string Child)> sourcePairs)
{ {
var allExisting = await _unitRepository.Get() var allExistings = await unitService.Get()
.AsNoTracking() .AsNoTracking()
.Include(u => u.ChildUnits).ThenInclude(r => r.ChildUnit) .Include(u => u.ChildUnits).ThenInclude(r => r.ChildUnit)
.Where(u => u.ChildUnits.Any()) .Where(u => u.ChildUnits.Any())
@@ -157,73 +155,79 @@ internal class RelationshipsSyncService : IRelationshipsSyncService
ParentName = parent.Name, ParentName = parent.Name,
ChildName = relationship.ChildUnit!.Name, ChildName = relationship.ChildUnit!.Name,
Relationship = relationship Relationship = relationship
}) }
)
.ToListAsync(); .ToListAsync();
var sourceSet = new HashSet<(string, string)>(sourcePairs); var sourceSet = new HashSet<(string, string)>(sourcePairs);
var existingSet = new HashSet<(string, string)>(allExisting.Select(x => (x.ParentName, x.ChildName))); var existingSet = new HashSet<(string, string)>(allExistings.Select(x => (x.ParentName, x.ChildName)));
var toRemove = allExisting.Where(r => !sourceSet.Contains((r.ParentName, r.ChildName))).ToList(); var toRemove = allExistings.Where(r => !sourceSet.Contains((r.ParentName, r.ChildName))).ToList();
var toAdd = sourcePairs.Where(p => !existingSet.Contains(p)).ToList(); var toAdd = sourcePairs.Where(p => !existingSet.Contains(p)).ToList();
_logger.LogInformation("Дельта: удаление {ToRemove}, добавление {ToAdd}", toRemove.Count, toAdd.Count); logger.LogInformation("Связей для удаления: {ToRemove}, для добавления: {ToAdd}", toRemove.Count, toAdd.Count);
return (toRemove, toAdd); return (toRemove, toAdd);
} }
private async Task RemoveRelationshipsAsync(List<ExistingRelationship> toRemove) private async Task RemoveRelationshipsAsync(List<ExistingRelationship> toRemove)
{ {
if (toRemove.Count == 0) if (!toRemove.Any()) return;
return;
var parentNames = toRemove.Select(r => r.ParentName).Distinct().ToList(); var parentNames = toRemove.Select(r => r.ParentName).Distinct().ToList();
var parents = await _unitRepository.Get() var parents = await unitService.Get()
.Include(u => u.ChildUnits) .Include(u => u.ChildUnits)
.Where(u => parentNames.Contains(u.Name)) .Where(u => parentNames.Contains(u.Name))
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal); .ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
foreach (var relationship in toRemove) foreach (var rel in toRemove)
{ {
if (!parents.TryGetValue(relationship.ParentName, out var parent)) if (!parents.TryGetValue(rel.ParentName, out var parent))
{ {
_logger.LogWarning("Родитель '{Parent}' не найден при удалении связи с '{Child}'", logger.LogWarning("Родитель '{Parent}' не найден при попытке удаления связи - '{Child}'", rel.ParentName, rel.ChildName);
relationship.ParentName, relationship.ChildName);
continue; continue;
} }
var entityToRemove = parent.ChildUnits var relationshipToRemove = parent.ChildUnits
.FirstOrDefault(r => r.ChildUnitId == relationship.Relationship.ChildUnitId); .FirstOrDefault(r => r.ChildUnitId == rel.Relationship.ChildUnitId);
if (entityToRemove != null) if (relationshipToRemove != null)
parent.ChildUnits.Remove(entityToRemove);
}
}
private async Task AddRelationshipsAsync(
List<(string ParentName, string ChildName)> toAdd,
Dictionary<string, Unit> unitsByName)
{ {
if (toAdd.Count == 0) logger.LogInformation("Удаление связи: '{Parent}' - '{Child}'", rel.ParentName, rel.ChildName);
return; parent.ChildUnits.Remove(relationshipToRemove);
}
else
{
logger.LogWarning("Связь '{Parent}'-'{Child}' не найдена в коллекции ChildUnits для удаления", rel.ParentName, rel.ChildName);
}
}
}
var parentNames = toAdd.Select(x => x.ParentName).Distinct().ToList(); private async Task AddRelationshipsAsync(List<(string Parent, string Child)> toAdd, Dictionary<string, Unit> allUnits)
{
if (!toAdd.Any()) return;
var parents = await _unitRepository.Get() var parentNames = toAdd.Select(x => x.Parent).Distinct().ToList();
var parents = await unitService.Get()
.Include(u => u.ChildUnits) .Include(u => u.ChildUnits)
.Where(u => parentNames.Contains(u.Name)) .Where(u => parentNames.Contains(u.Name))
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal); .ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
foreach (var (parentName, childName) in toAdd) foreach (var (Parent, Child) in toAdd)
{ {
if (!parents.TryGetValue(parentName, out var parent) || if (!parents.TryGetValue(Parent, out var parent) ||
!unitsByName.TryGetValue(childName, out var child)) !allUnits.TryGetValue(Child, out var child))
{ {
_logger.LogWarning("Пропущена связь '{Parent}' - '{Child}': юнит не найден", parentName, childName); logger.LogWarning("Пропущена связь '{Parent}' - '{Child}': Unit не найден", Parent, Child);
continue; continue;
} }
if (parent.ChildUnits.Any(r => r.ChildUnitId == child.Id)) if (parent!.ChildUnits.Any(r => r.ChildUnitId == child.Id))
{
logger.LogWarning("Связь уже существует: '{Parent}' - '{Child}'", Parent, Child);
continue; continue;
}
parent.ChildUnits.Add(new UnitInUnit parent.ChildUnits.Add(new UnitInUnit
{ {
@@ -231,27 +235,34 @@ internal class RelationshipsSyncService : IRelationshipsSyncService
ChildUnitId = child.Id, ChildUnitId = child.Id,
DateCreated = DateTimeOffset.UtcNow DateCreated = DateTimeOffset.UtcNow
}); });
logger.LogInformation("Добавлена связь: '{Parent}' - '{Child}'", Parent, Child);
} }
} }
private async Task CommitChangesAsync(int removedCount, int addedCount)
private async Task FinalCommitAsync(int removedCount, int addedCount)
{ {
if (removedCount == 0 && addedCount == 0) if (removedCount > 0 || addedCount > 0)
{ {
_logger.LogInformation("Изменений не обнаружено"); if (await unitService.CommitAsync())
return; {
logger.LogInformation("Синхронизация завершена. Удалено: {Removed}, добавлено: {Added}", removedCount, addedCount);
} }
else
if (!await _unitRepository.CommitAsync()) logger.LogError("Не удалось сохранить изменения в БД");
throw new InvalidOperationException("Не удалось сохранить изменения связей в БД"); }
else
_logger.LogInformation("Синхронизация завершена. Удалено: {Removed}, добавлено: {Added}", removedCount, addedCount); logger.LogInformation("Изменений не обнаружено");
} }
private sealed class ExistingRelationship private sealed class ExistingRelationship
{ {
public string ParentName { get; init; } = null!; public string ParentName { get; init; }
public string ChildName { get; init; } = null!; public string ChildName { get; init; }
public UnitInUnit Relationship { get; init; } = null!; public UnitInUnit Relationship { get; init; }
}
} }
} }