using MessengerApi.Configuration.Sources.Environment; using MessengerBroker.Configuration.Model; using MessengerBroker.Factories; using MessengerBroker.Handlers; using MessengerBroker.Handlers.Endpoint; using MessengerBroker.Model.Http; using MessengerBroker.Models.Scoped; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.EntityFrameworkCore; using System.Net; namespace MessengerBroker { public class Program { public static void Main(string[] args) { BrokerConfiguration configuration = null; try { configuration = new BrokerConfiguration(new EnvironmentConfigurationSource()); } catch (Exception ex) { Console.WriteLine("Can't load settings.", ex); throw; } var builder = WebApplication.CreateBuilder(args); builder.Services.AddMemoryCache(); builder.Services.AddSingleton(); builder.Services.AddSingleton(configuration); builder.Services.AddSingleton(); builder.Services.AddSingleton((sp) => { return new MessengerApi.Factories.DbContextFactory(configuration.ApiPersistenceConfiguration); }); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); // Authentication. builder.Services .AddAuthentication("Bearer") .AddScheme("Bearer", null); // Proxy registration to forward real client IPs. builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; foreach (var proxy in configuration.Proxies) { options.KnownProxies.Add(IPAddress.Parse(proxy)); } }); var app = builder.Build(); // DB Migrations using (var ctx = app.Services.GetRequiredService().CreateDbContext()) { var migrationLogger = app.Services.GetRequiredService(); try { if (ctx.Database.GetPendingMigrations().Any()) { migrationLogger.Info("Applying migrations."); ctx.Database.Migrate(); } else { migrationLogger.Info("No migrations pending."); } } catch (Exception ex) { migrationLogger.Error("Can't run migrations successfully.", ex); throw; } } //// Housekeeping. //if (configuration.HousekeepingEnabled) //{ // _ = Task.Run(async () => // { // while (true) // { // await app.Services.GetService().RemoveOldMessages(); // await Task.Delay(TimeSpan.FromMinutes(1)); // } // }); //} //// Run pull sync from masters. //_ = Task.Run(async () => //{ // var cts = new CancellationTokenSource(); // var handler = app.Services.GetService(); // foreach (var master in settings.Masters) // { // _ = handler.BeginSyncingWithMaster(master, cts.Token); // } //}); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseForwardedHeaders(); app.MapGet("/users", async (UsersEndpointHandler handler) => { var response = await handler.GetUsers(); return Results.Json(response); }); app.MapGet("/messages", async ( MessagesEndpointHandler handler, [AsParameters] Messages.MessagesRequest request) => { var response = await handler.GetMessages(request); return Results.Json(response); }); app.Run(); } } }