using LCU.Api.Internal.Dispatcher.Services.QueueServices; using LCU.Api.Internal.MaidBotLib.Models; using LCU.Library.Internal.DispatcherModels.Enums; using LCU.Library.Internal.DispatcherModels.Models.Requests; using System.Collections.Generic; using System.Threading; namespace LCU.Api.Internal.Dispatcher.Services.DispatcherOperationServices; public class BatchErroredJobsService : IBatchErroredJobsService { private readonly IQueueSendErroredJobAlertService _queueSendErroredJobAlertService; private readonly IJobService _jobService; public BatchErroredJobsService(IJobService jobService, IQueueSendErroredJobAlertService queueSendErroredJobAlertService) { _jobService = jobService; _queueSendErroredJobAlertService = queueSendErroredJobAlertService; } public async Task PerformBatchErroredJobs(CancellationToken cancellationToken) { try { var jobs = await _jobService.GetErrorMonitoringJobs(); if (jobs == null || !jobs.Any()) { return; } var batchedErroredJobAlertRequest = CreateBatchedErroredJobAlerts(jobs); await _queueSendErroredJobAlertService.QueueSendErroredJobAlert(batchedErroredJobAlertRequest); } catch (Exception ex) { //Fatal as we need to know if we can't get out our errors Log.ForContext(nameof(PropertyEnum.Group), nameof(GroupEnum.ITDevelopment)) .Fatal(ex, $"Failed to perform Error Monitoring."); } } private static BatchedErroredJobAlertRequest CreateBatchedErroredJobAlerts(IEnumerable jobs) { var batchedErroredJobAlertRequests = new BatchedErroredJobAlertRequest() { ErroredJobAlertRequests = new List() }; foreach (var job in jobs) { var failedOrProcessingWorkItem = job.WorkItems .FirstOrDefault(wi => wi.WorkItemExecutions != null && wi.WorkItemExecutions.Any(wie => wie.Status == StatusType.Failed || wie.Status == StatusType.Processing)); if (failedOrProcessingWorkItem == null || failedOrProcessingWorkItem.CurrentWorkItemExecution == null) { Log.Warning($"Failed or Processing workItem not found during CreateBatchedErroredJobAlerts. JobId and Name: {job.JobId}: {job.Name}"); continue; } batchedErroredJobAlertRequests.ErroredJobAlertRequests.Add(new ErroredJobAlertRequest { CurrentJob = job, CurrentWorkItem = failedOrProcessingWorkItem }); } return batchedErroredJobAlertRequests; } }