using Microsoft.AspNetCore.Diagnostics; using Messenger.Api.Endpoints; using Messenger.Api.Services; using Messenger.Api.Data; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authentication; // Режим для Docker HEALTHCHECK: в образе aspnet нет curl, поэтому проверку выполняет само приложение. if (args.Contains("--healthcheck")) { var port = Environment.GetEnvironmentVariable("APP_PORT") ?? "8080"; try { using var probe = new HttpClient { Timeout = TimeSpan.FromSeconds(2) }; var probeResponse = await probe.GetAsync($"http://127.0.0.1:{port}/health/live"); return probeResponse.IsSuccessStatusCode ? 0 : 1; } catch (Exception) { return 1; } } var builder = WebApplication.CreateBuilder(args); // SIGTERM: новые запросы перестают приниматься, активные получают не более 8 секунд (лимит задания — 10). builder.Services.Configure(options => options.ShutdownTimeout = TimeSpan.FromSeconds(8)); // Настройки читаются лениво из IConfiguration (после Build), поэтому тесты могут задавать их через UseSetting. builder.Services.AddSingleton(sp => DatabaseSettings.From(sp.GetRequiredService())); builder.Services.AddSingleton(sp => AuthSessionOptions.From(sp.GetRequiredService())); builder.Services.AddSingleton(sp => CacheSettings.From(sp.GetRequiredService())); builder.Services.AddSingleton(sp => DiagnosticsSettings.From(sp.GetRequiredService())); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); builder.Services.AddDbContext((sp, options) => { options.UseNpgsql(sp.GetRequiredService().ConnectionString) .UseSnakeCaseNamingConvention(); if (sp.GetRequiredService().Headers) { options.AddInterceptors(sp.GetRequiredService()); } }); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => { var settings = sp.GetRequiredService(); return settings.Enabled ? new ValkeyMessageHistoryCache(settings, sp.GetRequiredService>()) : new NullMessageHistoryCache(); }); builder.Services.AddAuthentication(BearerAuth.Scheme) .AddScheme(BearerAuth.Scheme, null); builder.Services.AddAuthorization(); builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower; options.SerializerOptions.Converters.Add(new UtcDateTimeOffsetJsonConverter()); options.SerializerOptions.UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Disallow; options.SerializerOptions.RespectNullableAnnotations = true; // Web-настройки по умолчанию включают регистронезависимое сопоставление имён: контракт его не допускает. options.SerializerOptions.PropertyNameCaseInsensitive = false; }); var app = builder.Build(); using (var scope = app.Services.CreateScope()) { scope.ServiceProvider.GetRequiredService().Database.Migrate(); } // Диагностика (только при DIAGNOSTIC_HEADERS=true): число SQL-команд EF Core за запрос — в заголовке X-Db-Queries. if (app.Services.GetRequiredService().Headers) { app.Use(async (context, next) => { var counter = new QueryCounter(); context.Items[QueryCountingInterceptor.ItemKey] = counter; context.Response.OnStarting(() => { context.Response.Headers["X-Db-Queries"] = Volatile.Read(ref counter.Count).ToString(); return Task.CompletedTask; }); await next(); }); } app.Use(async (context, next) => { var requestId = Guid.NewGuid().ToString(); context.Items["request_id"] = requestId; context.Response.Headers["X-Request-Id"] = requestId; await next(); }); // Лог запроса: метод, путь, статус, время, request_id. Тело и query не логируются. app.Use(async (context, next) => { var logger = context.RequestServices.GetRequiredService().CreateLogger("Messenger.Requests"); var started = System.Diagnostics.Stopwatch.GetTimestamp(); try { await next(); } finally { logger.LogInformation( "{Method} {Path} -> {Status} in {ElapsedMs:0.0} ms (request_id={RequestId})", context.Request.Method, context.Request.Path.Value, context.Response.StatusCode, System.Diagnostics.Stopwatch.GetElapsedTime(started).TotalMilliseconds, context.Items["request_id"]); } }); app.UseExceptionHandler(errorApp => errorApp.Run(context => { // В Development ошибки чтения запроса приходят исключением: сохраняем их 400/415 вместо 500. var error = context.Features.Get()?.Error; if (error is BadHttpRequestException { StatusCode: 400 or 415 } badRequest) { var (code, message) = badRequest.StatusCode == 415 ? ("unsupported_media_type", "Требуется Content-Type: application/json") : ("invalid_request", "Некорректный запрос"); return ApiErrors.Error(context, badRequest.StatusCode, code, message).ExecuteAsync(context); } // PostgreSQL недоступен или перегружен: ограниченный ответ 503 без внутренних деталей (стек и SQL только в логе). if (DependencyFailures.IsDatabaseUnavailable(error)) { return ApiErrors.Error(context, 503, "unavailable", "Сервис временно недоступен").ExecuteAsync(context); } return ApiErrors.Error(context, 500, "internal_error", "Внутренняя ошибка сервера").ExecuteAsync(context); })); // Пустые ответы 400/404/415 (ошибки привязки, неизвестный маршрут) получают стандартное тело ошибки. app.UseStatusCodePages(context => { var http = context.HttpContext; var (code, message) = http.Response.StatusCode switch { 400 => ("invalid_request", "Некорректный запрос"), 404 => ("not_found", "Объект не найден"), 415 => ("unsupported_media_type", "Требуется Content-Type: application/json"), _ => ("internal_error", "Ошибка запроса") }; return ApiErrors.Error(http, http.Response.StatusCode, code, message).ExecuteAsync(http); }); // Аутентификация (Bearer) выполняется до выбора обработчика и разбора тела: 401 приоритетнее 400/404. app.UseAuthentication(); app.UseAuthorization(); app.MapGet("/health/live", () => { return Results.Ok(new { status = "ok" }); }); // Готовность = API может обслуживать обязательный синхронный путь, а он требует PostgreSQL. app.MapGet("/health/ready", async (HttpContext context, MessengerDbContext db) => { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); timeout.CancelAfter(TimeSpan.FromSeconds(2)); try { return await db.Database.CanConnectAsync(timeout.Token) ? Results.Ok(new { status = "ok" }) : ApiErrors.Error(context, 503, "unavailable", "База данных недоступна"); } catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested) { return ApiErrors.Error(context, 503, "unavailable", "База данных недоступна"); } }); app.MapUserEndpoints(); app.MapAuthEndpoints(); app.MapChatEndpoints(); app.MapMessageEndpoints(); app.Lifetime.ApplicationStarted.Register(() => app.Logger.LogInformation("Messenger API started")); app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("SIGTERM received: shutting down, new requests are no longer accepted")); app.Lifetime.ApplicationStopped.Register(() => app.Logger.LogInformation("Messenger API stopped")); app.Run(); return 0; // Делает Program доступным для WebApplicationFactory в тестах. public partial class Program { }