Выполнениие лабораторной работы на 5, трек 2.
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-23 21:13:27 +03:00
parent 65003b6119
commit f511c95962
82 changed files with 4784 additions and 13 deletions
+197
View File
@@ -0,0 +1,197 @@
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<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(8));
// Настройки читаются лениво из IConfiguration (после Build), поэтому тесты могут задавать их через UseSetting.
builder.Services.AddSingleton(sp => DatabaseSettings.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton(sp => AuthSessionOptions.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton(sp => CacheSettings.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddSingleton(sp => DiagnosticsSettings.From(sp.GetRequiredService<IConfiguration>()));
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<QueryCountingInterceptor>();
builder.Services.AddDbContext<MessengerDbContext>((sp, options) =>
{
options.UseNpgsql(sp.GetRequiredService<DatabaseSettings>().ConnectionString)
.UseSnakeCaseNamingConvention();
if (sp.GetRequiredService<DiagnosticsSettings>().Headers)
{
options.AddInterceptors(sp.GetRequiredService<QueryCountingInterceptor>());
}
});
builder.Services.AddSingleton<IPasswordHasher, Argon2PasswordHasher>();
builder.Services.AddSingleton<IMessageHistoryCache>(sp =>
{
var settings = sp.GetRequiredService<CacheSettings>();
return settings.Enabled
? new ValkeyMessageHistoryCache(settings, sp.GetRequiredService<ILogger<ValkeyMessageHistoryCache>>())
: new NullMessageHistoryCache();
});
builder.Services.AddAuthentication(BearerAuth.Scheme)
.AddScheme<AuthenticationSchemeOptions, SessionAuthenticationHandler>(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<MessengerDbContext>().Database.Migrate();
}
// Диагностика (только при DIAGNOSTIC_HEADERS=true): число SQL-команд EF Core за запрос — в заголовке X-Db-Queries.
if (app.Services.GetRequiredService<DiagnosticsSettings>().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<ILoggerFactory>().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<IExceptionHandlerFeature>()?.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<Program> в тестах.
public partial class Program { }