using Elecciones.Database; using Elecciones.Infrastructure.Services; using Elecciones.Worker; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Net; using Serilog; using System.Net.Http; using System.Net.Security; using System.Security.Authentication; Log.Logger = new LoggerConfiguration() .WriteTo.Console() .CreateBootstrapLogger(); Log.Information("Iniciando Elecciones.Worker Host..."); var builder = Host.CreateApplicationBuilder(args); builder.Services.AddSerilog(config => config .ReadFrom.Configuration(builder.Configuration) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File("logs/worker-.log", rollingInterval: RollingInterval.Day)); // --- Configuración de Servicios --- var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext(options => options.UseSqlServer(connectionString)); builder.Services.AddHttpClient("ElectoralApiClient", client => { var baseUrl = builder.Configuration["ElectoralApi:BaseUrl"]; if (!string.IsNullOrEmpty(baseUrl)) { client.BaseAddress = new Uri(baseUrl); } // --- TIMEOUT MÁS LARGO --- // Aumentamos el tiempo de espera a 90 segundos. // Esto le dará a las peticiones lentas de la API tiempo suficiente para responder. client.Timeout = TimeSpan.FromSeconds(90); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"); client.DefaultRequestHeaders.Add("Accept", "*/*"); client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br"); client.DefaultRequestHeaders.Add("Connection", "keep-alive"); }) .ConfigurePrimaryHttpMessageHandler(() => { var handler = new SocketsHttpHandler { // Habilita la descompresión automática de respuestas GZIP y Deflate. // Esto soluciona el error de JsonException ('0x1F'). AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, SslOptions = new SslClientAuthenticationOptions { EnabledSslProtocols = SslProtocols.Tls13, } }; if (!OperatingSystem.IsWindows()) { handler.SslOptions.CipherSuitesPolicy = new CipherSuitesPolicy(new[] { TlsCipherSuite.TLS_AES_128_GCM_SHA256, TlsCipherSuite.TLS_AES_256_GCM_SHA384, TlsCipherSuite.TLS_CHACHA20_POLY1305_SHA256 }); } return handler; }); builder.Services.AddSingleton(); builder.Services.AddHostedService(); var host = builder.Build(); try { host.Run(); } catch (Exception ex) { Log.Fatal(ex, "El Host de Elecciones.Worker terminó inesperadamente"); } finally { Log.CloseAndFlush(); }