Try TimeOut Telegramas

This commit is contained in:
2025-09-08 14:19:16 -03:00
parent 9e0cf30294
commit d091d91f89

View File

@@ -727,14 +727,11 @@ public class LowPriorityDataWorker : BackgroundService
using var scope = _serviceProvider.CreateScope(); using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<EleccionesDbContext>(); var dbContext = scope.ServiceProvider.GetRequiredService<EleccionesDbContext>();
var partidos = await dbContext.AmbitosGeograficos // La obtención de partidos y categorías no cambia
.AsNoTracking() var partidos = await dbContext.AmbitosGeograficos.AsNoTracking()
.Where(a => a.NivelId == 30 && a.DistritoId != null && a.SeccionId != null) .Where(a => a.NivelId == 30 && a.DistritoId != null && a.SeccionId != null)
.ToListAsync(stoppingToken); .ToListAsync(stoppingToken);
var categorias = await dbContext.CategoriasElectorales.AsNoTracking().ToListAsync(stoppingToken);
var categorias = await dbContext.CategoriasElectorales
.AsNoTracking()
.ToListAsync(stoppingToken);
if (!partidos.Any() || !categorias.Any()) return; if (!partidos.Any() || !categorias.Any()) return;
@@ -748,13 +745,13 @@ public class LowPriorityDataWorker : BackgroundService
if (listaTelegramasApi is { Count: > 0 }) if (listaTelegramasApi is { Count: > 0 })
{ {
// Creamos el DbContext para la operación de guardado
using var innerScope = _serviceProvider.CreateScope(); using var innerScope = _serviceProvider.CreateScope();
var innerDbContext = innerScope.ServiceProvider.GetRequiredService<EleccionesDbContext>(); var innerDbContext = innerScope.ServiceProvider.GetRequiredService<EleccionesDbContext>();
var idsYaEnDb = await innerDbContext.Telegramas var idsYaEnDb = await innerDbContext.Telegramas
.Where(t => listaTelegramasApi.Contains(t.Id)) .Where(t => listaTelegramasApi.Contains(t.Id))
.Select(t => t.Id) .Select(t => t.Id).ToListAsync(stoppingToken);
.ToListAsync(stoppingToken);
var nuevosTelegramasIds = listaTelegramasApi.Except(idsYaEnDb).ToList(); var nuevosTelegramasIds = listaTelegramasApi.Except(idsYaEnDb).ToList();
@@ -762,58 +759,69 @@ public class LowPriorityDataWorker : BackgroundService
{ {
_logger.LogInformation("Se encontraron {count} telegramas nuevos en '{partido}' para '{cat}'. Descargando...", nuevosTelegramasIds.Count, partido.Nombre, categoria.Nombre); _logger.LogInformation("Se encontraron {count} telegramas nuevos en '{partido}' para '{cat}'. Descargando...", nuevosTelegramasIds.Count, partido.Nombre, categoria.Nombre);
int contadorLote = 0; var originalTimeout = innerDbContext.Database.GetCommandTimeout();
const int tamanoLote = 5; // Cantidad a Guarda Por Lote try
foreach (var mesaId in nuevosTelegramasIds)
{ {
if (stoppingToken.IsCancellationRequested) return; innerDbContext.Database.SetCommandTimeout(180);
_logger.LogDebug("Timeout de BD aumentado a 180s para descarga de telegramas.");
var telegramaFile = await _apiService.GetTelegramaFileAsync(authToken, mesaId); int contadorLote = 0;
if (telegramaFile != null) const int tamanoLote = 100;
foreach (var mesaId in nuevosTelegramasIds)
{ {
var ambitoMesa = await innerDbContext.AmbitosGeograficos.AsNoTracking() if (stoppingToken.IsCancellationRequested) return;
.FirstOrDefaultAsync(a => a.MesaId == mesaId, stoppingToken);
if (ambitoMesa != null) var telegramaFile = await _apiService.GetTelegramaFileAsync(authToken, mesaId);
if (telegramaFile != null)
{ {
var nuevoTelegrama = new Telegrama var ambitoMesa = await innerDbContext.AmbitosGeograficos.AsNoTracking()
.FirstOrDefaultAsync(a => a.MesaId == mesaId, stoppingToken);
if (ambitoMesa != null)
{ {
Id = telegramaFile.NombreArchivo, var nuevoTelegrama = new Telegrama
// 3. Usamos el ID del ÁMBITO DE LA MESA, no el del municipio. {
AmbitoGeograficoId = ambitoMesa.Id, Id = telegramaFile.NombreArchivo,
ContenidoBase64 = telegramaFile.Imagen, AmbitoGeograficoId = ambitoMesa.Id,
FechaEscaneo = DateTime.Parse(telegramaFile.FechaEscaneo).ToUniversalTime(), ContenidoBase64 = telegramaFile.Imagen,
FechaTotalizacion = DateTime.Parse(telegramaFile.FechaTotalizacion).ToUniversalTime() FechaEscaneo = DateTime.Parse(telegramaFile.FechaEscaneo).ToUniversalTime(),
}; FechaTotalizacion = DateTime.Parse(telegramaFile.FechaTotalizacion).ToUniversalTime()
await innerDbContext.Telegramas.AddAsync(nuevoTelegrama, stoppingToken); };
contadorLote++; // Incrementamos el contador await innerDbContext.Telegramas.AddAsync(nuevoTelegrama, stoppingToken);
contadorLote++;
}
else
{
_logger.LogWarning("No se encontró un ámbito geográfico para la mesa con MesaId {MesaId}. El telegrama no será guardado.", mesaId);
}
} }
else await Task.Delay(250, stoppingToken);
if (contadorLote >= tamanoLote)
{ {
_logger.LogWarning("No se encontró un ámbito geográfico para la mesa con MesaId {MesaId}. El telegrama no será guardado.", mesaId); await innerDbContext.SaveChangesAsync(stoppingToken);
_logger.LogInformation("Guardado un lote de {count} telegramas.", contadorLote);
contadorLote = 0;
} }
} }
await Task.Delay(250, stoppingToken); // Mantenemos el delay para no saturar la API
// Si hemos alcanzado el tamaño del lote, guardamos y reseteamos. if (contadorLote > 0)
if (contadorLote >= tamanoLote)
{ {
await innerDbContext.SaveChangesAsync(stoppingToken); await innerDbContext.SaveChangesAsync(stoppingToken);
_logger.LogInformation("Guardado un lote de {count} telegramas.", contadorLote); _logger.LogInformation("Guardado el último lote de {count} telegramas.", contadorLote);
contadorLote = 0; // Reseteamos el contador para el siguiente lote
} }
} }
finally
// Guardamos cualquier registro restante que no haya completado un lote completo.
if (contadorLote > 0)
{ {
await innerDbContext.SaveChangesAsync(stoppingToken); innerDbContext.Database.SetCommandTimeout(originalTimeout);
_logger.LogInformation("Guardado el último lote de {count} telegramas.", contadorLote); _logger.LogDebug("Timeout de BD restaurado a su valor original ({timeout}s).", originalTimeout);
} }
} } // Fin del if (nuevosTelegramasIds.Any())
}
await Task.Delay(100, stoppingToken); // Movemos el delay aquí para que solo se ejecute si hubo telegramas en la respuesta de la API
await Task.Delay(100, stoppingToken);
} // Fin del if (listaTelegramasApi is not null)
} }
} }
_logger.LogInformation("Sondeo de Telegramas completado."); _logger.LogInformation("Sondeo de Telegramas completado.");