using System; 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) .ToArray(); var lastDetectedDates = await detectedOperationRepository.GetLastDetectedDatesAsync(token); for (var i = 0; i < telemetryIds.Length; i++) { var telemetryId = telemetryIds[i]; var beginDate = lastDetectedDates.TryGetValue(telemetryId, out var date) ? date : (DateTimeOffset?)null; onProgressCallback($"Start detecting telemetry: {telemetryId} from {beginDate}", i++ / telemetryIds.Length); var detectedOperations = await detectedOperationService.DetectOperationsAsync(telemetryId, beginDate, token); if (detectedOperations.Any()) await detectedOperationRepository.InsertRangeAsync(detectedOperations, token); } } }