using System.Reflection; using System.Text; using FastEndpoints; using FastEndpoints.Swagger; using GB5Shared.Connection; using GB5Shared.Telemetry; using GB5Shared.DateConverter; using static GB5Shared.DateConverter.GB5JsonOptions; using GB5Shared.DTO.Framework.CommonConfig; using GB5Shared.DTO.Framework.Login; using GB5Shared.GB5CommonFunction; using GB5Shared.GenerateAutoNumber; using GB5Shared.ListQuery; using GB5Shared.QueryExecutor; using GB5Shared.Validation; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Caching.Hybrid; using Newtonsoft.Json; using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; using OpenTelemetry.Trace; // ------------------------- // Bootstrap // ------------------------- var builder = WebApplication.CreateBuilder(args); // ── Port from config — change "AppPort" in appsettings.json to use any port ── var appPort = builder.Configuration.GetValue("AppPort"); builder.WebHost.UseUrls($"http://0.0.0.0:{appPort}"); // ------------------------- // Console Encoding // ------------------------- Console.OutputEncoding = Encoding.UTF8; // ------------------------- // Dapr & Controllers Setup // ------------------------- builder.Services.AddDaprClient(); builder.Services.AddControllers() .AddDapr() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; options.JsonSerializerOptions.DictionaryKeyPolicy = null; options.JsonSerializerOptions.AddGB5Converters(); }); // ------------------------- // JSON Global (Minimal API / HttpContext) // ------------------------- builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.PropertyNamingPolicy = null; options.SerializerOptions.DictionaryKeyPolicy = null; options.SerializerOptions.AddGB5Converters(); }); // ------------------------- // Caching // ------------------------- #pragma warning disable EXTEXP0018 builder.Services.AddHybridCache(options => { options.DefaultEntryOptions = new HybridCacheEntryOptions(); options.DisableCompression = false; }); #pragma warning restore EXTEXP0018 builder.Services.AddMemoryCache(); builder.Services.AddDistributedMemoryCache(); // ------------------------- // CORS Policy // ------------------------- // ------------------------- // HTTP Context // ------------------------- builder.Services.AddHttpContextAccessor(); // ------------------------- // Login Header (per-request from HTTP header) // ------------------------- // ⚠ FOR HTTP ENDPOINTS ONLY. // Returns empty DTO instead of throwing — prevents crashes in // background scopes that transitively touch this registration. builder.Services.AddScoped(sp => { var httpContext = sp.GetRequiredService().HttpContext; if (httpContext != null && httpContext.Request.Headers.TryGetValue("Login", out var loginHeader)) return JsonConvert.DeserializeObject(loginHeader!)!; return new LoginDTO(); }); // ------------------------- // Application Services // ------------------------- builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.Configure( builder.Configuration.GetSection("Gb5SystemDTO")); // ------------------------- // Kestrel // ------------------------- builder.Services.Configure(options => { options.AllowSynchronousIO = true; }); // ------------------------- // Response Compression // ------------------------- builder.Services.AddResponseCompression(o => { o.EnableForHttps = true; o.Providers.Add(); }); // -- OpenTelemetry (Tracing + Metrics) ---------------------------------------- builder.Services.AddGB5Telemetry(builder.Configuration, "GB5-PIE"); // ------------------------- // Assembly Scan for DI // ------------------------- // PIE uses PostgreSQL — IQueryExecutor routes to the correct DB engine at runtime // via LoginDTO.DatabaseType. No special registration needed beyond the standard QueryExecutor. var pieBLLAssembly = Assembly.Load("PIEBLL"); var pieDALAssembly = Assembly.Load("PIEDAL"); builder.Services.Scan(scan => scan .FromAssemblies(pieBLLAssembly, pieDALAssembly) .AddClasses(c => c.Where(t => !t.IsAbstract && !t.IsInterface && (t.Namespace == null || !t.Namespace.Contains(".DTO")))) .AsImplementedInterfaces() .WithScopedLifetime()); // IListDispatcher + GenericListHandler + IQueryBuilder registrations // Scans PIEDAL for all IQueryBuilder implementations and auto-registers // GenericListHandler as IListHandler for each one found. builder.Services.AddListInfrastructure(pieDALAssembly); // ------------------------- // FastEndpoints // ------------------------- var endpointAssemblies = new[] { Assembly.Load("PIESL"), Assembly.Load("PIEBLL"), Assembly.Load("PIEDAL"), Assembly.Load("GB5Shared") }; builder.Services.AddFastEndpoints(o => { o.Assemblies = endpointAssemblies; }); // ------------------------- // Swagger // ------------------------- builder.Services.SwaggerDocument(o => { o.DocumentSettings = s => { s.Title = "GB5 PIE API"; s.Version = "v1"; s.Description = "GB5 Product Intelligence Engine Microservice — global module/config/variant/profile knowledge store"; }; }); // ------------------------- // Build App // ------------------------- var app = builder.Build(); // ------------------------- // Middleware // ------------------------- // 1. Reverse-proxy header forwarding (must be first) app.UseForwardedHeaders(); // 2. CORS (before auth) // 3. Response Compression app.UseResponseCompression(); // 4. Dapr CloudEvents + pub/sub subscription handler app.UseCloudEvents(); // 5. Session heartbeat + FastEndpoints app.UseMiddleware(); app.UseMiddleware(); app.UseFastEndpoints(c => { c.Serializer.Options.PropertyNamingPolicy = null; c.Serializer.Options.DictionaryKeyPolicy = null; c.Serializer.Options.AddGB5Converters(); }); // 6. MVC Controllers (Dapr subscribers use controller-based subscription) app.MapControllers(); // 7. Dapr subscribe handler app.MapSubscribeHandler(); // ------------------------- // Swagger UI (All Environments) // ------------------------- app.UseOpenApi(); app.UseSwaggerUi(o => { o.Path = "/GB5Documentation"; o.DocumentPath = "/swagger/{documentName}/swagger.json"; o.TransformToExternalPath = (internalUiRoute, _) => "/pie" + internalUiRoute; }); // ------------------------- // Test Endpoint // ------------------------- app.MapGet("/", () => "Hello from GB5 PIE (Product Intelligence Engine) in .NET 9!"); // ------------------------- // HTTPS & Authorization // ------------------------- app.UseAuthorization(); // ------------------------- // Run the Application // ------------------------- app.Run();