using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; using AsbCloudApp.Repositories; using AsbCloudApp.Services; using AsbCloudInfrastructure.Background; using Microsoft.Extensions.DependencyInjection; namespace AsbCloudInfrastructure.Services.DetectOperations; public class WorkOperationDetection: Work { public WorkOperationDetection() :base("Operation detection") { Timeout = TimeSpan.FromMinutes(20); OnErrorAsync = (id, exception, token) => { var text = $"work {id}, when {CurrentState?.State}, throw error:{exception.Message}"; Trace.TraceWarning(text); return Task.CompletedTask; }; } protected override async Task Action(string id, IServiceProvider services, Action onProgressCallback, CancellationToken token) { var telemetryRepository = services.GetRequiredService>(); var detectedOperationRepository = services.GetRequiredService(); var detectedOperationService = services.GetRequiredService(); var telemetryIds = (await telemetryRepository.GetAllAsync(token)) .Select(t => t.Id); var lastDetectedDates = await detectedOperationRepository.GetLastDetectedDatesAsync(token); var beginDatesDetectOperations = new List<(int TelemetryId, DateTimeOffset? BeginDate)>(); foreach (var telemetryId in telemetryIds) { if (lastDetectedDates.TryGetValue(telemetryId, out var beginDate)) { beginDatesDetectOperations.Add((telemetryId, beginDate)); continue; } beginDatesDetectOperations.Add((telemetryId, null)); } var count = beginDatesDetectOperations.Count; for (var i = 0; i < count; i++) { var (idTelemetry, beginDate) = beginDatesDetectOperations[i]; onProgressCallback($"Start detecting telemetry: {idTelemetry} from {beginDate}", i++ / count); var detectedOperations = await detectedOperationService.DetectOperationsAsync(idTelemetry, beginDate, token); if (detectedOperations.Any()) await detectedOperationRepository.InsertRangeAsync(detectedOperations, token); } } }