Try TimeOut Telegramas
This commit is contained in:
@@ -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,8 +759,14 @@ 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);
|
||||||
|
|
||||||
|
var originalTimeout = innerDbContext.Database.GetCommandTimeout();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
innerDbContext.Database.SetCommandTimeout(180);
|
||||||
|
_logger.LogDebug("Timeout de BD aumentado a 180s para descarga de telegramas.");
|
||||||
|
|
||||||
int contadorLote = 0;
|
int contadorLote = 0;
|
||||||
const int tamanoLote = 5; // Cantidad a Guarda Por Lote
|
const int tamanoLote = 100;
|
||||||
|
|
||||||
foreach (var mesaId in nuevosTelegramasIds)
|
foreach (var mesaId in nuevosTelegramasIds)
|
||||||
{
|
{
|
||||||
@@ -780,40 +783,45 @@ public class LowPriorityDataWorker : BackgroundService
|
|||||||
var nuevoTelegrama = new Telegrama
|
var nuevoTelegrama = new Telegrama
|
||||||
{
|
{
|
||||||
Id = telegramaFile.NombreArchivo,
|
Id = telegramaFile.NombreArchivo,
|
||||||
// 3. Usamos el ID del ÁMBITO DE LA MESA, no el del municipio.
|
|
||||||
AmbitoGeograficoId = ambitoMesa.Id,
|
AmbitoGeograficoId = ambitoMesa.Id,
|
||||||
ContenidoBase64 = telegramaFile.Imagen,
|
ContenidoBase64 = telegramaFile.Imagen,
|
||||||
FechaEscaneo = DateTime.Parse(telegramaFile.FechaEscaneo).ToUniversalTime(),
|
FechaEscaneo = DateTime.Parse(telegramaFile.FechaEscaneo).ToUniversalTime(),
|
||||||
FechaTotalizacion = DateTime.Parse(telegramaFile.FechaTotalizacion).ToUniversalTime()
|
FechaTotalizacion = DateTime.Parse(telegramaFile.FechaTotalizacion).ToUniversalTime()
|
||||||
};
|
};
|
||||||
await innerDbContext.Telegramas.AddAsync(nuevoTelegrama, stoppingToken);
|
await innerDbContext.Telegramas.AddAsync(nuevoTelegrama, stoppingToken);
|
||||||
contadorLote++; // Incrementamos el contador
|
contadorLote++;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
_logger.LogWarning("No se encontró un ámbito geográfico para la mesa con MesaId {MesaId}. El telegrama no será guardado.", mesaId);
|
_logger.LogWarning("No se encontró un ámbito geográfico para la mesa con MesaId {MesaId}. El telegrama no será guardado.", mesaId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await Task.Delay(250, stoppingToken); // Mantenemos el delay para no saturar la API
|
await Task.Delay(250, stoppingToken);
|
||||||
|
|
||||||
// Si hemos alcanzado el tamaño del lote, guardamos y reseteamos.
|
|
||||||
if (contadorLote >= tamanoLote)
|
if (contadorLote >= tamanoLote)
|
||||||
{
|
{
|
||||||
await innerDbContext.SaveChangesAsync(stoppingToken);
|
await innerDbContext.SaveChangesAsync(stoppingToken);
|
||||||
_logger.LogInformation("Guardado un lote de {count} telegramas.", contadorLote);
|
_logger.LogInformation("Guardado un lote de {count} telegramas.", contadorLote);
|
||||||
contadorLote = 0; // Reseteamos el contador para el siguiente lote
|
contadorLote = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guardamos cualquier registro restante que no haya completado un lote completo.
|
|
||||||
if (contadorLote > 0)
|
if (contadorLote > 0)
|
||||||
{
|
{
|
||||||
await innerDbContext.SaveChangesAsync(stoppingToken);
|
await innerDbContext.SaveChangesAsync(stoppingToken);
|
||||||
_logger.LogInformation("Guardado el último lote de {count} telegramas.", contadorLote);
|
_logger.LogInformation("Guardado el último lote de {count} telegramas.", contadorLote);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
innerDbContext.Database.SetCommandTimeout(originalTimeout);
|
||||||
|
_logger.LogDebug("Timeout de BD restaurado a su valor original ({timeout}s).", originalTimeout);
|
||||||
}
|
}
|
||||||
|
} // Fin del if (nuevosTelegramasIds.Any())
|
||||||
|
|
||||||
|
// Movemos el delay aquí para que solo se ejecute si hubo telegramas en la respuesta de la API
|
||||||
await Task.Delay(100, stoppingToken);
|
await Task.Delay(100, stoppingToken);
|
||||||
|
} // Fin del if (listaTelegramasApi is not null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_logger.LogInformation("Sondeo de Telegramas completado.");
|
_logger.LogInformation("Sondeo de Telegramas completado.");
|
||||||
|
|||||||
Reference in New Issue
Block a user